perf(dashboard): stop re-sending repo icon data URLs on every republish (#11089)

* perf(dashboard): stop re-sending repo icon data URLs on every republish

#11012 put repo icons on the dashboard snapshot keyed by repoId. Image icons
are data URLs capped at MAX_REPO_ICON_DATA_URL_LENGTH (400KB) and every repo
contributing a card ships one, while the snapshot republishes up to 4x/sec
(PUBLISH_THROTTLE_MS = 250) for as long as the pop-out is open. Icons change
about never, so that structured-clones megabytes per second across the window
boundary for bytes the pop-out already has.

Publish the map only when it actually changed, comparing by reference since
icons come off immutable store repo records. The two paths where the pop-out
could be starting from nothing — it opened, or it mounted and asked — still
force a full send, so the retained copy can never be the only one.

The pop-out keeps the last map it was given when a republish omits the field.
An explicitly empty map still clears, so removing an icon works.

repoIconsByRepoId was already optional on DashboardSnapshot and
isDashboardRepoIcons already returns true for undefined, so the main-process
validator needed no change.

* fix(dashboard): keep repo icons in the main-process snapshot cache

The bridge now omits an unchanged repoIconsByRepoId from republishes, so the
cached snapshot main replays to a mounting pop-out could be icon-less, blanking
the board's repo glyphs until the forced publish landed. Carry the last map
into the cache; the forwarded payload is unchanged.

Also covers the forced full sends (open, reopen, snapshot request) that no test
exercised.

* test(dashboard): pin the icon omit on the throttled trailing republish

* fix(dashboard): keep the popout bridge effect off the react-doctor gate

The changed-code quality gate reports react-doctor findings that overlap
added lines, and effect-needs-cleanup spans the whole publish effect — so
this PR's edits inside it turned a pre-existing false positive into a red
static-analysis check. Hoisting the store subscriber leaves the effect
owning one disposable; behaviour is unchanged.

* docs(dashboard): correct why watchSnapshotInputs sits outside the effect

The effect owns four disposables (offOpenChanged, offRequested, the store
unsubscribe, and the trailing timer), not one. State the real reason the
subscribe is hoisted so nobody inlines it back and re-reds the gate.

* test(dashboard): pin that the bridge subscribes only while the pop-out is open

The lazy wiring exists so an enabled-but-closed pop-out costs nothing — a live
subscriber would rebuild a cross-worktree snapshot on unrelated store writes.
Nothing pinned the unsubscribe on close.
This commit is contained in:
Brennan Benson
2026-07-28 16:00:22 -07:00
committed by GitHub
parent 13c193a00a
commit 25da91d653
6 changed files with 356 additions and 29 deletions
+23
View File
@@ -144,6 +144,29 @@ describe('registerDashboardPopoutHandlers', () => {
expect(sendToTrustedMock).toHaveBeenCalledWith('dashboard:snapshotRequested', null)
})
it('replays the last repo icons when the cached snapshot omitted them', () => {
const popout = makeWindow(popoutSender)
getPopoutMock.mockReturnValue(popout)
const repoIconsByRepoId = { r1: { type: 'emoji', emoji: '🦑' } }
const publish = handlers.get('dashboard:publishSnapshot')!
publish({ sender: mainSender } as never, { ...SNAPSHOT, repoIconsByRepoId })
// A throttled republish drops the unchanged map — the popout on the wire
// still holds it, but one mounting now would have nothing to hold.
publish({ sender: mainSender } as never, { generatedAt: 2, cards: [] })
expect(popoutSender.send).toHaveBeenLastCalledWith('dashboard:snapshot', {
generatedAt: 2,
cards: []
})
handlers.get('dashboard:requestSnapshot')!({ sender: popoutSender } as never)
expect(popoutSender.send).toHaveBeenLastCalledWith('dashboard:snapshot', {
generatedAt: 2,
cards: [],
repoIconsByRepoId
})
})
it('reports open state only to the trusted main renderer', () => {
getPopoutMock.mockReturnValue(makeWindow(popoutSender))
expect(handlers.get('dashboard:getPopoutOpen')!({ sender: untrustedSender } as never)).toBe(
+8 -1
View File
@@ -70,7 +70,14 @@ export function registerDashboardPopoutHandlers(
) {
return
}
lastSnapshot = snapshot
// The renderer omits repoIconsByRepoId once it is unchanged, so carry the
// last map into the cache — a popout mounting mid-session is replayed this
// and has no icons of its own to retain. The live popout does, so what is
// forwarded stays as slim as the renderer sent it.
lastSnapshot =
snapshot.repoIconsByRepoId === undefined && lastSnapshot?.repoIconsByRepoId
? { ...snapshot, repoIconsByRepoId: lastSnapshot.repoIconsByRepoId }
: snapshot
getDashboardPopoutWindow()?.webContents.send('dashboard:snapshot', snapshot)
})
@@ -96,4 +96,48 @@ describe('useDashboardSnapshot', () => {
expect(startViewTransition).not.toHaveBeenCalled()
expect(result.current.cards[0].bucket).toBe('working')
})
// Why: the bridge stops re-sending repoIconsByRepoId on throttled republishes
// once it is unchanged, so the icons would disappear from the board on the
// very next tick if this window did not hold on to the last map it was given.
it('retains the last repo icons when a republish omits them', () => {
const icons = {
r1: { type: 'image' as const, src: 'data:image/png;base64,AAAA', source: 'upload' as const }
}
const { result } = renderHook(() => useDashboardSnapshot())
act(() => apply({ ...snapshot([card({})]), repoIconsByRepoId: icons }))
expect(result.current.repoIconsByRepoId).toEqual(icons)
act(() => apply(snapshot([card({ task: 'moved on' })])))
expect(result.current.repoIconsByRepoId).toEqual(icons)
expect(result.current.cards[0].task).toBe('moved on')
})
it('replaces retained icons when the bridge sends a new map', () => {
const first = {
r1: { type: 'image' as const, src: 'data:image/png;base64,AAAA', source: 'upload' as const }
}
const second = { r1: { type: 'emoji' as const, emoji: '🦑' } }
const { result } = renderHook(() => useDashboardSnapshot())
act(() => apply({ ...snapshot([card({})]), repoIconsByRepoId: first }))
act(() => apply({ ...snapshot([card({})]), repoIconsByRepoId: second }))
expect(result.current.repoIconsByRepoId).toEqual(second)
// An omitted map must retain the NEW icons, not resurrect the old ones.
act(() => apply(snapshot([card({})])))
expect(result.current.repoIconsByRepoId).toEqual(second)
})
// A repo whose icon was cleared must actually lose it — retention applies to
// an OMITTED map, never to an empty one.
it('honours an explicitly empty icon map', () => {
const icons = { r1: { type: 'emoji' as const, emoji: '🦑' } }
const { result } = renderHook(() => useDashboardSnapshot())
act(() => apply({ ...snapshot([card({})]), repoIconsByRepoId: icons }))
act(() => apply({ ...snapshot([card({})]), repoIconsByRepoId: {} }))
expect(result.current.repoIconsByRepoId).toEqual({})
})
})
@@ -35,9 +35,21 @@ function terminalDialogIsOpen(): boolean {
export function useDashboardSnapshot(): DashboardSnapshot {
const [snapshot, setSnapshot] = useState<DashboardSnapshot>(EMPTY_DASHBOARD_SNAPSHOT)
const columnSignatureRef = useRef('')
const retainedRepoIconsRef = useRef<DashboardSnapshot['repoIconsByRepoId']>(undefined)
useEffect(() => {
const apply = (next: DashboardSnapshot): void => {
const apply = (incoming: DashboardSnapshot): void => {
// The bridge omits repoIconsByRepoId on throttled republishes when it has
// not changed, rather than re-sending data URLs 4x/sec. Retain the last
// map we were given; the bridge always re-sends it when this window opens
// or asks, so the retained value can never be the only copy.
const next =
incoming.repoIconsByRepoId === undefined && retainedRepoIconsRef.current
? { ...incoming, repoIconsByRepoId: retainedRepoIconsRef.current }
: incoming
if (next.repoIconsByRepoId !== undefined) {
retainedRepoIconsRef.current = next.repoIconsByRepoId
}
const nextSignature = columnSignature(next)
const layoutChanged = nextSignature !== columnSignatureRef.current
columnSignatureRef.current = nextSignature
@@ -7,13 +7,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => ({
acknowledgeAgents: vi.fn(),
setActiveWorktree: vi.fn(),
subscribeStore: vi.fn(() => vi.fn()),
subscribeStore: vi.fn((_listener: (state: unknown, previousState: unknown) => void) => vi.fn()),
onRevealAgent: vi.fn(),
onAckAgent: vi.fn(),
onPopoutOpenChanged: vi.fn(),
onSnapshotRequested: vi.fn(),
getPopoutOpen: vi.fn(async () => false),
publishSnapshot: vi.fn(async () => undefined),
publishSnapshot: vi.fn(async (_snapshot: DashboardSnapshot) => undefined),
buildDashboardSnapshot: vi.fn(
(_state: unknown, now: number): DashboardSnapshot => ({ generatedAt: now, cards: [] })
),
offRevealAgent: vi.fn(),
offAckAgent: vi.fn(),
offPopoutOpenChanged: vi.fn(),
@@ -34,8 +37,15 @@ vi.mock('@/lib/activate-tab-and-focus-pane', () => ({
activateTabAndFocusPane: vi.fn()
}))
vi.mock('./build-dashboard-snapshot', () => ({
buildDashboardSnapshot: mocks.buildDashboardSnapshot
}))
import type { DashboardSnapshot } from '../../../../shared/dashboard-snapshot'
import type { RepoIcon } from '../../../../shared/repo-icon'
import {
dashboardSnapshotInputsChanged,
repoIconsUnchanged,
useDashboardPopoutBridge
} from './useDashboardPopoutBridge'
import type { DashboardSnapshotState } from './build-dashboard-snapshot'
@@ -66,26 +76,30 @@ function Harness({ enabled }: { enabled: boolean }): null {
return null
}
function installDashboardApi(): void {
mocks.onRevealAgent.mockReturnValue(mocks.offRevealAgent)
mocks.onAckAgent.mockReturnValue(mocks.offAckAgent)
mocks.onPopoutOpenChanged.mockReturnValue(mocks.offPopoutOpenChanged)
mocks.onSnapshotRequested.mockReturnValue(mocks.offSnapshotRequested)
;(window as unknown as { api: unknown }).api = {
dashboard: {
onRevealAgent: mocks.onRevealAgent,
onAckAgent: mocks.onAckAgent,
onPopoutOpenChanged: mocks.onPopoutOpenChanged,
onSnapshotRequested: mocks.onSnapshotRequested,
getPopoutOpen: mocks.getPopoutOpen,
publishSnapshot: mocks.publishSnapshot
}
}
}
describe('useDashboardPopoutBridge', () => {
let root: Root
let container: HTMLDivElement
beforeEach(() => {
vi.clearAllMocks()
mocks.onRevealAgent.mockReturnValue(mocks.offRevealAgent)
mocks.onAckAgent.mockReturnValue(mocks.offAckAgent)
mocks.onPopoutOpenChanged.mockReturnValue(mocks.offPopoutOpenChanged)
mocks.onSnapshotRequested.mockReturnValue(mocks.offSnapshotRequested)
;(window as unknown as { api: unknown }).api = {
dashboard: {
onRevealAgent: mocks.onRevealAgent,
onAckAgent: mocks.onAckAgent,
onPopoutOpenChanged: mocks.onPopoutOpenChanged,
onSnapshotRequested: mocks.onSnapshotRequested,
getPopoutOpen: mocks.getPopoutOpen,
publishSnapshot: mocks.publishSnapshot
}
}
installDashboardApi()
container = document.createElement('div')
root = createRoot(container)
})
@@ -105,6 +119,24 @@ describe('useDashboardPopoutBridge', () => {
expect(mocks.subscribeStore).not.toHaveBeenCalled()
})
// The whole lazy design exists so an enabled-but-closed pop-out costs nothing:
// a live subscriber would rebuild a cross-worktree snapshot on store writes.
it('subscribes to the store only while the pop-out is open', async () => {
await act(async () => root.render(<Harness enabled />))
expect(mocks.onPopoutOpenChanged).toHaveBeenCalledTimes(1)
expect(mocks.subscribeStore).not.toHaveBeenCalled()
await act(async () => mocks.onPopoutOpenChanged.mock.calls[0][0](true))
expect(mocks.subscribeStore).toHaveBeenCalledTimes(1)
const unsubscribe = mocks.subscribeStore.mock.results[0]?.value as () => void
await act(async () => mocks.onPopoutOpenChanged.mock.calls[0][0](false))
expect(unsubscribe).toHaveBeenCalledTimes(1)
})
it('ignores unrelated store writes while retaining every snapshot input', () => {
const previousState = makeSnapshotWatchState()
expect(dashboardSnapshotInputsChanged({ ...previousState }, previousState)).toBe(false)
@@ -154,3 +186,168 @@ describe('useDashboardPopoutBridge', () => {
expect(mocks.offSnapshotRequested).toHaveBeenCalledTimes(1)
})
})
describe('repoIconsUnchanged', () => {
const icon: RepoIcon = { type: 'image', src: 'data:image/png;base64,AAAA', source: 'upload' }
it('treats a first publish as changed so the pop-out always gets a map', () => {
expect(repoIconsUnchanged({ r1: icon }, null)).toBe(false)
})
it('matches on reference, not deep value, so an unchanged repo skips the resend', () => {
expect(repoIconsUnchanged({ r1: icon }, { r1: icon })).toBe(true)
// Why: a structurally identical but freshly allocated icon means the store
// record was rebuilt, so the pop-out's copy may genuinely be stale.
expect(repoIconsUnchanged({ r1: { ...icon } }, { r1: icon })).toBe(false)
})
it('detects an added, removed, or swapped repo', () => {
expect(repoIconsUnchanged({ r1: icon, r2: icon }, { r1: icon })).toBe(false)
expect(repoIconsUnchanged({ r1: icon }, { r1: icon, r2: icon })).toBe(false)
// Same size, different keys — a plain length check would miss this.
expect(repoIconsUnchanged({ r2: icon }, { r1: icon })).toBe(false)
})
it('handles repos with no icon', () => {
expect(repoIconsUnchanged({ r1: null }, { r1: null })).toBe(true)
expect(repoIconsUnchanged({ r1: icon }, { r1: null })).toBe(false)
expect(repoIconsUnchanged({}, {})).toBe(true)
})
})
describe('useDashboardPopoutBridge repo icon publishing', () => {
const icons: Record<string, RepoIcon> = {
r1: { type: 'image', src: 'data:image/png;base64,AAAA', source: 'upload' }
}
// Longer than PUBLISH_THROTTLE_MS, so the next store change publishes on the
// leading edge instead of parking on the trailing timer.
const PAST_THROTTLE_MS = 1_000
const WITHIN_THROTTLE_MS = 50
let root: Root
let now = 0
let nowSpy: ReturnType<typeof vi.spyOn>
beforeEach(() => {
vi.clearAllMocks()
now = 10_000
nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now)
mocks.buildDashboardSnapshot.mockImplementation((_state, at) => ({
generatedAt: at,
cards: [],
repoIconsByRepoId: icons
}))
installDashboardApi()
root = createRoot(document.createElement('div'))
})
afterEach(async () => {
vi.useRealTimers()
await act(async () => root.unmount())
nowSpy.mockRestore()
})
const lastPublished = (): DashboardSnapshot => mocks.publishSnapshot.mock.calls.at(-1)![0]
const setPopoutOpen = (open: boolean): void => {
act(() => mocks.onPopoutOpenChanged.mock.calls[0][0](open))
}
const notifySnapshotInputsChanged = (): void => {
const previousState = makeSnapshotWatchState()
act(() =>
mocks.subscribeStore.mock.calls[0][0](
{ ...previousState, agentStatusEpoch: 1 },
previousState
)
)
}
const notifyUnrelatedStoreWrite = (): void => {
const previousState = makeSnapshotWatchState()
act(() => mocks.subscribeStore.mock.calls[0][0]({ ...previousState }, previousState))
}
const mountAndOpen = async (): Promise<void> => {
await act(async () => root.render(<Harness enabled />))
setPopoutOpen(true)
}
it('sends the icon map on open, then omits it while it is unchanged', async () => {
await mountAndOpen()
expect(mocks.publishSnapshot).toHaveBeenCalledTimes(1)
expect(lastPublished().repoIconsByRepoId).toBe(icons)
now += PAST_THROTTLE_MS
notifySnapshotInputsChanged()
expect(mocks.publishSnapshot).toHaveBeenCalledTimes(2)
expect(lastPublished()).not.toHaveProperty('repoIconsByRepoId')
expect(lastPublished().generatedAt).toBe(now)
})
it('skips the republish when a store write touches no snapshot input', async () => {
await mountAndOpen()
expect(mocks.publishSnapshot).toHaveBeenCalledTimes(1)
// Past the throttle, so an ungated write would publish on the leading edge
// rather than silently parking on the trailing timer.
now += PAST_THROTTLE_MS
notifyUnrelatedStoreWrite()
expect(mocks.publishSnapshot).toHaveBeenCalledTimes(1)
})
// A burst collapses onto the trailing timer, so that edge carries most of the
// republishes this PR exists to slim down.
it('omits the icon map on the throttled trailing republish', async () => {
await mountAndOpen()
// Date.now stays spied — only the throttle's timer is faked.
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
now += WITHIN_THROTTLE_MS
notifySnapshotInputsChanged()
expect(mocks.publishSnapshot).toHaveBeenCalledTimes(1)
now += PAST_THROTTLE_MS
act(() => {
vi.advanceTimersByTime(PAST_THROTTLE_MS)
})
expect(mocks.publishSnapshot).toHaveBeenCalledTimes(2)
expect(lastPublished()).not.toHaveProperty('repoIconsByRepoId')
})
it('resends the icon map when the pop-out asks for a fresh snapshot', async () => {
await mountAndOpen()
now += PAST_THROTTLE_MS
notifySnapshotInputsChanged()
expect(lastPublished()).not.toHaveProperty('repoIconsByRepoId')
// A remounted pop-out has no retained map, so its request must be answered in full.
now += PAST_THROTTLE_MS
act(() => mocks.onSnapshotRequested.mock.calls[0][0]())
expect(lastPublished().repoIconsByRepoId).toBe(icons)
})
it('resends the icon map when the pop-out is reopened', async () => {
await mountAndOpen()
setPopoutOpen(false)
now += PAST_THROTTLE_MS
setPopoutOpen(true)
expect(mocks.publishSnapshot).toHaveBeenCalledTimes(2)
expect(lastPublished().repoIconsByRepoId).toBe(icons)
})
it('resends the icon map when an icon actually changes', async () => {
await mountAndOpen()
const nextIcons: Record<string, RepoIcon> = { r1: { type: 'emoji', emoji: '🦑' } }
mocks.buildDashboardSnapshot.mockImplementation((_state, at) => ({
generatedAt: at,
cards: [],
repoIconsByRepoId: nextIcons
}))
now += PAST_THROTTLE_MS
notifySnapshotInputsChanged()
expect(lastPublished().repoIconsByRepoId).toBe(nextIcons)
})
})
@@ -1,6 +1,7 @@
import { useEffect } from 'react'
import { useAppStore, type AppState } from '@/store'
import { activateTabAndFocusPane } from '@/lib/activate-tab-and-focus-pane'
import type { RepoIcon } from '../../../../shared/repo-icon'
import { buildDashboardSnapshot, type DashboardSnapshotState } from './build-dashboard-snapshot'
// Why: cap snapshot rebuilds during bursts of agent-status pings. The board is a
@@ -8,6 +9,31 @@ import { buildDashboardSnapshot, type DashboardSnapshotState } from './build-das
// rebuild off the hot path.
const PUBLISH_THROTTLE_MS = 250
/**
* Repo icons are the only unbounded field on the snapshot — an image icon is a
* data URL capped at MAX_REPO_ICON_DATA_URL_LENGTH (400KB), and every repo that
* contributes a card ships one. They change about never, but the snapshot
* republishes up to 4x/sec while the pop-out is open, so re-sending them was
* structured-cloning megabytes per second across the window boundary for bytes
* the pop-out already had.
*
* Compare by reference: icons come off immutable store repo records, so an
* unchanged repo yields the identical object.
*/
export function repoIconsUnchanged(
next: Record<string, RepoIcon | null>,
previous: Record<string, RepoIcon | null> | null
): boolean {
if (!previous) {
return false
}
const nextIds = Object.keys(next)
if (nextIds.length !== Object.keys(previous).length) {
return false
}
return nextIds.every((id) => id in previous && next[id] === previous[id])
}
type DashboardSnapshotWatchState = DashboardSnapshotState & Pick<AppState, 'agentStatusEpoch'>
export function dashboardSnapshotInputsChanged(
@@ -36,6 +62,18 @@ export function dashboardSnapshotInputsChanged(
)
}
/** Watches the store for snapshot-relevant writes. Lives outside the effect
* because react-doctor's effect-needs-cleanup false-positives on `subscribe`
* inside an effect body; the caller's cleanup does unsubscribe. */
function watchSnapshotInputs(onChanged: () => void): () => void {
return useAppStore.subscribe((state, previousState) => {
// Why: unrelated high-frequency store writes must not rebuild a cross-worktree snapshot.
if (dashboardSnapshotInputsChanged(state, previousState)) {
onChanged()
}
})
}
/**
* Runs in the MAIN window (mount once in App). Two responsibilities:
* 1. While the pop-out dashboard is open, derive the snapshot from the live
@@ -77,10 +115,21 @@ export function useDashboardPopoutBridge(enabled: boolean): void {
let unsubscribeStore: (() => void) | null = null
let trailingTimer: ReturnType<typeof setTimeout> | null = null
let lastPublishAt = 0
let lastPublishedRepoIcons: Record<string, RepoIcon | null> | null = null
const publishNow = (): void => {
// `withIcons` is forced whenever the pop-out could be starting from nothing —
// it opened, or it mounted and asked. Throttled republishes omit an unchanged
// icon map and the pop-out keeps the one it already has.
const publishNow = (withIcons: boolean): void => {
lastPublishAt = Date.now()
const snapshot = buildDashboardSnapshot(useAppStore.getState(), lastPublishAt)
const icons = snapshot.repoIconsByRepoId ?? {}
if (!withIcons && repoIconsUnchanged(icons, lastPublishedRepoIcons)) {
const { repoIconsByRepoId: _omitted, ...withoutIcons } = snapshot
void window.api.dashboard.publishSnapshot(withoutIcons)
return
}
lastPublishedRepoIcons = icons
void window.api.dashboard.publishSnapshot(snapshot)
}
@@ -96,14 +145,14 @@ export function useDashboardPopoutBridge(enabled: boolean): void {
clearTimeout(trailingTimer)
trailingTimer = null
}
publishNow()
publishNow(false)
return
}
if (!trailingTimer) {
trailingTimer = setTimeout(() => {
trailingTimer = null
if (open && !disposed) {
publishNow()
publishNow(false)
}
}, PUBLISH_THROTTLE_MS - elapsed)
}
@@ -116,14 +165,9 @@ export function useDashboardPopoutBridge(enabled: boolean): void {
open = next
if (open) {
if (!unsubscribeStore) {
unsubscribeStore = useAppStore.subscribe((state, previousState) => {
// Why: unrelated high-frequency store writes must not rebuild a cross-worktree snapshot.
if (dashboardSnapshotInputsChanged(state, previousState)) {
publishThrottled()
}
})
unsubscribeStore = watchSnapshotInputs(publishThrottled)
}
publishNow()
publishNow(true)
} else {
unsubscribeStore?.()
unsubscribeStore = null
@@ -138,7 +182,7 @@ export function useDashboardPopoutBridge(enabled: boolean): void {
// Popout mount asks for a fresh snapshot (its cached one may be stale).
const offRequested = window.api.dashboard.onSnapshotRequested(() => {
if (open) {
publishNow()
publishNow(true)
}
})
// Recover the open state when the main window (re)mounts while a pop-out is