Skip to content

refactor: trim redundant optimizations from the perf PR#3928

Open
t3dotgg wants to merge 2 commits into
t3code/performance-fixesfrom
t3code/performance-fixes-trim
Open

refactor: trim redundant optimizations from the perf PR#3928
t3dotgg wants to merge 2 commits into
t3code/performance-fixesfrom
t3code/performance-fixes-trim

Conversation

@t3dotgg

@t3dotgg t3dotgg commented Jul 13, 2026

Copy link
Copy Markdown
Member

Follow-up to #3825, based on that branch so the diff shows only the delta. Drops the pieces of the perf PR whose complexity isn't justified by a measurable win, while keeping every hot-path fix (aggregate-indexed replay, bounded shell catch-up, incremental projections, O(append) reducer, skip-persist-while-running, debounced draft serialization, hover prewarm, shared activity ordering cache).

What's trimmed

Timeline k-way merge → back to concat + toSorted (~45 lines). V8's sort is TimSort, which is near-linear on nearly-sorted input — and this input is three already-sorted arrays concatenated. The derivation also runs behind a useMemo in ChatView, so it fires per event, not per render. The PR retained the toSorted fallback path regardless, so the merge was a second implementation of the same ordering. The real win in session-logic.ts — the shared orderActivities cache that stops four derivations re-sorting the full activity history — is kept.

useDesktopLocalBootstraps: equality bail instead of a module-global store (~40 lines). There are exactly two consumers (Sidebar, CommandPalette), so collapsing two 2s intervals into one shared refcounted poller saves nothing real. The actual fix — not re-rendering when the topology is unchanged — now lives inside the original hook as setBootstraps(prev => bootstrapsEqual(prev, next) ? prev : next).

Hover prewarm: dead injection params removed. setTimeoutFn/clearTimeoutFn were copied from the jump-hint controller's pattern but nothing passes them — the component uses defaults and the tests use fake timers. The controller and its tests are otherwise kept as-is.

Composer partialize: per-draft WeakMap cache dropped (~17 lines). Two mechanisms addressed the same keystroke path; createDebouncedJsonStorage (kept) removes the per-keystroke JSON.stringify, which was the dominant cost. What remains without the cache is shallow-cloning small context arrays for retained drafts — not worth a second caching layer unless measured otherwise.

Verification

  • pnpm run typecheck clean
  • Sidebar.logic, composerDraftStore, session-logic test files: 193 passed
  • pnpm run lint: same 30 pre-existing warnings as the base branch, none introduced

🤖 Generated with Claude Code

Note

Remove redundant optimizations from perf-related code in sidebar, draft store, and timeline

  • Removes injectable timer functions from createSidebarHoverPrewarmController in Sidebar.logic.ts, using global setTimeout/clearTimeout directly.
  • Removes the WeakMap draft cache (partializedDraftCache) from composerDraftStore.ts; partialized drafts are now recomputed on every call.
  • Replaces shared useSyncExternalStore-based polling in useDesktopLocalBootstraps.ts with per-instance useState/useEffect intervals; reference equality is preserved when topology is unchanged.
  • Simplifies deriveTimelineEntries in session-logic.ts by removing the k-way merge path and always using toSorted on the concatenated rows.

Macroscope summarized bec10f9.


Note

Low Risk
Simplifications with no auth or data-model changes; the only behavioral nuance is two independent bootstrap poll intervals instead of one shared poller, which the authors judged negligible for two consumers.

Overview
Follow-up cleanup that removes complexity from the recent perf work without undoing the meaningful hot-path wins (debounced draft persistence, hover prewarm, shared activity ordering cache, etc.).

deriveTimelineEntries in session-logic.ts no longer uses a custom k-way merge over three sorted arrays; it concatenates and toSorted by createdAt instead (~45 lines removed).

useDesktopLocalBootstraps drops the module-global useSyncExternalStore refcounted poller. Each mount now runs its own 2s interval and only updates state when bootstrapsEqual says the topology changed (Sidebar + Command Palette = two pollers).

Composer draft partialize no longer keeps a per-draft WeakMap cache; unchanged drafts are recomputed on each partialization, relying on createDebouncedJsonStorage for the heavy cost.

createSidebarHoverPrewarmController no longer accepts injectable timer functions; it uses global setTimeout / clearTimeout and ReturnType<typeof setTimeout> for the handle type. Sidebar hover prewarm behavior is unchanged; a comment in Sidebar.tsx is clarified.

Reviewed by Cursor Bugbot for commit bec10f9. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • Bug Fixes

    • Improved timeline ordering by consistently sorting entries by creation time.
    • Improved draft persistence reliability by recalculating saved draft data.
    • Improved desktop connection state updates while avoiding unnecessary refreshes.
  • Performance

    • Refined sidebar hover preloading behavior.
    • Reduced unnecessary updates while monitoring desktop connection bootstraps.
  • Documentation

    • Clarified inline documentation for sidebar hover behavior.

Drops the pieces whose cost isn't justified by a measurable win, keeping
every hot-path fix:

- Timeline k-way merge: revert to concat+toSorted. TimSort is near-linear
  on this nearly-sorted input, and the derivation already runs behind a
  useMemo; the PR kept the toSorted fallback anyway, so the merge was a
  second implementation of the same ordering.
- useDesktopLocalBootstraps: keep the equality bail (the actual fix for
  per-tick re-renders) inside the existing hook instead of a module-global
  store + refcounted shared interval for two consumers.
- Hover prewarm controller: remove the unused setTimeoutFn/clearTimeoutFn
  injection params (neither the component nor the tests pass them).
- Composer partialize: drop the per-draft WeakMap cache. Debounced JSON
  serialization already removed the keystroke-path cost; the remaining
  shallow clones are too small to warrant a second caching layer.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The changes update four web behaviors: sidebar hover timer handling, composer draft persistence, desktop bootstrap polling, and session timeline ordering.

Changes

Sidebar hover prewarm

Layer / File(s) Summary
Global hover timer scheduling
apps/web/src/components/Sidebar.logic.ts, apps/web/src/components/Sidebar.tsx
The prewarm controller uses global timer functions and ReturnType<typeof setTimeout>, while the related comment describes delegated pointerover wiring.

Composer draft persistence

Layer / File(s) Summary
Per-draft partialization
apps/web/src/composerDraftStore.ts
Draft persistence removes the WeakMap cache and recomputes each draft’s partialized state.

Desktop bootstrap polling

Layer / File(s) Summary
Per-hook bootstrap polling
apps/web/src/connection/useDesktopLocalBootstraps.ts
The hook uses local state and an effect-based interval, retaining the previous array reference when bootstrap topology is unchanged.

Timeline ordering

Layer / File(s) Summary
Unified timeline sorting
apps/web/src/session-logic.ts
Timeline derivation removes per-source sortedness checks and k-way merging, then sorts concatenated entries by createdAt.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Poem

I’m a rabbit with timers tucked neatly away,
Sorting the timeline at the close of the day.
Drafts bloom fresh, caches hop out of sight,
Bootstraps poll softly through morning and night.
Four little changes, all tidy and bright!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title accurately summarizes the PR as a cleanup that removes redundant optimizations from the perf work.
Description check ✅ Passed The description clearly explains what changed, why, and includes verification, even though it doesn't use the template headings exactly.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch t3code/performance-fixes-trim

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

@github-actions github-actions Bot added vouch:trusted PR author is trusted by repo permissions or the VOUCHED list. size:L 100-499 changed lines (additions + deletions). labels Jul 13, 2026
@t3dotgg t3dotgg marked this pull request as ready for review July 13, 2026 05:10

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit c12e50d. Configure here.

Comment thread apps/web/src/connection/useDesktopLocalBootstraps.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
apps/web/src/connection/useDesktopLocalBootstraps.ts (1)

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

Doc comment is stale — no longer describes actual behavior.

The JSDoc still claims "so every renderer consumer reads the same topology", but the rewrite moved topology state and polling from a shared store into per-hook useState/useEffect. Each hook instance now independently reads readDesktopSecondaryBootstraps() on its own interval and keeps its own reference via bootstrapsEqual, so multiple consumers no longer share a single topology or reference — they poll and settle independently. Update the comment to reflect the new per-hook polling model.

📝 Suggested doc fix
- * each poll returns a fresh array, so the previous reference is kept when the
- * topology is unchanged to avoid re-rendering consumers every tick. Use this
- * instead of polling the bridge ad hoc so every renderer consumer reads the
- * same topology.
+ * each poll returns a fresh array, so the previous reference is kept when the
+ * topology is unchanged to avoid re-rendering this consumer every tick. Each
+ * call to this hook polls independently (no shared subscription), so use it
+ * per consumer rather than relying on a shared/synchronized topology.
 */
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/web/src/connection/useDesktopLocalBootstraps.ts` around lines 32 - 36,
Update the JSDoc above the desktop bootstrap hook to describe its current
per-hook useState/useEffect polling behavior, including that each hook
independently calls readDesktopSecondaryBootstraps() and retains its reference
via bootstrapsEqual. Remove the claim that renderer consumers share one topology
or reference.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/web/src/connection/useDesktopLocalBootstraps.ts`:
- Around line 37-53: Replace the per-instance useState and polling in
useDesktopLocalBootstraps with a shared external snapshot/store so all consumers
read the same bootstrap list. Centralize polling and deduplicate updates using
bootstrapsEqual, then have the hook subscribe to that store and return its
current snapshot while preserving cleanup behavior.

---

Nitpick comments:
In `@apps/web/src/connection/useDesktopLocalBootstraps.ts`:
- Around line 32-36: Update the JSDoc above the desktop bootstrap hook to
describe its current per-hook useState/useEffect polling behavior, including
that each hook independently calls readDesktopSecondaryBootstraps() and retains
its reference via bootstrapsEqual. Remove the claim that renderer consumers
share one topology or reference.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 49b1ca47-505e-49f9-a60e-dcf69f5fdb37

📥 Commits

Reviewing files that changed from the base of the PR and between 6b2f3f8 and c12e50d.

📒 Files selected for processing (5)
  • apps/web/src/components/Sidebar.logic.ts
  • apps/web/src/components/Sidebar.tsx
  • apps/web/src/composerDraftStore.ts
  • apps/web/src/connection/useDesktopLocalBootstraps.ts
  • apps/web/src/session-logic.ts
💤 Files with no reviewable changes (1)
  • apps/web/src/composerDraftStore.ts

Comment thread apps/web/src/connection/useDesktopLocalBootstraps.ts
macroscopeapp[bot]
macroscopeapp Bot previously approved these changes Jul 13, 2026
@macroscopeapp

macroscopeapp Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Approvability

Verdict: Approved

This refactor removes optimization complexity (caching, shared polling, k-way merge) in favor of simpler implementations. The changes are purely deletions and simplifications with no functional behavior changes - only performance trade-offs where simplicity was preferred over micro-optimizations.

You can customize Macroscope's approvability policy. Learn more.

Addresses review: readDesktopSecondaryBootstraps (bridge IPC) now runs
before the state update instead of inside the updater, which React may
invoke more than once. Doc comment no longer claims a shared topology
snapshot across consumers.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@macroscopeapp macroscopeapp Bot dismissed their stale review July 13, 2026 05:22

Dismissing prior approval to re-evaluate bec10f9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L 100-499 changed lines (additions + deletions). vouch:trusted PR author is trusted by repo permissions or the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant