diff --git a/src/main/ipc/dashboard-popout.test.ts b/src/main/ipc/dashboard-popout.test.ts index 0a66b2baa..96631d2d6 100644 --- a/src/main/ipc/dashboard-popout.test.ts +++ b/src/main/ipc/dashboard-popout.test.ts @@ -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( diff --git a/src/main/ipc/dashboard-popout.ts b/src/main/ipc/dashboard-popout.ts index 066da8685..7c794041c 100644 --- a/src/main/ipc/dashboard-popout.ts +++ b/src/main/ipc/dashboard-popout.ts @@ -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) }) diff --git a/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.test.tsx b/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.test.tsx index 6c5d29c2e..5d6853d84 100644 --- a/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.test.tsx +++ b/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.test.tsx @@ -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({}) + }) }) diff --git a/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.ts b/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.ts index 5445c662a..47704958d 100644 --- a/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.ts +++ b/src/renderer/src/components/dashboard-popout/useDashboardSnapshot.ts @@ -35,9 +35,21 @@ function terminalDialogIsOpen(): boolean { export function useDashboardSnapshot(): DashboardSnapshot { const [snapshot, setSnapshot] = useState(EMPTY_DASHBOARD_SNAPSHOT) const columnSignatureRef = useRef('') + const retainedRepoIconsRef = useRef(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 diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx index be58d8aae..1bc03a6b4 100644 --- a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx @@ -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()) + + 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 = { + 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 + + 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 => { + await act(async () => root.render()) + 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 = { r1: { type: 'emoji', emoji: '🦑' } } + mocks.buildDashboardSnapshot.mockImplementation((_state, at) => ({ + generatedAt: at, + cards: [], + repoIconsByRepoId: nextIcons + })) + + now += PAST_THROTTLE_MS + notifySnapshotInputsChanged() + + expect(lastPublished().repoIconsByRepoId).toBe(nextIcons) + }) +}) diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts index afb9c69cf..abde79789 100644 --- a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts @@ -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, + previous: Record | 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 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 | null = null let lastPublishAt = 0 + let lastPublishedRepoIcons: Record | 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