Skip to content

The agent that grows with you

perf(desktop): memoize sidebar rows + status dots + artifact cells

Brooklyn Nicholson6fc01f8ab81c
diff --git a/apps/desktop/scripts/diag-overlay-sweep.mjs b/apps/desktop/scripts/diag-overlay-sweep.mjs
new file mode 100644
index 00000000000..bfb54fc1f3d
--- /dev/null
+++ b/apps/desktop/scripts/diag-overlay-sweep.mjs
@@ -0,0 +1,110 @@
+#!/usr/bin/env node
+// Full surface sweep: every overlay, every settings sub-page, every system overlay.
+// Read-only — navigates and clicks, never closes the app.
+import WebSocket from 'ws'
+
+const WS_URL = process.env.CDP_WS || 'ws://127.0.0.1:9222/devtools/page/6E095DBE024BD280C674D00023C01201'
+let msgId = 1
+
+function send(ws, method, params = {}) {
+ const id = msgId++
+ return new Promise((resolve, reject) => {
+ const handler = (data) => {
+ const msg = JSON.parse(data.toString())
+ if (msg.id === id) {
+ ws.off('message', handler)
+ msg.error ? reject(new Error(JSON.stringify(msg.error))) : resolve(msg.result)
+ }
+ }
+ ws.on('message', handler)
+ ws.send(JSON.stringify({ id, method, params }))
+ })
+}
+async function eval_(ws, expr) {
+ const r = await send(ws, 'Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true })
+ return r?.result?.value
+}
+async function sleep(ms) { return new Promise(r => setTimeout(r, ms)) }
+
+async function measure(ws, label, fn, settleMs = 300) {
+ await eval_(ws, `__RENDER_COUNTS__.start(); true`)
+ await fn(ws)
+ await sleep(settleMs)
+ const report = JSON.parse(await eval_(ws, `JSON.stringify(__RENDER_COUNTS__.report())`))
+ const totalRenders = report.reduce((s, c) => s + c.renders, 0)
+ const totalWasted = report.reduce((s, c) => s + c.wasted, 0)
+ const totalMs = report.reduce((s, c) => s + c.totalMs, 0)
+ const top = report.filter(c => c.wasted > 0).sort((a,b) => b.wasted - a.wasted).slice(0, 6)
+ console.log(`\n${label}`)
+ console.log(` ${totalRenders} renders · ${totalWasted} wasted · ${totalMs.toFixed(1)}ms`)
+ for (const c of top) console.log(` ${c.name}: ${c.renders}r / ${c.wasted}w / ${c.totalMs.toFixed(1)}ms`)
+ if (top.length === 0) console.log(` (clean)`)
+ return { label, totalRenders, totalWasted, totalMs }
+}
+
+async function nav(ws, hash) {
+ await eval_(ws, `window.location.hash = '#${hash}'; true`)
+}
+async function clickText(ws, text, tag='button') {
+ return eval_(ws, `
+ const el = Array.from(document.querySelectorAll('${tag}')).find(b => b.textContent?.trim() === ${JSON.stringify(text)})
+ if (el) { el.click(); true } else false
+ `)
+}
+
+async function main() {
+ const ws = new WebSocket(WS_URL)
+ await new Promise((res, rej) => { ws.on('open', res); ws.on('error', rej) })
+ await send(ws, 'Runtime.enable')
+ if (await eval_(ws, `typeof __RENDER_COUNTS__`) !== 'object') { console.error('counter not loaded'); process.exit(1) }
+
+ const results = []
+
+ // System overlays — open each, idle 2s (streaming underneath is the churn test)
+ for (const [label, route] of [
+ ['Artifacts', '/artifacts'],
+ ['Messaging', '/messaging'],
+ ['Cron', '/cron'],
+ ['Profiles', '/profiles'],
+ ['Agents', '/agents'],
+ ['Starmap', '/starmap'],
+ ['Webhooks', '/webhooks'],
+ ]) {
+ results.push(await measure(ws, `OVERLAY: ${label} (open + 2s idle)`, async (ws) => {
+ await nav(ws, route)
+ await sleep(2200)
+ }, 100))
+ await nav(ws, '/')
+ await sleep(300)
+ }
+
+ // Settings sub-pages — open settings, click each nav item, idle 1.5s on it
+ await nav(ws, '/settings')
+ await sleep(600)
+ for (const label of ['Model','Session','Appearance','Notifications','Providers','Gateway','Keybinds','API Keys','Plugins','Archived Chats','About']) {
+ results.push(await measure(ws, `SETTINGS: ${label} (1.5s idle)`, async (ws) => {
+ await clickText(ws, label)
+ await sleep(1500)
+ }, 100))
+ }
+ await nav(ws, '/')
+ await sleep(300)
+
+ // Messaging sub-tabs (platform detail) — click through if present
+ await nav(ws, '/messaging')
+ await sleep(800)
+ results.push(await measure(ws, 'MESSAGING: idle 2s w/ platform list', async (ws) => {
+ await sleep(2000)
+ }, 100))
+ await nav(ws, '/')
+ await sleep(300)
+
+ console.log('\n\n=== SUMMARY (wasted renders) ===')
+ console.log('Surface'.padEnd(48) + 'Renders'.padStart(9) + 'Wasted'.padStart(9) + 'ms'.padStart(9))
+ console.log('-'.repeat(75))
+ for (const r of results) {
+ console.log(r.label.padEnd(48) + String(r.totalRenders).padStart(9) + String(r.totalWasted).padStart(9) + r.totalMs.toFixed(1).padStart(9))
+ }
+ ws.close()
+}
+main().catch(e => { console.error(e); process.exit(1) })
diff --git a/apps/desktop/src/app/artifacts/index.tsx b/apps/desktop/src/app/artifacts/index.tsx
index 6660b15f595..2482405fb7b 100644
--- a/apps/desktop/src/app/artifacts/index.tsx
+++ b/apps/desktop/src/app/artifacts/index.tsx
@@ -1,5 +1,5 @@
import type * as React from 'react'
-import { useCallback, useEffect, useMemo, useState } from 'react'
+import { memo, useCallback, useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ZoomableImage } from '@/components/chat/zoomable-image'
@@ -96,7 +96,7 @@ type CellCtx = {
}
interface ArtifactColumn {
- Cell: (props: { artifact: ArtifactRecord; ctx: CellCtx }) => React.ReactElement
+ Cell: React.ComponentType<{ artifact: ArtifactRecord; ctx: CellCtx }>
bodyClassName: string
header: (filter: ArtifactFilter, a: Translations['artifacts']) => string
id: 'location' | 'primary' | 'session'
@@ -278,10 +278,12 @@ export function ArtifactsView({ setStatusbarItemGroup: _setStatusbarItemGroup, .
})
}, [])
- const cellCtx: CellCtx = {
- onOpen: openArtifact,
- onOpenChat: sessionId => openSession(sessionId, navigate)
- }
+ // Stable ctx: recreating it (or its onOpenChat closure) every render made
+ // every artifact cell re-render whenever the page did — and a link cell's
+ // async title fetch re-rendered the page repeatedly. openArtifact is already
+ // a useCallback; navigate is stable, so onOpenChat can be too.
+ const openChat = useCallback((sessionId: string) => openSession(sessionId, navigate), [navigate])
+ const cellCtx: CellCtx = useMemo(() => ({ onOpen: openArtifact, onOpenChat: openChat }), [openArtifact, openChat])
return (
<PageSearchShell
@@ -549,7 +551,7 @@ function ArtifactCellAction({
)
}
-function PrimaryCell({ artifact, ctx }: { artifact: ArtifactRecord; ctx: CellCtx }) {
+const PrimaryCell = memo(function PrimaryCell({ artifact, ctx }: { artifact: ArtifactRecord; ctx: CellCtx }) {
const isLink = artifact.kind === 'link'
const brand = isLink ? resolveBrandIcon(shortHostLabel(artifact.href)) : null
const Icon = brand ?? (isLink ? Link2 : FileText)
@@ -571,9 +573,9 @@ function PrimaryCell({ artifact, ctx }: { artifact: ArtifactRecord; ctx: CellCtx
</span>
</ArtifactCellAction>
)
-}
+})
-function LocationCell({ artifact }: { artifact: ArtifactRecord; ctx: CellCtx }) {
+const LocationCell = memo(function LocationCell({ artifact }: { artifact: ArtifactRecord; ctx: CellCtx }) {
const { t } = useI18n()
const isLink = artifact.kind === 'link'
const value = isLink ? hostPathLabel(artifact.value) : artifact.value
@@ -602,9 +604,9 @@ function LocationCell({ artifact }: { artifact: ArtifactRecord; ctx: CellCtx })
/>
</div>
)
-}
+})
-function SessionCell({ artifact, ctx }: { artifact: ArtifactRecord; ctx: CellCtx }) {
+const SessionCell = memo(function SessionCell({ artifact, ctx }: { artifact: ArtifactRecord; ctx: CellCtx }) {
return (
<ArtifactCellAction onClick={() => ctx.onOpenChat(artifact.sessionId)} title={artifact.sessionTitle}>
<span className="flex min-w-0 flex-col">
@@ -615,7 +617,7 @@ function SessionCell({ artifact, ctx }: { artifact: ArtifactRecord; ctx: CellCtx
</span>
</ArtifactCellAction>
)
-}
+})
const ARTIFACT_COLUMNS: readonly ArtifactColumn[] = [
{
diff --git a/apps/desktop/src/app/chat/session-status-dot.tsx b/apps/desktop/src/app/chat/session-status-dot.tsx
index 684b21e9927..09fb7773a87 100644
--- a/apps/desktop/src/app/chat/session-status-dot.tsx
+++ b/apps/desktop/src/app/chat/session-status-dot.tsx
@@ -1,6 +1,7 @@
import { useStore } from '@nanostores/react'
import { type Translations, useI18n } from '@/i18n'
+import { useStoreSelector } from '@/lib/use-session-slice'
import { cn } from '@/lib/utils'
import { $backgroundRunningSessionIds } from '@/store/composer-status'
import { $unreadFinishedSessionIds } from '@/store/session'
@@ -111,11 +112,15 @@ export function SessionStatusDot({ storedSessionId, session, branchStem, classNa
useStore($sessionColorById)
const color = sessionColorFor(session) ?? null
- const needsInput = useStore($attentionSessionIds).includes(storedSessionId)
- const isWorking = useStore($workingSessionIds).includes(storedSessionId)
- const isStalled = useStore($stalledSessionIds).includes(storedSessionId)
- const isUnread = useStore($unreadFinishedSessionIds).includes(storedSessionId)
- const hasBackground = useStore($backgroundRunningSessionIds).includes(storedSessionId)
+ // Per-session membership as booleans via useStoreSelector: these arrays tick
+ // on every stream delta (any session working/stalled/etc changes the array
+ // reference), but a given dot only repaints when ITS OWN membership flips.
+ // A plain useStore(array).includes(id) re-rendered every dot on every tick.
+ const needsInput = useStoreSelector($attentionSessionIds, ids => ids.includes(storedSessionId))
+ const isWorking = useStoreSelector($workingSessionIds, ids => ids.includes(storedSessionId))
+ const isStalled = useStoreSelector($stalledSessionIds, ids => ids.includes(storedSessionId))
+ const isUnread = useStoreSelector($unreadFinishedSessionIds, ids => ids.includes(storedSessionId))
+ const hasBackground = useStoreSelector($backgroundRunningSessionIds, ids => ids.includes(storedSessionId))
const dotState = sessionDotState({ hasBackground, isStalled, isUnread, isWorking, needsInput })
diff --git a/apps/desktop/src/app/chat/sidebar/session-row.tsx b/apps/desktop/src/app/chat/sidebar/session-row.tsx
index 051f8893d7a..fcaa8b19edf 100644
--- a/apps/desktop/src/app/chat/sidebar/session-row.tsx
+++ b/apps/desktop/src/app/chat/sidebar/session-row.tsx
@@ -1,4 +1,5 @@
import { useStore } from '@nanostores/react'
+import { memo } from 'react'
import type * as React from 'react'
import { ProfileTag } from '@/app/chat/profile-tag'
@@ -54,7 +55,7 @@ function formatAge(seconds: number, r: Translations['sidebar']['row']): string {
return unit === 'second' ? r.ageNow : `${value}${r[AGE_KEY[unit]]}`
}
-export function SidebarSessionRow({
+function SidebarSessionRowImpl({
session,
branchStem,
isPinned,
@@ -251,3 +252,32 @@ export function SidebarSessionRow({
</SessionContextMenu>
)
}
+
+// The sidebar re-renders on every stream tick ($sessions/$workingSessionIds
+// churn), and it stays mounted beneath every overlay — so an unmemoized row
+// re-rendered the whole list (and its Codicon/label/status-dot subtree) on each
+// delta, bleeding churn into Settings, Cron, Profiles, Artifacts, etc.
+//
+// The callback props (onArchive/onResume/…) are fresh closures every render by
+// design (they close over the row's session id), so a default memo never bails.
+// They're pure id-forwarders, though — identical behavior for a given row — so
+// the comparator deliberately ignores them and compares only the DATA that
+// changes what the row paints. A row whose session/selection/working/pin state
+// is unchanged now bails out, even while a sibling session streams.
+function rowPropsEqual(a: SidebarSessionRowProps, b: SidebarSessionRowProps): boolean {
+ return (
+ a.session === b.session &&
+ a.isPinned === b.isPinned &&
+ a.isSelected === b.isSelected &&
+ a.isWorking === b.isWorking &&
+ a.branchStem === b.branchStem &&
+ a.reorderable === b.reorderable &&
+ a.dragging === b.dragging &&
+ a.showProfile === b.showProfile &&
+ a.dragHandleProps === b.dragHandleProps &&
+ a.className === b.className &&
+ a.style === b.style
+ )
+}
+
+export const SidebarSessionRow = memo(SidebarSessionRowImpl, rowPropsEqual)