Skip to content

perf(ui): memoize sidebar row projection at its owner - #160876

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-sidebar-row-projection-memo
Sep 30, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-sidebar-row-projection-memo

Conversation

@steipete

@steipete steipete commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: the Control UI sidebar re-projects every session row on every sidebar update, including unrelated menu, hover, footer, and presence updates. On a 300-session roster that is ~77 ms of main-thread CPU per cold /chat load and ~16 ms per session switch.

User Impact

User impact: cold /chat loads and session switches spend less main-thread time on sidebar projection: −53% per cold load (~77 → ~36 ms) and −37% per switch (~16 → ~10 ms). Unrelated sidebar updates no longer re-project rows. No visible behavior change.

Why This Change Was Made

The navigation element that owns the sidebar projection now memoizes each stage (navigation state, rows, catalogs, sections, Home) keyed by snapshot identities and explicit revisions. Every live input the per-row callbacks read (attention, outbox/drafts, sessions-store facts, projection state, locale) got an explicit invalidation source instead of time- or poll-based freshness.

Problem detail, root cause, change, and growth

The Control UI sidebar rebuilt its whole session projection on every sidebar update, whatever had changed: navigation state (filter and sort of the roster), the row forest (projectSidebarAgentSessionRows → archive visibility → projectSessionTree → per-row toSidebarSession), catalogs, zoned sections, and the Home row. That included updates from unrelated menus, footer state, hover and presence. On a 300-session roster, the production-bundle profile attributed ~77 ms of main-thread CPU per cold /chat load and ~16 ms per session switch to these projections, spread thinly across per-row helpers. Micro-optimizing those helpers would not help; the lever is not recomputing when the inputs are unchanged.

Root cause

AppSidebarSessionNavigationElement owns the projection, but AppSidebar.willUpdate() rebuilt it unconditionally and held the result only for one update. Several live inputs had no identity a cache could key on: the attention resolver was recreated every update; outbox and draft badges came from stable call-time callbacks, backed by a manual requestUpdate() poke from the shell; sessions-store facts (PR summary, prepared work sessions, deletion and archive visibility) had no revision; and several collections were mutated in place. The Home row separately re-ran archive visibility and tree projection on every render and in updated().

Change

One owner and staged memos. The navigation element owns memos for navigation state, rows, catalogs, zoned sections, and one Home memo per agent. Each stage compares a slot tuple with Object.is and recomputes only when a slot or its upstream stage value changes. A stage lists only the inputs its upstream value does not already key. The per-update cache and its overrides in AppSidebar are deleted. Stage inputs and projection bodies live in sidebar-projection-memo.ts next to the owner, which keeps the navigation module under its line cap. There is no second projection path.

Every live input now has an explicit invalidation source (nothing is time- or poll-based):

  • Session data: sessionResultsByAgent, pendingCatalogArchives, visibleSessionLimits, and rosterVisibleSessionLimits are replaced immutably instead of mutated in place.
  • Sessions store: one publication revision, bumped where the store notifies subscribers.
  • Attention: SessionAttentionController owns a revision bumped by question-prompt changes, overlay approval changes, Gateway resync, and the agent-status expiry timer, which keeps its deliberate +1 ms guard. createResolver() is memoized by that revision.
  • Outbox and drafts: the shell passes the outbox snapshot (storedOutboxes) as a sidebar property, and its identity changes when the outbox publishes. This replaces the outboxAttentionCountForSession/hasSessionDraft callbacks and the manual sidebar poke.
  • Projection state: SidebarSessionProjection revisions cover created order (only when keys are added), sticky membership, and child expansion. Held subtitles get one earliest-deadline timer, cleared on disconnect, so a replacement deferred by the 2 s display floor lands at its deadline instead of waiting for an unrelated update.
  • Locale: i18n.getLocale() is a navigation slot, since row labels are translated.

The roster child element now re-renders with its mutable host (selection, menus, drag, presence) through hasChanged on host. Before, it re-rendered on every sidebar update only because sections was a fresh array each time.

Route switches still run two full row projections: first for the route key, then for the lineage publication, which can change row fields and structure. An active-flags-only post-pass cannot safely replace that structural invalidation, so none was added.

Production code grows by 286 net lines. The navigation owner shrinks by 17. The new stage module is 250 lines, about 110 of which are the existing navigation and section projection bodies moved out of the owner. Projection revisions and the subtitle deadline add ~59, the attention revision ~23, the sessions revision ~7, and immutable publications ~7. The AppSidebar cache and callback removal saves 44. The growth is the explicit slot list for ~25 live inputs; the alternative (time-based freshness or deep comparison) was rejected.

Behavior preserved

Grouping, catalogs, archive and deletion visibility, attention summaries, child loading and expansion, show-more, organizer drag/drop, pinned rows, owner filters, roster and chip modes, the Home row, hovercards, narration, and PR indicators behave as before. No config options, dependencies, or Gateway changes.

Evidence

Setup: scratch Playwright rig against the production bundle (mocked Gateway, 300-session roster, Chromium, CPU throttle 1). Base 632b150d462f vs this change, run back-to-back on the same host. Sampled inclusive CPU per trace, source-mapped, median of 5 traces.

Projection CPU base after Δ
cold /chat: rows (projectSidebarAgentSessionRows) 50.9 ms 26.8 ms −47%
cold /chat: Home (projectSidebarHomeSession) 19.4 ms 5.6 ms −71%
cold /chat: navigation state 7.0 ms 3.3 ms −53%
cold /chat total ~77 ms ~36 ms −53%
4 switches: rows 41.9 ms 30.8 ms −26%
4 switches: Home 19.3 ms 8.6 ms −55%
4 switches: navigation state 4.2 ms 1.5 ms −64%
4 switches total ~65 ms ~41 ms −37% (≈16 → 10 ms/switch)

Slot evaluation costs about 0.5 ms per cold load (navigation inputs) plus ~0.2 ms (resolver check).

Page-level medians: cold /chat (7 iterations) script 276 → 255 ms and task 1,350 → 1,241 ms. First sidebar row 1,032 → 1,024 ms (unchanged; in both builds it usually lands in the same long task as the transcript tail). Switch task 1,824 → 1,750 ms, switch median 441 → 435 ms. Style and layout work counters are unchanged (switch styleEls ≈21.8k, layoutObjs ≈12.5k in both), as expected for a JS-only change. The host ran at load ~50, so wall-clock deltas are within noise; the attributed CPU is the reliable signal.

Projection invocation counts (300 rows, Lit lifecycle kept, DOM suppressed): initial setup 6 → 2, 20 unrelated updates 20 → 0, 4 route switches 12 → 8. Total 38 → 10 full row projections.

  • Regression ui/src/components/app-sidebar.projection-memo.test.ts (5 tests, mounted sidebar, spies on the exported projection functions, no production test hooks). Unrelated updates reuse the projection. Route, list, sort, show-cron/system, status and owner filters, agent selection, question and approval attention, agent-status expiry, outbox/draft snapshots, PR summary, archive lifecycle, catalogs, hidden catalogs, child loading, and Home row changes each recompute and render the change. Roster selection and menus update without re-projection. Held subtitles swap at their deadline without re-projecting rows. Fails on base (four unrelated updates → four projections). Cost: ~2.6 s test time locally (node scripts/run-vitest.mjs <file> --maxWorkers=1), 3.45 s runner wall on Testbox.
  • Testbox tbx_01m3n6hbd050gjt0c8bmwc184h (blacksmith-testbox, via scripts/crabbox-wrapper.mjs): 51 sidebar/outbox/shell unit files, 1,122/1,122 passed. Sidebar browser tests 86/86. Sidebar e2e (27 files) 135/135. check-changed: typecheck core/UI/tests, tsgo boundary, line-cap and dead-export ratchets green. Its lint step flagged 5 findings in this change, fixed afterward, and the repo oxlint wrapper is clean on the changed files.
  • Earlier lease tbx_01m3n3913gbc43dkbe5588wq71: sidebar-roster.e2e failed its 8 px spacing assertion (measured 7.9999 px) on both base and branch. It passed on the later lease, so it is environmental, not caused by this change. sidebar-cached-list-stability.e2e needed Playwright's FFmpeg on the lease.
  • Final head 0cd53b77e50b on fresh Testbox leases: app-sidebar.projection-memo, app-sidebar.people, and app-sidebar.sessions tests 297/297 (tbx_01m3nbqma3wmb4gxh4ct9bfzk0); node scripts/check-changed.mjs green (tbx_01m3ncehbq8ag5xyb45wbjhkk0; format and lint scoped to exactly the 25 changed files).
  • Autoreview (Codex, max priority P2, local mode over the full change): scoped-clean, no findings.

The sidebar rebuilt navigation state, the row forest, catalogs, zoned
sections, and the Home row on every Lit update. The navigation element now
owns staged slot memos keyed by snapshot identities and explicit revisions:
attention, sessions-store publication, outbox snapshot, projection
membership/created order, and a held-subtitle deadline. Collections that were
mutated in place are replaced immutably.

Production bundle, 300-session roster: sidebar projection CPU per cold /chat
~77 -> ~36 ms; per session switch ~16 -> ~10 ms.
@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete enabled auto-merge (squash) September 29, 2026 01:45
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 29, 2026
@clawsweeper

clawsweeper Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 29, 2026, 9:25 PM ET / September 30, 2026, 01:25 UTC (Revision 2).

ClawSweeper review

What this changes

The Control UI sidebar reuses session navigation, row, catalog, section, and Home projections across updates, with explicit invalidation inputs and regression coverage.

Merge readiness

✅ Ready for maintainer review

Current main still rebuilds unchanged sidebar projections. The earlier menu-only PR closed without merging, so this broader candidate remains useful. The prior import-cycle finding is fixed, and this review found no actionable defect in the pinned head.

Priority: P2
Reviewed head: 7175b5d125bd736b7ecb73e9c51a71964a885442

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has direct browser performance measurements, focused regression coverage, and a repaired prior finding; its larger memo boundary merits normal maintainer review.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The changed sidebar projection owner was exercised through the production-bundle /chat UI in Chromium with a mocked Gateway and 300-session roster; the PR body reports lower projection CPU and fewer full-row projections after the change. The later commits adjust the host type contract. No stored-data format changes, so migration compatibility is not applicable.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The changed sidebar projection owner was exercised through the production-bundle /chat UI in Chromium with a mocked Gateway and 300-session roster; the PR body reports lower projection CPU and fewer full-row projections after the change. The later commits adjust the host type contract. No stored-data format changes, so migration compatibility is not applicable.
Evidence reviewed 9 items Current main still repeats projection work: The current-main sidebar builds navigation, rows, catalogs, and sections during every willUpdate.
One staged cache owner: The introduced memo compares explicit input slots, and the navigation element owns the stage instances.
Invalidation sources: Navigation inputs include session publication, created-order, attention-resolver, outbox-snapshot, and locale changes.
Findings None None.
Security None None.

How this fits together

The Control UI sidebar combines Gateway session lists with local attention, outbox, and view state. It projects session rows and sections for the sidebar renderer.

flowchart LR
 A[Gateway session lists] --> D[Sidebar projection memo]
 B[Attention and outbox snapshots] --> D
 C[View preferences] --> D
 D --> E[Session rows and sections]
 E --> F[Sidebar renderer]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +339, Tests +484. Total +823 across 25 files.

View PR surface stats
Area Files Added Removed Net
Source 16 522 183 +339
Tests 9 522 38 +484
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 25 1044 221 +823

Review metrics

Metric Value Why it matters
Production and test growth production +339, tests and test helpers +484 net lines The cache and invalidation design explains the growth; the PR body's +286 production figure predates the leaf host contract added after review.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #149874
Summary: The open menu-update report describes a narrower instance of this PR's repeated-projection problem; its earlier candidate closed without merging.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep one sidebar projection owner with explicit invalidation from the session, attention, outbox, and view-state publishers.

Do we have a high-confidence way to reproduce the issue?

Yes, at source level: current main rebuilds session projections during every sidebar update, including menu-only updates. The contributor supplies a concrete 300-session browser scenario; this review did not execute it.

Is this the best way to solve the issue?

Yes. Caching at the projection owner with publisher-backed invalidation addresses the repeated work while preserving one rendering path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 452c808d5b1b.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The changed sidebar projection owner was exercised through the production-bundle /chat UI in Chromium with a mocked Gateway and 300-session roster; the PR body reports lower projection CPU and fewer full-row projections after the change. The later commits adjust the host type contract. No stored-data format changes, so migration compatibility is not applicable.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: The measured improvement addresses bounded Control UI CPU work without evidence of an urgent user-workflow outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The changed sidebar projection owner was exercised through the production-bundle /chat UI in Chromium with a mocked Gateway and 300-session roster; the PR body reports lower projection CPU and fewer full-row projections after the change. The later commits adjust the host type contract. No stored-data format changes, so migration compatibility is not applicable.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed sidebar projection owner was exercised through the production-bundle /chat UI in Chromium with a mocked Gateway and 300-session roster; the PR body reports lower projection CPU and fewer full-row projections after the change. The later commits adjust the host type contract. No stored-data format changes, so migration compatibility is not applicable.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Patrick-Erichsen: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-29T01:53:37.686Z sha 0cd53b7 :: needs changes before merge. :: [P2] Extract a leaf host type to break the import cycle

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 30, 2026
@steipete
steipete merged commit 6f24d83 into main Sep 30, 2026
98 checks passed
@steipete
steipete deleted the steipete/perf-sidebar-row-projection-memo branch September 30, 2026 01:32
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 30, 2026
* perf(ui): memoize sidebar row projection at its owner

The sidebar rebuilt navigation state, the row forest, catalogs, zoned
sections, and the Home row on every Lit update. The navigation element now
owns staged slot memos keyed by snapshot identities and explicit revisions:
attention, sessions-store publication, outbox snapshot, projection
membership/created order, and a held-subtitle deadline. Collections that were
mutated in place are replaced immutably.

Production bundle, 300-session roster: sidebar projection CPU per cold /chat
~77 -> ~36 ms; per session switch ~16 -> ~10 ms.

* fix(ui): break sidebar projection memo import cycle

* fix(ui): align sidebar projection host signatures
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

app: web-ui App: web-ui P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant