Skip to content

perf(renderer): gate WorktreeCardAgentsBody's send-target subscriptions - #7545

Merged
nwparker merged 1 commit into
mainfrom
nwparker/perf-agentsbody-send-target-subs
Jul 6, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/perf-agentsbody-send-target-subs

Conversation

@nwparker

@nwparker nwparker commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Part of a fresh adversarially-verified perf/memory audit (10 finders → 3-skeptic refute-by-default verify → synthesis). This was the highest-value survivor (severity: high), 3/3 skeptic votes, safe in-pattern fix.

1. Description

WorktreeCardAgentsBody is mounted once per worktree that's currently showing inline agent rows in the sidebar. It opened five separate whole-map Zustand subscriptions:

agentStatusByPaneKey, tabsByWorktree, terminalLayoutsByTabId,
ptyIdsByTabId, runtimePaneTitlesByTabId

Those five maps are read only inside the sendTargetsByPaneKey useMemo, which early-returns an empty Map whenever the send-target popover isn't targeting this worktree (!isAgentSendTargetModeActive). But subscriptions fire regardless of whether the value is used: two of these maps — runtimePaneTitlesByTabId and agentStatusByPaneKey — get their top-level reference replaced on every terminal-title change and every agent-status transition (the PTY OSC-title / status path). So in the normal state (popover closed), every mounted agent body across the whole sidebar re-rendered on every unrelated title/status write anywhere in the app.

Fix: collapse the five subscriptions into one useShallow selector (selectSendTargetInputs, extracted to its own module following the existing worktree-card-status-inputs.ts convention) that returns a shared frozen constant while the popover isn't targeting this card. Idle bodies then stay referentially equal and react only to their own agents/ack props; the selector subscribes fully the instant the popover targets this worktree.

2. Undeniable evidence + measurable improvement

  • Deterministic unit proof (committed, red→green — the honest, non-flaky evidence): worktree-card-send-target-inputs.test.ts asserts, via zustand/shallow, that:
    • popover closed → selector returns the same EMPTY_SEND_TARGET_INPUTS reference even after runtimePaneTitlesByTabId/agentStatusByPaneKey churn (→ useShallow skips the render);
    • popover targeting a different worktree → still the stable constant;
    • popover targeting this worktree → live map refs pass through, and the result shallow-changes only when a subscribed map ref actually changes (so the open popover still re-derives eligibility exactly as before).
  • Behavioral preservation: all 41 existing WorktreeCardAgents render tests (including the send-target suite) pass unchanged.
  • Metric: renders-per-unrelated-title/status-write for idle agent bodies drops from N → 0 (N = mounted agent bodies).

3. ELI5

Every little agent name-tag in the sidebar was listening for every terminal in the whole app to rename itself or change status, and redrawing itself each time — even though it only needed that information for the brief moment you open the "send to agent" menu. Now each name-tag ignores all that chatter until you actually open that menu on its card.

4. Trade-offs that regress the end experience

None material. The only behavior depending on those maps is the send-target popover, and the selector subscribes fully the instant the popover targets this worktree, so eligibility stays live while the menu is open. agentStatusEpoch (a cheap scalar) is deliberately left subscribed so stale-boundary freshness flips still re-derive. The one theoretical risk — a useShallow selector dropping a needed field — is covered by the unit test above and by the 41 passing render tests.

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 319f138e-1868-4f9b-81c9-954fafb0f269

📥 Commits

Reviewing files that changed from the base of the PR and between d191d1d8e962fd55c81d331c34fa03a68f70b70e and d124430.

📒 Files selected for processing (3)
  • src/renderer/src/components/sidebar/WorktreeCardAgents.tsx
  • src/renderer/src/components/sidebar/worktree-card-send-target-inputs.test.ts
  • src/renderer/src/components/sidebar/worktree-card-send-target-inputs.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/renderer/src/components/sidebar/worktree-card-send-target-inputs.test.ts
  • src/renderer/src/components/sidebar/worktree-card-send-target-inputs.ts
  • src/renderer/src/components/sidebar/WorktreeCardAgents.tsx

📝 Walkthrough

Walkthrough

This PR adds worktree-card-send-target-inputs.ts, which exports SendTargetInputsState, EMPTY_SEND_TARGET_INPUTS, and selectSendTargetInputs for worktree-scoped send-target input selection. WorktreeCardAgents.tsx now reads those inputs through useShallow instead of subscribing directly to five store maps, and passes the derived value into deriveRunningAgentSendTargets. A new Vitest suite covers inactive, active, and shallow-compare selector behavior.

Changes

Cohort / File(s) Summary
Selector module — worktree-card-send-target-inputs.ts New type, stable empty constant, and selector for gated send-target inputs.
Component integration — WorktreeCardAgents.tsx Uses the selector via useShallow and updates send-target derivation dependencies.
Tests — worktree-card-send-target-inputs.test.ts Verifies selector behavior for inactive, active, and shallow-equality cases.

Sequence Diagram(s)

sequenceDiagram
  participant WorktreeCardAgentsBody
  participant useAppStore
  participant selectSendTargetInputs
  participant deriveRunningAgentSendTargets

  WorktreeCardAgentsBody->>useAppStore: subscribe with useShallow(selectSendTargetInputs(s, worktreeId))
  useAppStore->>selectSendTargetInputs: evaluate against agentSendPopoverTargetMode
  selectSendTargetInputs-->>useAppStore: EMPTY_SEND_TARGET_INPUTS or live map refs
  useAppStore-->>WorktreeCardAgentsBody: sendTargetInputs
  WorktreeCardAgentsBody->>deriveRunningAgentSendTargets: deriveRunningAgentSendTargets(sendTargetInputs, worktreeId)
  deriveRunningAgentSendTargets-->>WorktreeCardAgentsBody: sendTargetsByPaneKey
Loading

Estimated code review effort: Medium

Related PRs: None identified.

Suggested labels: refactor, tests

Suggested reviewers: None identified.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed but does not follow the required template and omits Screenshots, Testing, AI Review Report, Security Audit, and Notes. Rewrite the PR description in the repo template and add the missing sections, including screenshots or 'No visual change', testing checklist, AI review, security audit, and notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main performance change in WorktreeCardAgentsBody.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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

Comment @coderabbitai help to get the list of available commands.

@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.

🧹 Nitpick comments (2)
src/renderer/src/components/sidebar/worktree-card-send-target-inputs.ts (2)

32-38: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated worktree-match predicate risks drift.

This gate (s.agentSendPopoverTargetMode?.worktreeId !== worktreeId) duplicates the exact condition computed independently in WorktreeCardAgents.tsx as isAgentSendTargetModeActive (agentSendPopoverTargetMode?.worktreeId === worktreeId). If the "is this worktree the active send target" rule ever needs an extra condition (e.g. checking status === 'open'), it's easy to update one site and miss the other, causing sendTargetInputs and isAgentSendTargetModeActive to disagree.

Consider extracting a shared predicate (e.g. isSendTargetPopoverActiveFor(mode, worktreeId)) used by both this selector and the component.

♻️ Proposed shared predicate
+export function isSendTargetPopoverActiveFor(
+  mode: SendTargetInputsState['agentSendPopoverTargetMode'],
+  worktreeId: string
+): boolean {
+  return mode?.worktreeId === worktreeId
+}
+
 export function selectSendTargetInputs(
   s: SendTargetInputsState,
   worktreeId: string
 ): RunningAgentTargetState {
-  if (s.agentSendPopoverTargetMode?.worktreeId !== worktreeId) {
+  if (!isSendTargetPopoverActiveFor(s.agentSendPopoverTargetMode, worktreeId)) {
     return EMPTY_SEND_TARGET_INPUTS
   }

And in WorktreeCardAgents.tsx:

-  const isAgentSendTargetModeActive = agentSendPopoverTargetMode?.worktreeId === worktreeId
+  const isAgentSendTargetModeActive = isSendTargetPopoverActiveFor(agentSendPopoverTargetMode, worktreeId)

17-23: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider Object.freeze on the shared empty singleton.

EMPTY_SEND_TARGET_INPUTS is returned as the shared reference for every idle WorktreeCardAgentsBody instance app-wide. Nothing currently mutates it, but freezing costs nothing and guards against a future accidental write silently corrupting state across every mounted card.

🛡️ Proposed fix
-export const EMPTY_SEND_TARGET_INPUTS: RunningAgentTargetState = {
+export const EMPTY_SEND_TARGET_INPUTS: RunningAgentTargetState = Object.freeze({
   agentStatusByPaneKey: {},
   tabsByWorktree: {},
   terminalLayoutsByTabId: {},
   ptyIdsByTabId: {},
   runtimePaneTitlesByTabId: {}
-}
+})

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: b087a0b4-8000-4caf-a3da-b8d2de4410b0

📥 Commits

Reviewing files that changed from the base of the PR and between 3826169 and d191d1d8e962fd55c81d331c34fa03a68f70b70e.

📒 Files selected for processing (3)
  • src/renderer/src/components/sidebar/WorktreeCardAgents.tsx
  • src/renderer/src/components/sidebar/worktree-card-send-target-inputs.test.ts
  • src/renderer/src/components/sidebar/worktree-card-send-target-inputs.ts

@nwparker
nwparker force-pushed the nwparker/perf-agentsbody-send-target-subs branch from d191d1d to 5cf7294 Compare July 6, 2026 08:33
WorktreeCardAgentsBody (mounted once per worktree showing inline agents)
opened five whole-map Zustand subscriptions — agentStatusByPaneKey,
tabsByWorktree, terminalLayoutsByTabId, ptyIdsByTabId,
runtimePaneTitlesByTabId. They're read ONLY inside the sendTargetsByPaneKey
memo, which early-returns unless the send-target popover targets this
worktree. Two of them (runtimePaneTitlesByTabId, agentStatusByPaneKey)
churn on every pane-title and agent-status write app-wide, so every mounted
agent body re-rendered on every unrelated terminal's title/status change.

Collapse the five into one useShallow selector (selectSendTargetInputs)
that returns a shared frozen constant while the popover isn't targeting this
card, so idle bodies stay referentially equal and stop reacting to the
churn — and subscribe fully the instant the popover is ours.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the nwparker/perf-agentsbody-send-target-subs branch from 5cf7294 to d124430 Compare July 6, 2026 08:39
@nwparker
nwparker merged commit dfc839f into main Jul 6, 2026
1 check passed
@nwparker
nwparker deleted the nwparker/perf-agentsbody-send-target-subs branch July 6, 2026 09:01
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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