From d426088c3f78cdfb332812ab8eeb85cef343743a Mon Sep 17 00:00:00 2001 From: "paseo-bot[bot]" <266920839+paseo-bot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:04:24 +0000 Subject: [PATCH] Stop agent updates re-rendering the workspace screen, favicon, and command center (#9497) * Stop hidden surfaces rebuilding the agent directory on every update The favicon is mounted at the root of every web and Electron session, and it derived the whole aggregated agent list to answer three questions: is any agent running, does any want attention, does any need input. The aggregated list allocates a projection per agent, deep-compares it, sorts the whole host and rebuilds its identity cache, and useAggregatedAgents re-ran all of that on every agent update on any host. The dock badge did the same for workspaces: it materialised every workspace status and deep-compared the array for a number. Both now read a scalar selector: selectFaviconStatus walks the agent maps and returns one of three strings, and selectMacDockBadgeCount counts actionable workspaces without building a list. A store write that leaves those values alone no longer re-renders the root component. useAggregatedAgents also treated `demand` as "hold the directory subscription" but still subscribed to every host's agent map, so the closed command center (useAggregatedAgents({ demand: open })) rebuilt the full list on every update too. With demand false the hook now returns a stable empty result and stays off the maps. Measured on the many-agent-tabs harness (5 tabs, 20 s windows, agent_update churn from a background host): the root favicon component rendered 1554 times in 20 s before this change and 1 time after. * Complete the host runtime mock in the favicon test * Keep the profiling harness out of the fix The harness scans every process environment to find the daemon. Whether Paseo carries a renderer CPU harness, and how it samples processes, is a separate decision from the rendering fix. Co-Authored-By: Claude Opus 5.5 * Stop re-rendering the workspace screen on unrelated agent updates useOpenAgentTabLabels subscribed the workspace screen to the host's whole agent map. Every agent update on the host replaces that map, so each update re-rendered the open workspace screen, its split panes and tab menus. Subscribe only to the agents that have open tabs. Co-authored-by: jl97mcad <56251999+jl97mcad@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 * Test render isolation through pure selectors and the browser Replace the JSDOM hook tests and module mocks with pure selector tests and a browser test that updates an agent in another workspace and checks the open workspace screen does not re-render. Memoize the favicon and dock badge selectors on the session maps they read, so unrelated store writes skip the scan, and pass directory demand as an object. Co-authored-by: jl97mcad <56251999+jl97mcad@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: jl97mcad <56251999+jl97mcad@users.noreply.github.com> Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 --- .../workspace-unrelated-agent-update.spec.ts | 56 ++++++++++++++ .../app/src/hooks/use-aggregated-agents.ts | 30 ++++++-- .../app/src/hooks/use-directory-demand.ts | 18 +++++ packages/app/src/hooks/use-favicon-status.ts | 53 ++++++------- .../src/stores/session-store-hooks/index.ts | 16 +--- .../session-store-hooks/selectors.test.ts | 31 -------- .../stores/session-store-hooks/selectors.ts | 14 ---- .../app/src/subagents/open-tab-labels.test.ts | 54 ++++++++++++- packages/app/src/subagents/open-tab-labels.ts | 21 +++++ .../subagents/use-open-agent-tab-labels.ts | 30 +++++--- .../app/src/utils/desktop-badge-state.test.ts | 76 ++++++++++++++++--- packages/app/src/utils/desktop-badge-state.ts | 35 ++++++++- packages/app/src/utils/favicon-status.test.ts | 71 +++++++++++++++++ packages/app/src/utils/favicon-status.ts | 40 ++++++++++ .../app/src/utils/memoize-on-session-maps.ts | 31 ++++++++ 15 files changed, 449 insertions(+), 127 deletions(-) create mode 100644 packages/app/e2e/browser/workspace-unrelated-agent-update.spec.ts create mode 100644 packages/app/src/utils/favicon-status.test.ts create mode 100644 packages/app/src/utils/favicon-status.ts create mode 100644 packages/app/src/utils/memoize-on-session-maps.ts diff --git a/packages/app/e2e/browser/workspace-unrelated-agent-update.spec.ts b/packages/app/e2e/browser/workspace-unrelated-agent-update.spec.ts new file mode 100644 index 000000000..8d283191c --- /dev/null +++ b/packages/app/e2e/browser/workspace-unrelated-agent-update.spec.ts @@ -0,0 +1,56 @@ +import { test, expect } from "../support/fixtures"; +import { openAgentRoute } from "../support/helpers/mock-agent"; +import { + readReactRenders, + recordReactRenders, + resetReactRenders, +} from "../support/helpers/react-renders"; +import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client"; + +async function createMockAgent(workspace: SeededWorkspace, title: string): Promise { + const agent = await workspace.client.createAgent({ + provider: "mock", + cwd: workspace.repoPath, + workspaceId: workspace.workspaceId, + title, + modeId: "load-test", + model: "e2e-fast-stream", + }); + return agent.id; +} + +test.describe("Updates to agents in other workspaces", () => { + let open: SeededWorkspace; + let other: SeededWorkspace; + + test.afterEach(async () => { + await open?.cleanup(); + await other?.cleanup(); + }); + + test("do not re-render the open workspace screen", async ({ page }) => { + open = await seedWorkspace({ repoPrefix: "unrelated-update-open-", title: "Open" }); + other = await seedWorkspace({ repoPrefix: "unrelated-update-other-", title: "Other" }); + const openAgentId = await createMockAgent(open, "Open agent"); + const otherAgentId = await createMockAgent(other, "Other agent"); + + await recordReactRenders(page); + await openAgentRoute(page, { workspaceId: open.workspaceId, agentId: openAgentId }); + await expect( + page.getByTestId(`workspace-tab-agent_${openAgentId}`).filter({ visible: true }).first(), + ).toBeVisible({ timeout: 60_000 }); + await page.waitForTimeout(2_000); + await resetReactRenders(page); + + await other.client.sendAgentMessage(otherAgentId, "update"); + await other.client.waitForFinish(otherAgentId, 60_000); + // The favicon follows every agent on the host, so it renders when the other agent runs and + // settles. That confirms the updates reached this page. + await expect + .poll(async () => (await readReactRenders(page)).FaviconStatusSync ?? 0) + .toBeGreaterThan(0); + + const renders = await readReactRenders(page); + expect(renders.WorkspaceScreenContent ?? 0).toBe(0); + }); +}); diff --git a/packages/app/src/hooks/use-aggregated-agents.ts b/packages/app/src/hooks/use-aggregated-agents.ts index 910caf1d6..ffce971ca 100644 --- a/packages/app/src/hooks/use-aggregated-agents.ts +++ b/packages/app/src/hooks/use-aggregated-agents.ts @@ -1,10 +1,11 @@ -import { useMemo, useCallback, useEffect, useRef, useSyncExternalStore } from "react"; +import { useMemo, useCallback, useRef, useSyncExternalStore } from "react"; import equal from "fast-deep-equal"; import { useShallow } from "zustand/shallow"; import { useSessionStore } from "@/stores/session-store"; import type { AgentDirectoryEntry } from "@/types/agent-directory"; import type { Agent } from "@/stores/session-store"; import { getHostRuntimeStore, useHosts } from "@/runtime/host-runtime"; +import { useAllDirectoryDemand } from "./use-directory-demand"; export interface AggregatedAgent extends AgentDirectoryEntry { serverId: string; @@ -19,6 +20,9 @@ export interface AggregatedAgentsResult { refreshAll: () => void; } +const NO_AGENT_MAPS: Record | undefined> = Object.freeze({}); +const NO_AGENTS: AggregatedAgent[] = []; + export function useAggregatedAgents(options?: { includeArchived?: boolean; demand?: boolean; @@ -28,19 +32,21 @@ export function useAggregatedAgents(options?: { const includeArchived = options?.includeArchived ?? false; const demand = options?.demand ?? true; const serverIds = useMemo(() => daemons.map((daemon) => daemon.serverId), [daemons]); - useEffect(() => { - if (!demand) return; - const releases = serverIds.map((serverId) => runtime.acquireDirectoryDemand(serverId)); - return () => releases.forEach((release) => release()); - }, [demand, runtime, serverIds]); + useAllDirectoryDemand({ serverIds, enabled: demand }); const runtimeVersion = useSyncExternalStore( (onStoreChange) => runtime.subscribeAll(onStoreChange), () => runtime.getVersion(), () => runtime.getVersion(), ); + // The caller has said it does not need the directory, so stay off the agent maps entirely: + // every map change otherwise re-renders this hook and rebuilds the whole list for a surface + // that is not on screen (the command center while it is closed). const sessionAgents = useSessionStore( useShallow((state) => { + if (!demand) { + return NO_AGENT_MAPS; + } const result: Record | undefined> = {}; for (const [serverId, session] of Object.entries(state.sessions)) { result[serverId] = session.agents; @@ -64,6 +70,16 @@ export function useAggregatedAgents(options?: { const result = useMemo(() => { // runtimeVersion is referenced so the memo recomputes when runtime state changes. void runtimeVersion; + if (!demand) { + prevAgentsRef.current = new Map(); + prevSortedRef.current = NO_AGENTS; + return { + agents: NO_AGENTS, + isLoading: false, + isInitialLoad: false, + isRevalidating: false, + }; + } const allAgents: AggregatedAgent[] = []; const serverLabelById = new Map( daemons.map((daemon) => [daemon.serverId, daemon.label] as const), @@ -158,7 +174,7 @@ export function useAggregatedAgents(options?: { isInitialLoad, isRevalidating, }; - }, [daemons, includeArchived, runtime, runtimeVersion, sessionAgents]); + }, [daemons, demand, includeArchived, runtime, runtimeVersion, sessionAgents]); return { ...result, diff --git a/packages/app/src/hooks/use-directory-demand.ts b/packages/app/src/hooks/use-directory-demand.ts index f4d2953ab..b9e8ccb9a 100644 --- a/packages/app/src/hooks/use-directory-demand.ts +++ b/packages/app/src/hooks/use-directory-demand.ts @@ -14,3 +14,21 @@ export function useDirectoryDemand(serverId: string | null | undefined): void { return getHostRuntimeStore().acquireDirectoryDemand(serverId); }, [serverId]); } + +/** + * Holds directory demand for several hosts at once, so a caller that needs the whole fleet + * (the favicon, the aggregated agent list) does not have to subscribe to every agent map to + * keep the directories loading. + */ +export function useAllDirectoryDemand(input: { + serverIds: readonly string[]; + enabled: boolean; +}): void { + const { serverIds, enabled } = input; + useEffect(() => { + if (!enabled) return; + const runtime = getHostRuntimeStore(); + const releases = serverIds.map((serverId) => runtime.acquireDirectoryDemand(serverId)); + return () => releases.forEach((release) => release()); + }, [enabled, serverIds]); +} diff --git a/packages/app/src/hooks/use-favicon-status.ts b/packages/app/src/hooks/use-favicon-status.ts index 5fcce9a24..4686b10ff 100644 --- a/packages/app/src/hooks/use-favicon-status.ts +++ b/packages/app/src/hooks/use-favicon-status.ts @@ -1,12 +1,13 @@ -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { getIsElectronRuntimeMac } from "@/constants/layout"; -import { useAggregatedAgents } from "./use-aggregated-agents"; +import { useAllDirectoryDemand } from "./use-directory-demand"; import { getDesktopHost } from "@/desktop/host"; -import { useWorkspaceStatusesForBadges } from "@/stores/session-store-hooks"; -import { deriveMacDockBadgeCountFromWorkspaceStatuses } from "@/utils/desktop-badge-state"; +import { createMacDockBadgeCountSelector } from "@/utils/desktop-badge-state"; +import { createFaviconStatusSelector, type FaviconStatus } from "@/utils/favicon-status"; import { isNative } from "@/constants/platform"; +import { useSessionStore } from "@/stores/session-store"; +import { useHosts } from "@/runtime/host-runtime"; -type FaviconStatus = "none" | "running" | "attention"; type ColorScheme = "dark" | "light"; /* eslint-disable @typescript-eslint/no-require-imports */ @@ -24,21 +25,6 @@ const FAVICON_IMAGES: Record["agents"], -): FaviconStatus { - const hasRunning = agents.some((agent) => agent.status === "running"); - if (hasRunning) { - return "running"; - } - const hasAttention = agents.some((agent) => agent.requiresAttention); - const hasNeedsInput = agents.some((agent) => (agent.pendingPermissionCount ?? 0) > 0); - if (hasAttention || hasNeedsInput) { - return "attention"; - } - return "none"; -} - function getFaviconUri(status: FaviconStatus, colorScheme: ColorScheme): string { const image = FAVICON_IMAGES[colorScheme][status]; if (typeof image === "object" && "uri" in image) { @@ -94,8 +80,15 @@ async function updateMacDockBadge(count?: number) { } export function useFaviconStatus() { - const { agents } = useAggregatedAgents({ demand: !isNative }); - const workspaceStatuses = useWorkspaceStatusesForBadges(); + const daemons = useHosts(); + const serverIds = useMemo(() => daemons.map((daemon) => daemon.serverId), [daemons]); + // The favicon reads the whole fleet, so it has to keep every host's directory loading even + // though it no longer subscribes to the agent maps. + useAllDirectoryDemand({ serverIds, enabled: !isNative }); + const selectFaviconStatus = useMemo(createFaviconStatusSelector, []); + const selectMacDockBadgeCount = useMemo(createMacDockBadgeCountSelector, []); + const status = useSessionStore(selectFaviconStatus); + const dockBadgeCount = useSessionStore(selectMacDockBadgeCount); const [colorScheme, setColorScheme] = useState(getSystemColorScheme); const lastDockBadgeCountRef = useRef(undefined); @@ -112,17 +105,15 @@ export function useFaviconStatus() { return () => mediaQuery.removeEventListener("change", handler); }, []); - // Update favicon when agents or color scheme changes useEffect(() => { if (isNative) return; - - const status = deriveFaviconStatus(agents); updateFavicon(status, colorScheme); + }, [status, colorScheme]); - const dockBadgeCount = deriveMacDockBadgeCountFromWorkspaceStatuses(workspaceStatuses); - if (dockBadgeCount !== lastDockBadgeCountRef.current) { - lastDockBadgeCountRef.current = dockBadgeCount; - void updateMacDockBadge(dockBadgeCount); - } - }, [agents, colorScheme, workspaceStatuses]); + useEffect(() => { + if (isNative) return; + if (dockBadgeCount === lastDockBadgeCountRef.current) return; + lastDockBadgeCountRef.current = dockBadgeCount; + void updateMacDockBadge(dockBadgeCount); + }, [dockBadgeCount]); } diff --git a/packages/app/src/stores/session-store-hooks/index.ts b/packages/app/src/stores/session-store-hooks/index.ts index d6d4a188c..e2cc20454 100644 --- a/packages/app/src/stores/session-store-hooks/index.ts +++ b/packages/app/src/stores/session-store-hooks/index.ts @@ -17,22 +17,16 @@ import { selectWorkspaceExists, selectWorkspaceFields, selectWorkspaceKeys, - selectWorkspaceStatusesForBadges, workspaceEqualityFns, type WorkspaceStructure, } from "./selectors"; import { useSessionStore, type WorkspaceDescriptor } from "../session-store"; -import type { DesktopBadgeWorkspaceStatus } from "@/utils/desktop-badge-state"; // These are the ONLY supported ways to read workspaces from the session store. // Do not write raw `useSessionStore` selectors that return the workspaces Map, a session object, // or the sessions dict — it breaks re-render isolation. -export type { - DesktopBadgeWorkspaceStatus, - WorkspaceStructure, - WorkspaceStructureProject, -} from "./selectors"; +export type { WorkspaceStructure, WorkspaceStructureProject } from "./selectors"; export function useWorkspace( serverId: string | null, @@ -163,11 +157,3 @@ export function useHasWorkspaces(serverId: string | null): boolean { workspaceEqualityFns.identity, ); } - -export function useWorkspaceStatusesForBadges(): DesktopBadgeWorkspaceStatus[] { - return useStoreWithEqualityFn( - useSessionStore, - (state) => selectWorkspaceStatusesForBadges(state), - workspaceEqualityFns.deep, - ); -} diff --git a/packages/app/src/stores/session-store-hooks/selectors.test.ts b/packages/app/src/stores/session-store-hooks/selectors.test.ts index 95cc1ba49..68caaf229 100644 --- a/packages/app/src/stores/session-store-hooks/selectors.test.ts +++ b/packages/app/src/stores/session-store-hooks/selectors.test.ts @@ -14,7 +14,6 @@ import { selectWorkspaceDirectory, selectWorkspaceFields, selectWorkspaceKeys, - selectWorkspaceStatusesForBadges, selectWorkspaceStructureProjects, workspaceEqualityFns, type SidebarOrderSnapshot, @@ -589,36 +588,6 @@ describe("selectHasWorkspaces", () => { }); }); -describe("selectWorkspaceStatusesForBadges", () => { - it("tracks status changes without changing for no-ops or unrelated descriptor updates", () => { - const workspaceA = createWorkspace({ id: "workspace-a", status: "done" }); - const workspaceB = createWorkspace({ id: "workspace-b", status: "attention" }); - initializeWorkspaces([workspaceA, workspaceB]); - - const tracked = trackSelector( - useSessionStore, - (state) => selectWorkspaceStatusesForBadges(state), - workspaceEqualityFns.deep, - ); - const before = tracked.current; - expect(before).toEqual(["done", "attention"]); - - useSessionStore - .getState() - .mergeWorkspaces(SERVER_ID, [{ ...workspaceA, scripts: [...workspaceA.scripts] }]); - expect(tracked.current).toBe(before); - - useSessionStore.getState().mergeWorkspaces(SERVER_ID, [{ ...workspaceB, name: "Renamed" }]); - expect(tracked.current).toBe(before); - - useSessionStore.getState().mergeWorkspaces(SERVER_ID, [{ ...workspaceA, status: "failed" }]); - expect(tracked.current).not.toBe(before); - expect(tracked.current).toEqual(["failed", "attention"]); - - tracked.stop(); - }); -}); - it("a prompt changes only its project's structure and output preserves both project identities", () => { const a = { ...createWorkspace({ id: "a", projectId: "p" }), createdAt: new Date("2026-01-01") }; const b = { ...createWorkspace({ id: "b", projectId: "p" }), createdAt: new Date("2026-02-01") }; diff --git a/packages/app/src/stores/session-store-hooks/selectors.ts b/packages/app/src/stores/session-store-hooks/selectors.ts index 85169b6f4..832ae54ca 100644 --- a/packages/app/src/stores/session-store-hooks/selectors.ts +++ b/packages/app/src/stores/session-store-hooks/selectors.ts @@ -5,11 +5,9 @@ import { type WorkspaceStructure, type WorkspaceStructureProject, } from "@/projects/workspace-structure"; -import type { DesktopBadgeWorkspaceStatus } from "@/utils/desktop-badge-state"; import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity"; import type { ProjectDescriptor, WorkspaceDescriptor } from "../session-store"; -export type { DesktopBadgeWorkspaceStatus } from "@/utils/desktop-badge-state"; export type { WorkspaceStructure, WorkspaceStructureProject } from "@/projects/workspace-structure"; export interface SessionsSnapshot { @@ -321,15 +319,3 @@ export function selectHasWorkspaces(state: SessionsSnapshot, serverId: string | } return (state.sessions[serverId]?.workspaces?.size ?? 0) > 0; } - -export function selectWorkspaceStatusesForBadges( - state: SessionsSnapshot, -): DesktopBadgeWorkspaceStatus[] { - const statuses: DesktopBadgeWorkspaceStatus[] = []; - for (const session of Object.values(state.sessions)) { - for (const workspace of session.workspaces.values()) { - statuses.push(workspace.status); - } - } - return statuses; -} diff --git a/packages/app/src/subagents/open-tab-labels.test.ts b/packages/app/src/subagents/open-tab-labels.test.ts index 61874cd05..9cab01f11 100644 --- a/packages/app/src/subagents/open-tab-labels.test.ts +++ b/packages/app/src/subagents/open-tab-labels.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from "vitest"; import type { Agent } from "@/stores/session-store"; import type { WorkspaceTab } from "@/workspace-tabs/model"; -import { getAgentTabsNeedingOpenLabel } from "./open-tab-labels"; +import { shallow } from "zustand/shallow"; +import { getAgentTabsNeedingOpenLabel, selectOpenTabAgents } from "./open-tab-labels"; const label = "paseo.open-agent-tab.client-1"; @@ -51,3 +52,54 @@ describe("getAgentTabsNeedingOpenLabel", () => { ).toEqual([]); }); }); + +describe("selectOpenTabAgents", () => { + function stateWith(agents: Agent[]) { + return { + sessions: { + srv: { agents: new Map(agents.map((entry) => [entry.id, entry])), agentDetails: new Map() }, + }, + }; + } + + it("stays equal when only an agent without an open tab changes", () => { + const open = agent({ id: "open" }); + const before = selectOpenTabAgents(stateWith([open, agent({ id: "elsewhere" })]), { + serverId: "srv", + agentIds: ["open"], + }); + const after = selectOpenTabAgents(stateWith([open, agent({ id: "elsewhere" })]), { + serverId: "srv", + agentIds: ["open"], + }); + + expect(shallow(before, after)).toBe(true); + }); + + it("changes when an agent with an open tab changes", () => { + const elsewhere = agent({ id: "elsewhere" }); + const before = selectOpenTabAgents(stateWith([agent({ id: "open" }), elsewhere]), { + serverId: "srv", + agentIds: ["open"], + }); + const after = selectOpenTabAgents(stateWith([agent({ id: "open" }), elsewhere]), { + serverId: "srv", + agentIds: ["open"], + }); + + expect(shallow(before, after)).toBe(false); + }); + + it("falls back to agent details and returns null for unknown agents", () => { + const detail = agent({ id: "detail" }); + const state = { + sessions: { + srv: { agents: new Map(), agentDetails: new Map([["detail", detail]]) }, + }, + }; + + expect( + selectOpenTabAgents(state, { serverId: "srv", agentIds: ["detail", "missing"] }), + ).toEqual([detail, null]); + }); +}); diff --git a/packages/app/src/subagents/open-tab-labels.ts b/packages/app/src/subagents/open-tab-labels.ts index ca7d8e63d..df855a6df 100644 --- a/packages/app/src/subagents/open-tab-labels.ts +++ b/packages/app/src/subagents/open-tab-labels.ts @@ -23,3 +23,24 @@ export function getAgentTabsNeedingOpenLabel(input: { } return [...agentIds]; } + +interface OpenTabAgentSource { + sessions: Record< + string, + { agents: ReadonlyMap; agentDetails: ReadonlyMap } | undefined + >; +} + +/** + * The agents behind the given open tabs, in tab order. Compared element by element, this changes + * only when one of those agents changes, not on updates to other agents on the host. + */ +export function selectOpenTabAgents( + state: OpenTabAgentSource, + input: { serverId: string; agentIds: readonly string[] }, +): (Agent | null)[] { + const session = state.sessions[input.serverId]; + return input.agentIds.map( + (agentId) => session?.agents.get(agentId) ?? session?.agentDetails.get(agentId) ?? null, + ); +} diff --git a/packages/app/src/subagents/use-open-agent-tab-labels.ts b/packages/app/src/subagents/use-open-agent-tab-labels.ts index ea02fd1b1..7570d6546 100644 --- a/packages/app/src/subagents/use-open-agent-tab-labels.ts +++ b/packages/app/src/subagents/use-open-agent-tab-labels.ts @@ -1,10 +1,11 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client"; import { getOpenAgentTabLabel } from "@getpaseo/protocol/agent-labels"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; +import { useShallow } from "zustand/shallow"; import { useSessionStore } from "@/stores/session-store"; import { getOrCreateClientId } from "@/utils/client-id"; import type { WorkspaceTab } from "@/workspace-tabs/model"; -import { getAgentTabsNeedingOpenLabel } from "./open-tab-labels"; +import { getAgentTabsNeedingOpenLabel, selectOpenTabAgents } from "./open-tab-labels"; function increment(value: number): number { return value + 1; @@ -16,9 +17,16 @@ export function useOpenAgentTabLabels(input: { tabs: WorkspaceTab[]; enabled: boolean; }): void { - const agents = useSessionStore((state) => state.sessions[input.serverId]?.agents ?? null); - const agentDetails = useSessionStore( - (state) => state.sessions[input.serverId]?.agentDetails ?? null, + const openAgentIds = useMemo( + () => input.tabs.flatMap((tab) => (tab.target.kind === "agent" ? [tab.target.agentId] : [])), + [input.tabs], + ); + // Only the agents with open tabs can need a label. Subscribing to the whole agent map would + // re-render the workspace screen on every update to any agent on the host. + const openAgents = useSessionStore( + useShallow((state) => + selectOpenTabAgents(state, { serverId: input.serverId, agentIds: openAgentIds }), + ), ); const pendingAgentIdsRef = useRef(new Set()); const retryTimerRef = useRef | null>(null); @@ -39,15 +47,13 @@ export function useOpenAgentTabLabels(input: { return; } - const openAgentIds = new Set( - input.tabs.flatMap((tab) => (tab.target.kind === "agent" ? [tab.target.agentId] : [])), - ); + const agentsById = new Map(openAgentIds.map((agentId, index) => [agentId, openAgents[index]])); for (const agentId of pendingAgentIdsRef.current) { - if (!openAgentIds.has(agentId)) { + if (!agentsById.has(agentId)) { pendingAgentIdsRef.current.delete(agentId); } } - if (openAgentIds.size === 0) { + if (agentsById.size === 0) { return; } @@ -57,7 +63,7 @@ export function useOpenAgentTabLabels(input: { const label = getOpenAgentTabLabel(clientId); const agentIds = getAgentTabsNeedingOpenLabel({ tabs: input.tabs, - getAgent: (agentId) => agents?.get(agentId) ?? agentDetails?.get(agentId), + getAgent: (agentId) => agentsById.get(agentId), label, pendingAgentIds: pendingAgentIdsRef.current, }); @@ -82,5 +88,5 @@ export function useOpenAgentTabLabels(input: { console.warn("[OpenAgentTabLabels] Failed to resolve client ID", { error }); } })(); - }, [agentDetails, agents, input.client, input.enabled, input.tabs, retryVersion]); + }, [input.client, input.enabled, input.tabs, openAgentIds, openAgents, retryVersion]); } diff --git a/packages/app/src/utils/desktop-badge-state.test.ts b/packages/app/src/utils/desktop-badge-state.test.ts index 9bcdd39bc..69c747bcf 100644 --- a/packages/app/src/utils/desktop-badge-state.test.ts +++ b/packages/app/src/utils/desktop-badge-state.test.ts @@ -1,9 +1,39 @@ import { describe, expect, it } from "vitest"; +import type { WorkspaceDescriptor } from "@/stores/session-store"; import { - deriveMacDockBadgeCountFromWorkspaceStatuses, + createMacDockBadgeCountSelector, isWorkspaceActionableForDesktopBadge, + selectMacDockBadgeCount, } from "./desktop-badge-state"; +function workspace(id: string, status: WorkspaceDescriptor["status"]): WorkspaceDescriptor { + return { + createdAt: null, + lastUserMessageAt: null, + id, + projectId: "project-1", + projectDisplayName: "Project 1", + projectRootPath: "/repo", + workspaceDirectory: "/repo", + projectKind: "git", + workspaceKind: "local_checkout", + name: id, + status, + archivingAt: null, + statusEnteredAt: null, + diffStat: null, + scripts: [], + }; +} + +function stateWith(...workspaces: WorkspaceDescriptor[]) { + return { + sessions: { + srv_a: { workspaces: new Map(workspaces.map((entry) => [entry.id, entry])) }, + }, + }; +} + describe("desktop-badge-state", () => { it("treats attention-requiring workspace statuses as actionable", () => { expect(isWorkspaceActionableForDesktopBadge("attention")).toBe(true); @@ -17,18 +47,40 @@ describe("desktop-badge-state", () => { }); it("returns undefined when no visible workspaces need attention", () => { - expect(deriveMacDockBadgeCountFromWorkspaceStatuses(["done", "running"])).toBeUndefined(); + expect( + selectMacDockBadgeCount(stateWith(workspace("a", "done"), workspace("b", "running"))), + ).toBeUndefined(); }); - it("counts only actionable visible workspaces", () => { - expect( - deriveMacDockBadgeCountFromWorkspaceStatuses([ - "done", - "attention", - "running", - "needs_input", - "failed", - ]), - ).toBe(3); + it("counts only actionable visible workspaces across every host", () => { + const state = { + sessions: { + srv_a: { + workspaces: new Map([ + ["a", workspace("a", "done")], + ["b", workspace("b", "attention")], + ]), + }, + srv_b: { + workspaces: new Map([ + ["c", workspace("c", "running")], + ["d", workspace("d", "needs_input")], + ["e", workspace("e", "failed")], + ]), + }, + }, + }; + expect(selectMacDockBadgeCount(state)).toBe(3); + }); + + it("recounts only when a workspace map is replaced", () => { + const select = createMacDockBadgeCountSelector(); + const state = stateWith(workspace("a", "attention")); + expect(select(state)).toBe(1); + + state.sessions.srv_a.workspaces.set("b", workspace("b", "failed")); + expect(select({ sessions: { ...state.sessions } })).toBe(1); + + expect(select(stateWith(workspace("a", "attention"), workspace("b", "failed")))).toBe(2); }); }); diff --git a/packages/app/src/utils/desktop-badge-state.ts b/packages/app/src/utils/desktop-badge-state.ts index 00a2a7832..94cf025b5 100644 --- a/packages/app/src/utils/desktop-badge-state.ts +++ b/packages/app/src/utils/desktop-badge-state.ts @@ -1,14 +1,41 @@ import type { WorkspaceDescriptor } from "@/stores/session-store"; +import { memoizeOnSessionMaps } from "./memoize-on-session-maps"; export type DesktopBadgeWorkspaceStatus = WorkspaceDescriptor["status"]; +interface WorkspaceStatusSession { + workspaces: ReadonlyMap; +} + +interface WorkspaceStatusSource { + sessions: Record; +} + export function isWorkspaceActionableForDesktopBadge(status: DesktopBadgeWorkspaceStatus): boolean { return status === "attention" || status === "needs_input" || status === "failed"; } -export function deriveMacDockBadgeCountFromWorkspaceStatuses( - statuses: readonly DesktopBadgeWorkspaceStatus[], -): number | undefined { - const actionableCount = statuses.filter(isWorkspaceActionableForDesktopBadge).length; +/** + * The macOS dock badge only needs a count, so count here instead of materialising every + * workspace status and comparing the whole list on every store write. + */ +export function selectMacDockBadgeCount(state: WorkspaceStatusSource): number | undefined { + let actionableCount = 0; + for (const session of Object.values(state.sessions)) { + if (!session) continue; + for (const workspace of session.workspaces.values()) { + if (isWorkspaceActionableForDesktopBadge(workspace.status)) actionableCount += 1; + } + } return actionableCount > 0 ? actionableCount : undefined; } + +/** A session-store selector for the dock badge count that recounts only when a workspace map changes. */ +export function createMacDockBadgeCountSelector(): ( + state: WorkspaceStatusSource, +) => number | undefined { + return memoizeOnSessionMaps( + (session) => session.workspaces, + selectMacDockBadgeCount, + ); +} diff --git a/packages/app/src/utils/favicon-status.test.ts b/packages/app/src/utils/favicon-status.test.ts new file mode 100644 index 000000000..6bb6a71d8 --- /dev/null +++ b/packages/app/src/utils/favicon-status.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import type { Agent } from "@/stores/session-store"; +import { createFaviconStatusSelector, deriveFaviconStatus } from "./favicon-status"; + +function agent(input: Partial & { id: string }): Agent { + return { + status: "idle", + background: false, + archivedAt: null, + requiresAttention: false, + pendingPermissions: [], + ...input, + } as Agent; +} + +function stateWith(...agents: Agent[]) { + return { sessions: { srv: { agents: new Map(agents.map((entry) => [entry.id, entry])) } } }; +} + +describe("deriveFaviconStatus", () => { + it("is running when any visible agent runs", () => { + expect( + deriveFaviconStatus( + stateWith( + agent({ id: "a", requiresAttention: true }), + agent({ id: "b", status: "running" }), + ), + ), + ).toBe("running"); + }); + + it("needs attention for attention or pending permissions", () => { + expect(deriveFaviconStatus(stateWith(agent({ id: "a", requiresAttention: true })))).toBe( + "attention", + ); + expect( + deriveFaviconStatus( + stateWith(agent({ id: "a", pendingPermissions: [{}] as Agent["pendingPermissions"] })), + ), + ).toBe("attention"); + }); + + it("ignores background and archived agents", () => { + expect( + deriveFaviconStatus( + stateWith( + agent({ id: "a", status: "running", background: true }), + agent({ id: "b", requiresAttention: true, archivedAt: new Date() }), + ), + ), + ).toBe("none"); + }); +}); + +describe("createFaviconStatusSelector", () => { + it("reuses its result while the agent maps are unchanged", () => { + const select = createFaviconStatusSelector(); + const state = stateWith(agent({ id: "a", status: "running" })); + expect(select(state)).toBe("running"); + + // Same agent map, mutated behind the store's back: the selector must not rescan. + state.sessions.srv.agents.set("a", agent({ id: "a" })); + expect(select({ sessions: { ...state.sessions } })).toBe("running"); + }); + + it("rescans when an agent map is replaced", () => { + const select = createFaviconStatusSelector(); + expect(select(stateWith(agent({ id: "a", status: "running" })))).toBe("running"); + expect(select(stateWith(agent({ id: "a" })))).toBe("none"); + }); +}); diff --git a/packages/app/src/utils/favicon-status.ts b/packages/app/src/utils/favicon-status.ts new file mode 100644 index 000000000..62d1630ab --- /dev/null +++ b/packages/app/src/utils/favicon-status.ts @@ -0,0 +1,40 @@ +import type { Agent } from "@/stores/session-store"; +import { memoizeOnSessionMaps } from "./memoize-on-session-maps"; + +export type FaviconStatus = "none" | "running" | "attention"; + +interface FaviconAgentSession { + agents: ReadonlyMap; +} + +interface FaviconAgentSource { + sessions: Record; +} + +/** + * The favicon is the only always-mounted consumer of the whole agent directory, so derive its + * three states here instead of building the aggregated agent list: the list allocates a + * projection per agent, deep-compares it and sorts every agent on the host on each update. + */ +export function deriveFaviconStatus(state: FaviconAgentSource): FaviconStatus { + let hasAttention = false; + let hasNeedsInput = false; + for (const session of Object.values(state.sessions)) { + if (!session) continue; + for (const agent of session.agents.values()) { + if (agent.background || agent.archivedAt) continue; + if (agent.status === "running") return "running"; + if (agent.requiresAttention) hasAttention = true; + if (agent.pendingPermissions.length > 0) hasNeedsInput = true; + } + } + return hasAttention || hasNeedsInput ? "attention" : "none"; +} + +/** A session-store selector for the favicon status that rescans only when an agent map changes. */ +export function createFaviconStatusSelector(): (state: FaviconAgentSource) => FaviconStatus { + return memoizeOnSessionMaps( + (session) => session.agents, + deriveFaviconStatus, + ); +} diff --git a/packages/app/src/utils/memoize-on-session-maps.ts b/packages/app/src/utils/memoize-on-session-maps.ts new file mode 100644 index 000000000..ed621ee1c --- /dev/null +++ b/packages/app/src/utils/memoize-on-session-maps.ts @@ -0,0 +1,31 @@ +interface SessionsSource { + sessions: Record; +} + +/** + * Wraps a whole-store selector so it reruns only when one of the per-session maps it reads has + * changed. Session-store writes that leave those maps alone (timeline updates, drafts) then cost + * a reference check per host instead of a walk over every entry. + */ +export function memoizeOnSessionMaps, TResult>( + pickMap: (session: TSession) => unknown, + derive: (state: TState) => TResult, +): (state: TState) => TResult { + let previousMaps: unknown[] | null = null; + let previousResult: TResult; + return (state) => { + const maps = Object.values(state.sessions).map((session) => + session ? pickMap(session) : undefined, + ); + if ( + previousMaps && + previousMaps.length === maps.length && + previousMaps.every((map, index) => map === maps[index]) + ) { + return previousResult; + } + previousMaps = maps; + previousResult = derive(state); + return previousResult; + }; +}