From 2c494da3617879f0aa70ef1794d0ff8b56ae33b6 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 28 Apr 2026 10:13:32 -0700 Subject: [PATCH] =?UTF-8?q?feat(agents):=20Agent=20Dashboard=20v2=20?= =?UTF-8?q?=E2=80=94=20hook=20endpoint=20discovery,=20dashboard=20UI,=20si?= =?UTF-8?q?debar=20status=20overlay=20(#1147)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Orca --- .../runtime-home-service.test.ts | 1 + src/main/codex-accounts/service.test.ts | 1 + src/renderer/src/App.tsx | 46 +- .../components/dashboard/AgentDashboard.tsx | 333 ++++++++++++ .../dashboard/DashboardAgentRow.tsx | 462 +++++++++++++++++ .../dashboard/DashboardFilterBar.tsx | 41 ++ .../dashboard/DashboardWorktreeCard.tsx | 141 ++++++ .../dashboard/RetainedAgentsSyncGate.tsx | 17 + .../components/dashboard/useDashboardData.ts | 222 ++++++++ .../dashboard/useDashboardFilter.ts | 185 +++++++ .../dashboard/useDashboardKeyboard.ts | 223 ++++++++ .../src/components/dashboard/useNow.ts | 18 + .../dashboard/useRetainedAgents.test.ts | 147 ++++++ .../components/dashboard/useRetainedAgents.ts | 245 +++++++++ .../right-sidebar/DashboardBottomPanel.tsx | 340 +++++++++++++ .../src/components/right-sidebar/index.tsx | 25 +- .../src/components/settings/AgentsPane.tsx | 43 ++ .../components/sidebar/AgentStatusHover.tsx | 479 ++++++++---------- .../src/components/sidebar/WorktreeCard.tsx | 218 +++----- .../components/terminal-pane/TerminalPane.tsx | 8 +- .../terminal-pane/pty-connection.ts | 8 + .../use-terminal-pane-lifecycle.ts | 9 +- .../store/slices/agent-status-drop.test.ts | 195 +++++++ .../agent-status-freshness-scheduler.ts | 73 +++ .../src/store/slices/agent-status.test.ts | 62 ++- src/renderer/src/store/slices/agent-status.ts | 379 +++++++++++--- src/renderer/src/store/slices/terminals.ts | 18 +- src/shared/constants.ts | 1 + src/shared/types.ts | 10 + 29 files changed, 3441 insertions(+), 509 deletions(-) create mode 100644 src/renderer/src/components/dashboard/AgentDashboard.tsx create mode 100644 src/renderer/src/components/dashboard/DashboardAgentRow.tsx create mode 100644 src/renderer/src/components/dashboard/DashboardFilterBar.tsx create mode 100644 src/renderer/src/components/dashboard/DashboardWorktreeCard.tsx create mode 100644 src/renderer/src/components/dashboard/RetainedAgentsSyncGate.tsx create mode 100644 src/renderer/src/components/dashboard/useDashboardData.ts create mode 100644 src/renderer/src/components/dashboard/useDashboardFilter.ts create mode 100644 src/renderer/src/components/dashboard/useDashboardKeyboard.ts create mode 100644 src/renderer/src/components/dashboard/useNow.ts create mode 100644 src/renderer/src/components/dashboard/useRetainedAgents.test.ts create mode 100644 src/renderer/src/components/dashboard/useRetainedAgents.ts create mode 100644 src/renderer/src/components/right-sidebar/DashboardBottomPanel.tsx create mode 100644 src/renderer/src/store/slices/agent-status-drop.test.ts create mode 100644 src/renderer/src/store/slices/agent-status-freshness-scheduler.ts diff --git a/src/main/codex-accounts/runtime-home-service.test.ts b/src/main/codex-accounts/runtime-home-service.test.ts index d5b62e9ff..6b230d613 100644 --- a/src/main/codex-accounts/runtime-home-service.test.ts +++ b/src/main/codex-accounts/runtime-home-service.test.ts @@ -64,6 +64,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings openLinksInApp: false, rightSidebarOpenByDefault: true, showTitlebarAgentActivity: true, + showAgentDashboard: true, showTaskProviderIcons: true, diffDefaultView: 'inline', notifications: { diff --git a/src/main/codex-accounts/service.test.ts b/src/main/codex-accounts/service.test.ts index 98338cc24..e4db05b45 100644 --- a/src/main/codex-accounts/service.test.ts +++ b/src/main/codex-accounts/service.test.ts @@ -58,6 +58,7 @@ function createSettings(overrides: Partial = {}): GlobalSettings openLinksInApp: false, rightSidebarOpenByDefault: true, showTitlebarAgentActivity: true, + showAgentDashboard: true, showTaskProviderIcons: true, diffDefaultView: 'inline', notifications: { diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 5f4974b40..19ed5954f 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -1,6 +1,10 @@ /* eslint-disable max-lines */ import { lazy, Suspense, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' -import { DEFAULT_STATUS_BAR_ITEMS, DEFAULT_WORKTREE_CARD_PROPERTIES } from '../../shared/constants' +import { + AGENT_DASHBOARD_ENABLED, + DEFAULT_STATUS_BAR_ITEMS, + DEFAULT_WORKTREE_CARD_PROPERTIES +} from '../../shared/constants' import { ArrowLeft, ArrowRight, Minimize2, PanelLeft, PanelRight } from 'lucide-react' import { @@ -15,6 +19,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/comp import { useAppStore } from './store' import { useShallow } from 'zustand/react/shallow' import { useIpcEvents } from './hooks/useIpcEvents' +import RetainedAgentsSyncGate from './components/dashboard/RetainedAgentsSyncGate' import Sidebar from './components/Sidebar' import Terminal from './components/Terminal' import { shutdownBufferCaptures } from './components/terminal-pane/TerminalPane' @@ -145,6 +150,21 @@ function App(): React.JSX.Element { // Subscribe to IPC push events useIpcEvents() + // Why: retention must run at App level (not inside AgentDashboard) because + // the sidebar hovercard also reads retained entries. If retention only ran + // when the dashboard is mounted, "done" agents would vanish from the hover + // any time the user collapses the dashboard panel. + // + // The retention hooks are hosted inside (a leaf + // component that renders null) rather than being called inline here. + // Calling useDashboardData() from App.tsx would subscribe the root component + // to high-churn slices (agentStatusByPaneKey + agentStatusEpoch tick at PTY + // event frequency), re-rendering the entire app tree on every agent status + // update. Hosting the subscriptions in a leaf isolates that churn. + // + // The AGENT_DASHBOARD_ENABLED gate still lives inside the hooks themselves + // (useDashboardData early-returns [] from its memo; useRetainedAgentsSync + // early-returns from its effect), so the gate component is cheap when off. // Why: git conflict-operation state also drives the worktree cards. Polling // cannot live under RightSidebar because App unmounts that subtree when the // sidebar is closed, which leaves stale "Rebasing"/"Merging" badges behind @@ -693,6 +713,26 @@ function App(): React.JSX.Element { return } + // Cmd/Ctrl+Shift+D — open right sidebar (agent dashboard is now + // docked at the sidebar bottom, so only toggle visibility). + // Why: skip when a terminal is focused — that combo is the terminal + // split-pane shortcut (see terminal-shortcut-policy.ts). Both listeners + // share the window capture phase and registration order can vary with + // React effect re-runs, so a DOM check is the reliable coordination + // mechanism (same pattern as Cmd+Shift+G above). xterm-helper-textarea + // is the focus target the terminal handler itself uses to detect + // terminal focus (see keyboard-handlers.ts isEditableTarget). + if (AGENT_DASHBOARD_ENABLED && e.shiftKey && !e.altKey && e.key.toLowerCase() === 'd') { + const active = document.activeElement as HTMLElement | null + if (active?.classList.contains('xterm-helper-textarea')) { + return + } + dispatchClearModifierHints() + e.preventDefault() + actions.setRightSidebarOpen(true) + return + } + // Cmd+Shift+I — toggle right sidebar / ports tab (macOS only). // Why: Ctrl+Shift+I is the built-in DevTools accelerator on Windows/Linux; // intercepting it would break an essential developer tool. @@ -968,6 +1008,10 @@ function App(): React.JSX.Element { } > + {/* Why: leaf-mounted retention sync. Hosts useDashboardData() + + useRetainedAgentsSync() so their high-churn store subscriptions + re-render a null component rather than the entire App tree. */} + {/* Why: in workspace view (split groups always enabled), the full-width titlebar is removed so tab groups + terminal extend to the top of the window. Left titlebar controls move to a header above the sidebar. diff --git a/src/renderer/src/components/dashboard/AgentDashboard.tsx b/src/renderer/src/components/dashboard/AgentDashboard.tsx new file mode 100644 index 000000000..b9622cb05 --- /dev/null +++ b/src/renderer/src/components/dashboard/AgentDashboard.tsx @@ -0,0 +1,333 @@ +import React, { useState, useCallback, useMemo, useRef } from 'react' +import { Search, X, ChevronDown, ChevronRight, FolderGit2 } from 'lucide-react' +import { cn } from '@/lib/utils' +import { useAppStore } from '@/store' +import { Input } from '@/components/ui/input' +import { Button } from '@/components/ui/button' +import { useDashboardData } from './useDashboardData' +import { useDashboardFilter } from './useDashboardFilter' +import { useDashboardKeyboard } from './useDashboardKeyboard' +import { useRetainedAgents } from './useRetainedAgents' +import DashboardFilterBar from './DashboardFilterBar' +import DashboardWorktreeCard from './DashboardWorktreeCard' +import { useNow } from './useNow' + +const AgentDashboard = React.memo(function AgentDashboard() { + const liveGroups = useDashboardData() + // Why: useRetainedAgents keeps a "done" row visible after the terminal/pane + // is closed and the explicit status entry is evicted from the store. Without + // this, a completed agent vanishes entirely — and the user loses the signal + // that the agent finished. Retained rows are dismissed when the user clicks + // through to the worktree. + const { enrichedGroups: groups, dismissAgent } = useRetainedAgents(liveGroups) + const dropAgentStatus = useAppStore((s) => s.dropAgentStatus) + const setActiveWorktree = useAppStore((s) => s.setActiveWorktree) + const setActiveTab = useAppStore((s) => s.setActiveTab) + const setActiveView = useAppStore((s) => s.setActiveView) + // Why: the persistent "selected" tint on a worktree card tracks the active + // worktree, not the last-clicked focus state. Keeping this in sync with the + // app-level activeWorktreeId makes the dashboard highlight what the user is + // currently viewing rather than where the keyboard/mouse last landed. + const activeWorktreeId = useAppStore((s) => s.activeWorktreeId) + // Why: own the 30s relative-time tick once for the whole dashboard and + // thread it down to every agent row. Previously each DashboardAgentRow + // instantiated its own setInterval, which scaled linearly with the number + // of rows on screen (N timers → N staggered re-renders per cycle). + const now = useNow(30_000) + + // Why: the store's explicit status entry persists after an agent reports + // `done` until the pane actually exits — which may be much later, since the + // user often leaves the Claude/Codex session alive to review output. The + // per-row dismiss removes both the live store entry and any retained entry + // so done agents don't pile up indefinitely in the dashboard. + const handleDismissAgent = useCallback( + (paneKey: string) => { + dropAgentStatus(paneKey) + dismissAgent(paneKey) + }, + [dropAgentStatus, dismissAgent] + ) + + const [searchQuery, setSearchQuery] = useState('') + const { filter, setFilter, filteredGroups, hasResults } = useDashboardFilter(groups, searchQuery) + const [focusedWorktreeId, setFocusedWorktreeId] = useState(null) + // Why: repo groups are collapsible so users can hide repos they aren't + // actively watching. State is per-session (intentionally not persisted) — + // a long-lived collapsed state across restarts would hide new activity + // under a closed header and silently erase the "needs attention" signal. + const [collapsedRepos, setCollapsedRepos] = useState>(new Set()) + const toggleCollapse = useCallback((repoId: string) => { + setCollapsedRepos((prev) => { + const next = new Set(prev) + if (next.has(repoId)) { + next.delete(repoId) + } else { + next.add(repoId) + } + return next + }) + }, []) + // Why: arrow-key nav should only step over worktrees whose repo header is + // expanded. Building this list here keeps the source of truth in one place + // for both the DOM render order and the keyboard iteration order. + const visibleWorktrees = useMemo( + () => filteredGroups.flatMap((g) => (collapsedRepos.has(g.repo.id) ? [] : g.worktrees)), + [filteredGroups, collapsedRepos] + ) + + // Why: the keyboard hook scopes its listener to this container (not window) + // so dashboard shortcuts (1-5, arrows, Enter, Escape) don't hijack the + // terminal or other focused inputs when the dashboard pane is merely open. + // We keep a local ref so the callback ref below can detect the null → element + // transition (for focus-on-first-mount), and separately feed the element into + // `useDashboardKeyboard` via its callback ref. The container is rendered + // unconditionally (including on the no-repos empty state) so keyboard + // shortcuts remain wired even before any repo is added — otherwise the + // filter keys (1-5) would silently no-op until the first repo arrived. + const containerRef = useRef(null) + + // Why: clicking an agent row takes the user to the specific tab the agent + // ran in, not just the worktree's last-active tab. Retained rows can outlive + // their pane — fall back to worktree-only activation when the tab is no + // longer present so the click still lands somewhere useful. + const handleActivateAgentTab = useCallback( + (worktreeId: string, tabId: string) => { + setActiveWorktree(worktreeId) + setActiveView('terminal') + const tabs = useAppStore.getState().tabsByWorktree[worktreeId] ?? [] + if (tabs.some((t) => t.id === tabId)) { + setActiveTab(tabId) + } + }, + [setActiveWorktree, setActiveTab, setActiveView] + ) + + // Why: a stable reference shared across every DashboardWorktreeCard so + // React.memo can actually short-circuit re-renders. An inline + // `() => setFocusedWorktreeId(card.worktree.id)` per card per render would + // mint a fresh function every render and invalidate memo on all N cards + // even when nothing else changed — the 30s `now` tick alone would cascade. + const handleCardFocus = useCallback((worktreeId: string) => setFocusedWorktreeId(worktreeId), []) + + const setKeyboardContainer = useDashboardKeyboard({ + filteredWorktrees: visibleWorktrees, + focusedWorktreeId, + setFocusedWorktreeId, + filter, + setFilter + }) + + // Why: combine the local RefObject with the keyboard hook's callback ref so + // both see the same element on attach/detach, and use the callback to drive + // focus-on-first-mount (below). A callback ref is the canonical React + // pattern for "run code when an element mounts/unmounts" and is required + // here because the container div is conditionally rendered — a RefObject + // alone wouldn't notify the keyboard hook (or the focus logic) when the + // container appears after the empty-state branch is replaced. + const setContainerRef = useCallback( + (el: HTMLDivElement | null) => { + const hadEl = containerRef.current !== null + containerRef.current = el + setKeyboardContainer(el) + // Why: focus the container the first time it becomes non-null so keyboard + // shortcuts work immediately — including on the path where the empty-state + // branch renders first (no container) and repos arrive later. A []-deps + // useEffect would fire once against a null ref on that path and never + // re-run. activeElement guard prevents stealing focus from inputs the + // user is currently typing in (e.g. sidebar search, terminal). + if (el && !hadEl) { + if (document.activeElement === null || document.activeElement === document.body) { + el.focus() + } + } + }, + [setKeyboardContainer] + ) + + const handleClearSearch = useCallback(() => setSearchQuery(''), []) + + const searchActive = searchQuery.trim().length > 0 + const showNoResults = searchActive && !hasResults + // Why: render the container unconditionally so the keyboard hook's + // callback ref fires on mount even when no repos exist yet — otherwise + // filter/arrow shortcuts don't bind until the first repo arrives. + const hasRepos = groups.length > 0 + + return ( +
+ {!hasRepos ? ( +
+
+ No repos added. Add a repo to see agent activity. +
+
+ ) : ( + <> +
+
+ + setSearchQuery(e.target.value)} + placeholder="Search..." + className="h-7 pl-7 pr-7 text-[11px] border-none bg-muted/50 shadow-none focus-visible:ring-1 focus-visible:ring-ring/30" + /> + {searchActive && ( + + )} +
+
+ +
+
+ +
+ {hasResults ? ( +
+ {filteredGroups.map((group, groupIdx) => { + const isCollapsed = collapsedRepos.has(group.repo.id) + // Why: per-repo stats replace the global stats strip that used + // to sit above the whole dashboard. Counts live at the scope + // of the grouping so the user sees per-repo agent load instead + // of a rollup that hides which repo is busy. Counts come from + // useDashboardFilter's memo so this doesn't re-walk every agent + // in every worktree on each `now` tick or search change. + const { running: groupRunning, blocked: groupBlocked, done: groupDone } = group + const Icon = isCollapsed ? ChevronRight : ChevronDown + return ( +
+ {/* Why: the repo header is a lightweight row, not a card — + no background fill, no border box. It stays an + expand/collapse control so users can hide repos they + aren't watching, but it doesn't wrap the children in + chrome that duplicates the worktree row's own borders. */} + + {!isCollapsed && + group.worktrees.map((card, i) => ( + + ))} +
+ ) + })} +
+ ) : ( +
+
+ {showNoResults + ? 'No matches.' + : filter === 'active' + ? 'No active agents.' + : filter === 'blocked' + ? 'No agents are blocked.' + : filter === 'done' + ? 'No completed agents to show.' + : 'No agent activity yet.'} +
+ {showNoResults ? ( + + ) : ( + filter !== 'all' && ( + + ) + )} +
+ )} +
+ + )} +
+ ) +}) + +export default AgentDashboard diff --git a/src/renderer/src/components/dashboard/DashboardAgentRow.tsx b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx new file mode 100644 index 000000000..cf52937fe --- /dev/null +++ b/src/renderer/src/components/dashboard/DashboardAgentRow.tsx @@ -0,0 +1,462 @@ +import React, { useState, useCallback } from 'react' +import { X, Wrench, ChevronDown } from 'lucide-react' +import { cn } from '@/lib/utils' +import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip' +import { AgentStateDot, agentStateLabel, type AgentDotState } from '@/components/AgentStateDot' +import { AgentIcon } from '@/lib/agent-catalog' +import { agentTypeToIconAgent, formatAgentTypeLabel } from '@/lib/agent-status' +import CommentMarkdown from '@/components/sidebar/CommentMarkdown' +import type { AgentStatusState } from '../../../../shared/agent-status-types' +import type { DashboardAgentRow as DashboardAgentRowData } from './useDashboardData' + +// Why: the dashboard tracks its own rollup states (incl. 'idle'); narrow to the +// shared dot states for rendering, falling back to 'idle' for any unknown +// value so an unexpected state never crashes a row. +function asDotState(state: AgentStatusState | 'idle'): AgentDotState { + switch (state) { + case 'working': + case 'blocked': + case 'waiting': + case 'done': + case 'idle': + return state + default: + return 'idle' + } +} + +function formatTimeAgo(ts: number, now: number): string { + const delta = now - ts + if (delta < 60_000) { + return 'just now' + } + const minutes = Math.floor(delta / 60_000) + if (minutes < 60) { + return `${minutes}m ago` + } + const hours = Math.floor(minutes / 60) + if (hours < 24) { + return `${hours}h ago` + } + const days = Math.floor(hours / 24) + return `${days}d ago` +} + +// Why: surface the moment the agent most recently transitioned *into* done. +// When the current live state is done, use `stateStartedAt` (not `updatedAt`) +// — `updatedAt` is refreshed on within-state pings (tool/prompt) and would +// drift away from the true transition moment. For past dones, stateHistory +// entries already store the per-transition `startedAt` so we read it directly. +function lastEnteredDoneAt(agent: DashboardAgentRowData): number | null { + const entry = agent.entry + if (entry.state === 'done') { + return entry.stateStartedAt + } + for (let i = entry.stateHistory.length - 1; i >= 0; i--) { + if (entry.stateHistory[i].state === 'done') { + return entry.stateHistory[i].startedAt + } + } + return null +} + +type Props = { + agent: DashboardAgentRowData + onDismiss: (paneKey: string) => void + /** Navigate directly to the tab this agent lives in. */ + onActivate: (tabId: string) => void + /** + * Why: the relative-time labels ("Xm ago") need a periodic re-render to stay + * honest. We accept `now` from a parent container so a single 30s tick owned + * by the container drives every visible row, rather than each row running + * its own setInterval. See useNow.ts for the shared hook — callers own the + * tick (AgentDashboard for the dashboard, AgentStatusHover for hovercards). + */ + now: number +} + +const DashboardAgentRow = React.memo(function DashboardAgentRow({ + agent, + onDismiss, + onActivate, + now +}: Props) { + const [expanded, setExpanded] = useState(false) + // Why: stop propagation so clicking the X doesn't also fire the worktree + // card's click handler (which navigates away from the dashboard). + const handleDismiss = useCallback( + (e: React.MouseEvent) => { + e.stopPropagation() + onDismiss(agent.paneKey) + }, + [onDismiss, agent.paneKey] + ) + // Why: the chevron toggles expand-collapse and must not propagate — clicks + // on it would otherwise bubble to the row's activate handler and navigate + // away the instant the user tried to reveal the full text. Stop mousedown + // too so focus-based navigation on the parent can't fire first. + const handleToggleExpand = useCallback((e: React.MouseEvent) => { + e.preventDefault() + e.stopPropagation() + setExpanded((prev) => !prev) + }, []) + const stopMouseDown = useCallback((e: React.MouseEvent) => { + e.stopPropagation() + }, []) + // Why: nested buttons (dismiss X, expand chevron) are real + + + Dismiss + + + + )} + {/* Why: when there is no timestamp yet (fresh agent, never + reported), the grid slot above does not render — show the X + as a standalone hover-only control so dismiss is still + reachable. Rare path; most rows have a timestamp the moment + they start. */} + {startedAt === null && doneAt === null && ( + + + + + + Dismiss + + + )} + {/* Why: chevron points down when collapsed (content below is + available) and rotates 180° to point up when expanded + (content is showing above the fold line). Single glyph + with a transform animates smoothly; swapping between two + glyphs (ChevronDown / ChevronUp) would snap because the + old node unmounts. Invisible placeholder keeps vertical + alignment stable across rows when nothing is expandable + so the row-trailing edge stays stable. */} + + + + {/* Why: tool row and message row both carry different info — tool shows + the mechanical step (Bash: ...), message shows the agent's narration + ("let me verify the test ordering"). Rendering both together would + cause the row to jump whenever one appeared/disappeared mid-turn, + so instead we always render both slots and fall back to a single-line + placeholder when empty. Tool slot only reserves height while working, + since done/blocked rows shouldn't show a dangling wrench. */} + {isWorking && ( +
+ {toolName ? ( + <> + {/* Why: header (wrench + tool name) stays on one line. When + collapsed, the input truncates inline next to the name. When + expanded, the input moves to its own block below so long + commands wrap to a consistent left margin instead of the + jagged shape that flex-wrapping produces. */} +
+ + {toolName} + {!expanded && toolInput && ( + + {toolInput} + + )} +
+ {/* Why: grid-rows [0fr]→[1fr] is the CSS-only height animation + pattern — outer grid track interpolates smoothly while the + inner min-h-0 + overflow-hidden clips content during the + transition. This avoids measuring heights in JS and still + animates unknown content sizes. */} + {toolInput && ( +
+
+                    {toolInput}
+                  
+
+ )} + + ) : ( + ' ' + )} +
+ )} + {/* Why: message slot is always reserved in collapsed view so the row + height stays fixed as lastAssistantMessage arrives/clears. The + expand animation lives on the CommentMarkdown itself (height + + interpolate-size) so the body reveals smoothly instead of snapping + open. When the message is empty we still render a placeholder in + the collapsed view to preserve the reserved line height. */} + {lastAssistantMessage ? ( + /'s preserved + // newlines don't break out of the truncation container. The + // `!` prefixes override CommentMarkdown's own layout styles so + // nothing (margins, list markers, block line-breaks) can push + // the preview onto a second line. + !expanded && + 'truncate whitespace-nowrap [&_*]:inline [&_*]:!whitespace-nowrap [&_*]:!m-0 [&_*]:!p-0 [&_ul]:list-none [&_ol]:list-none [&_br]:hidden' + )} + title={!expanded ? lastAssistantMessage : undefined} + /> + ) : ( + !expanded && ( +
+ ) + )} + + ) +}) + +export default DashboardAgentRow diff --git a/src/renderer/src/components/dashboard/DashboardFilterBar.tsx b/src/renderer/src/components/dashboard/DashboardFilterBar.tsx new file mode 100644 index 000000000..329d6201c --- /dev/null +++ b/src/renderer/src/components/dashboard/DashboardFilterBar.tsx @@ -0,0 +1,41 @@ +import React from 'react' +import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group' +import type { DashboardFilter } from './useDashboardFilter' + +const FILTERS: { value: DashboardFilter; label: string }[] = [ + { value: 'all', label: 'All' }, + { value: 'active', label: 'Active' }, + { value: 'blocked', label: 'Blocked' }, + { value: 'done', label: 'Done' } +] + +type Props = { + value: DashboardFilter + onChange: (value: DashboardFilter) => void +} + +const DashboardFilterBar = React.memo(function DashboardFilterBar({ value, onChange }: Props) { + return ( + { + // ToggleGroup fires empty string when deselecting — keep current filter + if (v) { + onChange(v as DashboardFilter) + } + }} + variant="outline" + size="sm" + className="gap-0" + > + {FILTERS.map((f) => ( + + {f.label} + + ))} + + ) +}) + +export default DashboardFilterBar diff --git a/src/renderer/src/components/dashboard/DashboardWorktreeCard.tsx b/src/renderer/src/components/dashboard/DashboardWorktreeCard.tsx new file mode 100644 index 000000000..7669b5bb3 --- /dev/null +++ b/src/renderer/src/components/dashboard/DashboardWorktreeCard.tsx @@ -0,0 +1,141 @@ +import React, { useCallback } from 'react' +import { cn } from '@/lib/utils' +import { useAppStore } from '@/store' +import DashboardAgentRow from './DashboardAgentRow' +import type { DashboardWorktreeCard as DashboardWorktreeCardData } from './useDashboardData' + +type Props = { + card: DashboardWorktreeCardData + /** True when this worktree is the one the user is currently viewing. */ + isActive: boolean + /** + * Why: accepts the worktree id (not a SyntheticEvent) so the parent can pass + * a single stable callback shared across all cards instead of minting a + * fresh `() => setFocusedWorktreeId(id)` closure per card per render — that + * inline lambda would invalidate React.memo on every AgentDashboard render. + */ + onFocus: (worktreeId: string) => void + onDismissAgent: (paneKey: string) => void + /** Navigate to a specific tab inside this card's worktree. */ + onActivateAgentTab: (worktreeId: string, tabId: string) => void + isLast: boolean + /** + * Why: `now` is owned by the dashboard container and threaded through every + * card to its rows. One shared 30s tick re-renders all visible "Xm ago" + * labels instead of each row owning its own setInterval (which would fire N + * times per cycle, staggered by mount time). + */ + now: number +} + +const DashboardWorktreeCard = React.memo(function DashboardWorktreeCard({ + card, + isActive, + onFocus, + onDismissAgent, + onActivateAgentTab, + isLast, + now +}: Props) { + const setActiveWorktree = useAppStore((s) => s.setActiveWorktree) + const setActiveView = useAppStore((s) => s.setActiveView) + + // Why: clicking a worktree row only navigates. It does NOT dismiss retained + // done agents — the user may have multiple agents done (e.g. Claude + Codex) + // and silently dropping any of them on row click erases a signal they were + // about to click through to investigate. Dismissal happens only through the + // explicit X button on each agent row. + const handleClick = useCallback(() => { + setActiveWorktree(card.worktree.id) + setActiveView('terminal') + }, [card.worktree.id, setActiveWorktree, setActiveView]) + + // Why: clicking an agent row only navigates to that agent's tab. It must not + // call onCheck() — that would mark the worktree as checked AND dismiss all + // retained done rows in it, which erases the signal the user was clicking + // through to investigate. Only the X button on a done row should dismiss it. + const handleActivateAgent = useCallback( + (tabId: string) => { + onActivateAgentTab(card.worktree.id, tabId) + }, + [card.worktree.id, onActivateAgentTab] + ) + + // Why: React's onFocus handler receives a SyntheticEvent, but the parent + // needs the worktree id. Wrap here so the parent can pass a single stable + // callback that does not get invalidated per-card per-render. + const handleFocus = useCallback(() => { + onFocus(card.worktree.id) + }, [onFocus, card.worktree.id]) + + const branchName = card.worktree.branch?.replace(/^refs\/heads\//, '') ?? '' + + // Why: the card is a clickable *surface* but NOT a `role="button"` — its + // children (DashboardAgentRow) render real + + {/* Body: full AgentDashboard */} + {!collapsed && ( +
+ +
+ )} + + ) +} diff --git a/src/renderer/src/components/right-sidebar/index.tsx b/src/renderer/src/components/right-sidebar/index.tsx index b95a85d4f..94bb9a1ec 100644 --- a/src/renderer/src/components/right-sidebar/index.tsx +++ b/src/renderer/src/components/right-sidebar/index.tsx @@ -6,6 +6,7 @@ import { cn } from '@/lib/utils' import { useSidebarResize } from '@/hooks/useSidebarResize' import type { RightSidebarTab, ActivityBarPosition } from '@/store/slices/editor' import type { CheckStatus } from '../../../../shared/types' +import { AGENT_DASHBOARD_ENABLED } from '../../../../shared/constants' import { isFolderRepo } from '../../../../shared/repo-kind' import { findWorktreeById } from '@/store/slices/worktree-helpers' import { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from '@/components/ui/tooltip' @@ -21,6 +22,7 @@ import FileExplorer from './FileExplorer' import SourceControl from './SourceControl' import SearchPanel from './Search' import ChecksPanel from './ChecksPanel' +import DashboardBottomPanel from './DashboardBottomPanel' import PortsPanel from './PortsPanel' const MIN_WIDTH = 220 @@ -123,6 +125,12 @@ function RightSidebarInner(): React.JSX.Element { const checksStatus = useAppStore(getActiveChecksStatus) const activityBarPosition = useAppStore((s) => s.activityBarPosition) const setActivityBarPosition = useAppStore((s) => s.setActivityBarPosition) + // Why: the bottom-docked agent dashboard is opt-out via Settings → Agents. + // Users who prefer a quieter sidebar can hide the panel without losing any + // in-terminal agent status — the per-tab status indicators remain. While + // settings are still loading, render the panel so it doesn't flash in once + // settings arrive. + const showAgentDashboard = useAppStore((s) => s.settings?.showAgentDashboard !== false) // Why: source control and checks are meaningless for non-git folders. // Hide those tabs so the activity bar only shows relevant actions. @@ -235,11 +243,18 @@ function RightSidebarInner(): React.JSX.Element { that froze the app for seconds on Windows. Each panel now reacts to activeWorktreeId changes via store subscriptions and reset effects, keeping the component instance alive across switches. */} - {effectiveTab === 'explorer' && } - {effectiveTab === 'search' && } - {effectiveTab === 'source-control' && } - {effectiveTab === 'checks' && } - {effectiveTab === 'ports' && } + {/* Why: the active tab content takes the top of the sidebar. The agent + dashboard docks at the bottom regardless of which tab is selected, + so users keep a glanceable view of agent status while they browse + files, search, etc. */} +
+ {effectiveTab === 'explorer' && } + {effectiveTab === 'search' && } + {effectiveTab === 'source-control' && } + {effectiveTab === 'checks' && } + {effectiveTab === 'ports' && } +
+ {AGENT_DASHBOARD_ENABLED && showAgentDashboard && } ) diff --git a/src/renderer/src/components/settings/AgentsPane.tsx b/src/renderer/src/components/settings/AgentsPane.tsx index 980f713a5..aa2b76e7e 100644 --- a/src/renderer/src/components/settings/AgentsPane.tsx +++ b/src/renderer/src/components/settings/AgentsPane.tsx @@ -1,6 +1,7 @@ import { useEffect, useMemo, useState } from 'react' import { Check, ChevronDown, ExternalLink, RefreshCw, Terminal } from 'lucide-react' import type { GlobalSettings, TuiAgent } from '../../../../shared/types' +import { AGENT_DASHBOARD_ENABLED } from '../../../../shared/constants' import { AGENT_CATALOG, AgentIcon } from '@/lib/agent-catalog' import { useDetectedAgents } from '@/hooks/useDetectedAgents' import { Button } from '../ui/button' @@ -246,8 +247,50 @@ export function AgentsPane({ settings, updateSettings }: AgentsPaneProps): React defaultAgent === null || (defaultAgent !== 'blank' && !detectedIds?.has(defaultAgent)) const isBlankDefault = defaultAgent === 'blank' + // Why: match right-sidebar's `s.settings?.showAgentDashboard !== false` read. + // Persisted settings from older versions may be missing this field — treating + // `undefined` as "on" here keeps the toggle's displayed state in sync with + // the sidebar's actual rendering, so the UI never contradicts itself. + const showDashboard = settings.showAgentDashboard !== false + return (
+ {/* Dashboard visibility */} + {AGENT_DASHBOARD_ENABLED && ( +
+
+
+ + Show Agent Dashboard + +

+ Show the live agent activity panel docked at the bottom of the right sidebar — + surfaces working, blocked, and done agents across all open worktrees. +

+
+ +
+
+ )} + {/* Default agent picker */}
diff --git a/src/renderer/src/components/sidebar/AgentStatusHover.tsx b/src/renderer/src/components/sidebar/AgentStatusHover.tsx index a03c9f69c..6e54861e1 100644 --- a/src/renderer/src/components/sidebar/AgentStatusHover.tsx +++ b/src/renderer/src/components/sidebar/AgentStatusHover.tsx @@ -1,188 +1,56 @@ import React, { useCallback, useMemo } from 'react' import { useShallow } from 'zustand/react/shallow' -import { X } from 'lucide-react' import { HoverCard, HoverCardTrigger, HoverCardContent } from '@/components/ui/hover-card' import { useAppStore } from '@/store' -import { AgentIcon } from '@/lib/agent-catalog' -import { AgentStateDot, type AgentDotState, agentStateLabel } from '@/components/AgentStateDot' -import { isExplicitAgentStatusFresh, agentTypeToIconAgent } from '@/lib/agent-status' +import DashboardAgentRow from '@/components/dashboard/DashboardAgentRow' +import type { DashboardAgentRow as DashboardAgentRowType } from '@/components/dashboard/useDashboardData' +import { useNow } from '@/components/dashboard/useNow' +import { isExplicitAgentStatusFresh } from '@/lib/agent-status' +import type { RetainedAgentEntry } from '@/store/slices/agent-status' +import type { TerminalTab } from '../../../../shared/types' import { AGENT_STATUS_STALE_AFTER_MS, type AgentStatusEntry } from '../../../../shared/agent-status-types' -import { cn } from '@/lib/utils' -import { EMPTY_TABS } from './WorktreeCardHelpers' -import type { RetainedAgentEntry } from '@/store/slices/agent-status' - -// Why: stable ordering used by the `rows` memo — working first, then -// blocked/waiting/permission, then done, then idle. Hoisted to module scope -// so the Record literal isn't re-allocated on every memo recompute. -const STATE_RANK: Record = { - working: 0, - blocked: 1, - waiting: 1, - permission: 1, - done: 2, - idle: 3 -} - -// Why: stable empty arrays so the narrowed selectors below can return the -// same reference when the worktree has no live/retained agents, avoiding -// unnecessary re-renders through `useShallow`'s array identity check. -const EMPTY_LIVE_ENTRIES: AgentStatusEntry[] = [] -const EMPTY_RETAINED: { paneKey: string; snapshot: RetainedAgentEntry }[] = [] - -// Why: this hovercard is intentionally self-contained in PR 3 (sidebar). The -// grouped Agent Dashboard (PR 4) will build its own view on top of the same -// store slice (`agentStatusByPaneKey` + `retainedAgentsByPaneKey`). Reading -// directly from the store here — rather than sharing a dashboard pipeline that -// doesn't exist yet — lets the sidebar ship independently and guarantees both -// PRs converge on the same source of truth without one depending on the other. -// When PR 4 lands, it will populate retainedAgentsByPaneKey via its retention -// sync effect; the union we build below already accounts for that, so no -// changes are needed here. type AgentStatusHoverProps = { worktreeId: string children: React.ReactNode } -type HoverAgentRow = { - paneKey: string - tabId: string - entry: AgentStatusEntry - dotState: AgentDotState - isRetained: boolean -} - -// Why: stale "working" entries (hook stream went silent past the freshness -// TTL) should appear as idle rather than spinning indefinitely. All other -// live states pass through 1:1 — AgentDotState is a superset of -// AgentStatusState so the cast is safe for fresh entries. -function liveEntryToDotState(entry: AgentStatusEntry, now: number): AgentDotState { - if (!isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { - return 'idle' - } - return entry.state as AgentDotState -} - -function truncatePrompt(value: string, max = 80): string { - if (!value) { - return '' - } - if (value.length <= max) { - return value - } - return `${value.slice(0, max - 1).trimEnd()}…` -} - -type InlineAgentRowProps = { - row: HoverAgentRow - onDismiss: (paneKey: string) => void - onActivate: (tabId: string) => void -} - -// Why: defined at module scope (memoized) rather than inside the hovercard so -// the row implementation is stable across re-renders and obviously shared -// between live and retained entries — the only difference between them for -// display purposes is the isRetained flag. -const InlineAgentRow = React.memo(function InlineAgentRow({ - row, - onDismiss, - onActivate -}: InlineAgentRowProps) { - const { entry, dotState, isRetained, tabId, paneKey } = row - const iconAgent = agentTypeToIconAgent(entry.agentType) - const prompt = truncatePrompt(entry.prompt) - const label = prompt || agentStateLabel(dotState) - - const handleActivateClick = useCallback(() => { - onActivate(tabId) - }, [onActivate, tabId]) - - const handleDismissClick = useCallback( - (e: React.MouseEvent) => { - // Why: the activate button sits next to this one inside a shared row - // container (not a nested button — nesting - -
- ) -}) +// Why: stable empty-array references so narrow selectors return the same +// reference when there's nothing for this worktree. Without stable empties, +// zustand's shallow equality would see a new `[]` every render and trigger +// unnecessary re-renders — defeating the purpose of the narrow selector. +const EMPTY_TABS: TerminalTab[] = [] +const EMPTY_LIVE_ENTRIES: AgentStatusEntry[] = [] +const EMPTY_RETAINED: RetainedAgentEntry[] = [] +// Why: the hovercard must render the exact same information the per-worktree +// dashboard card shows — hook-reported agents plus any retained "done" +// snapshots. We intentionally do NOT call useDashboardData() + +// enrichGroupsWithRetained() here, even though that would centralize the row- +// building logic. AgentStatusHover wraps every WorktreeCard, so reusing the +// full dashboard pipeline would mean every agent-status event recomputes the +// entire repo × worktree × tabs × agentStatus aggregation once per card on +// screen — O(worktrees²) work per update (render amplification). Instead we +// read the store's primitive maps via narrow selectors and do a focused +// per-worktree scan that mirrors buildAgentRowsForWorktree in +// useDashboardData.ts and the retained-row merge in useRetainedAgents.ts. +// Retention state itself is still hoisted into the store (see +// useRetainedAgentsSync wired at App level), so dismissing in the hover +// reflects in the dashboard and vice versa. const AgentStatusHover = React.memo(function AgentStatusHover({ worktreeId, children }: AgentStatusHoverProps) { - // Why: narrowed selectors — this hovercard wraps every WorktreeCard's agent - // indicator, so subscribing to the three whole-store maps - // (`tabsByWorktree`, `agentStatusByPaneKey`, `retainedAgentsByPaneKey`) - // would make every card re-compute its `rows` memo on any unrelated agent - // event (the render-amplification problem flagged in review). - // - // Why two separate selectors (not one wrapper object): zustand's `shallow` - // comparator compares a plain object's keys with `Object.is` on each value. - // Because the selector body constructs fresh arrays each run, a wrapper - // `{ entries, retained }` would fail `Object.is` per-key on every unrelated - // store event and defeat `useShallow` for any worktree with at least one - // agent. Bare arrays, by contrast, are compared element-wise with - // `Object.is` (via `Array.prototype.entries`) — so when the entries haven't - // changed, identity IS preserved across runs. Mirrors the precedent in - // `WorktreeCard.tsx:115-149`. + const tabs = useAppStore((s) => s.tabsByWorktree[worktreeId]) + // Why: narrow the store subscriptions to only THIS worktree's entries via + // useShallow. AgentStatusHover wraps every WorktreeCard, so subscribing to + // the whole agentStatusByPaneKey/retainedAgentsByPaneKey map would make every + // on-screen hovercard re-render on any agent-status update anywhere — + // O(worktrees²) render amplification. Pre-filtering here means the card only + // re-renders when something relevant to THIS worktree changes. const entries = useAppStore( useShallow((s) => { const wtTabs = s.tabsByWorktree[worktreeId] ?? EMPTY_TABS @@ -190,12 +58,6 @@ const AgentStatusHover = React.memo(function AgentStatusHover({ return EMPTY_LIVE_ENTRIES } const tabIds = new Set(wtTabs.map((t) => t.id)) - - // Why: scan all live entries once, keep those whose paneKey prefix - // (`${tabId}:`) matches a tab in this worktree. The paneKey format is - // enforced by the store slice (`${tabId}:${paneId}`), so prefix - // matching is the canonical lookup path without requiring an - // auxiliary index. const out: AgentStatusEntry[] = [] for (const [paneKey, entry] of Object.entries(s.agentStatusByPaneKey)) { const sepIdx = paneKey.indexOf(':') @@ -211,112 +73,131 @@ const AgentStatusHover = React.memo(function AgentStatusHover({ return out.length > 0 ? out : EMPTY_LIVE_ENTRIES }) ) - // Why: retained snapshots for this worktree. PR 3 has no retention-sync - // hook yet, so this map is always empty here; the union is preserved so - // PR 4 can auto-populate without touching this file. - // - // Caveat (for PR 4): the `{ paneKey, snapshot }` wrapper objects below - // are freshly allocated on each selector run, so `compareIterables`' - // element-wise `Object.is` will report inequality even when the - // underlying snapshot identity is stable. That's fine while the map is - // empty, but once PR 4 populates `retainedAgentsByPaneKey` this shape - // may need a further refactor — e.g., caching wrappers by paneKey, or - // returning two parallel arrays (paneKeys + snapshots) that preserve - // per-element identity across runs. const retained = useAppStore( useShallow((s) => { - const out: { paneKey: string; snapshot: RetainedAgentEntry }[] = [] - for (const [paneKey, snapshot] of Object.entries(s.retainedAgentsByPaneKey)) { - if (snapshot.worktreeId === worktreeId) { - out.push({ paneKey, snapshot }) + const out: RetainedAgentEntry[] = [] + for (const ra of Object.values(s.retainedAgentsByPaneKey)) { + if (ra.worktreeId === worktreeId) { + out.push(ra) } } return out.length > 0 ? out : EMPTY_RETAINED }) ) - // Why: subscribe to the freshness epoch so the hovercard re-renders the - // "idle" decay the moment an entry crosses AGENT_STATUS_STALE_AFTER_MS, - // without needing a separate ticking timer in this component. + // Why: agentStatusEpoch is included in the dependency array (but not in the + // computation itself) so the memo recomputes when freshness boundaries + // expire, even if no new PTY data arrives — same rationale as + // useDashboardData. const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) - const removeAgentStatus = useAppStore((s) => s.removeAgentStatus) + const dropAgentStatus = useAppStore((s) => s.dropAgentStatus) const dismissRetainedAgent = useAppStore((s) => s.dismissRetainedAgent) const setActiveWorktree = useAppStore((s) => s.setActiveWorktree) const setActiveTab = useAppStore((s) => s.setActiveTab) const setActiveView = useAppStore((s) => s.setActiveView) - const rows = useMemo(() => { - if (entries.length === 0 && retained.length === 0) { - return [] - } + const agents = useMemo(() => { + const rows: DashboardAgentRowType[] = [] + const seenPaneKeys = new Set() + // Why: Date.now() is read inside the memo (not as a dep) so stale-decay + // recalculates whenever agentStatusEpoch ticks — same pattern as + // useDashboardData. const now = Date.now() - const seen = new Set() - const collected: HoverAgentRow[] = [] - // Why: build a tabId lookup so we can resolve the tabId from each live - // entry's paneKey (the selector already filtered to this worktree's - // tabs, so every paneKey here is guaranteed to belong to one of them). + // Why: build a tabId -> entries index once instead of re-scanning every + // agent status entry inside the per-tab loop. paneKey is formatted as + // `${tabId}:${paneId}`; splitting on the first ':' lets us bucket entries + // by tab in a single O(N) pass, turning the per-worktree build from + // O(tabs × statuses) into O(tabs + statuses). Mirrors the same index + // built in useDashboardData.buildDashboardData. `entries` is already + // pre-filtered to this worktree by the narrow selector above, so this is + // O(M) where M is this-worktree-entries, not the global map. + const entriesByTabId = new Map() for (const entry of entries) { - const paneKey = entry.paneKey - const sepIdx = paneKey.indexOf(':') - if (sepIdx <= 0) { + const colonIndex = entry.paneKey.indexOf(':') + if (colonIndex === -1) { continue } - const tabId = paneKey.slice(0, sepIdx) - collected.push({ - paneKey, - tabId, - entry, - dotState: liveEntryToDotState(entry, now), - isRetained: false - }) - seen.add(paneKey) + const tabId = entry.paneKey.slice(0, colonIndex) + const bucket = entriesByTabId.get(tabId) + if (bucket) { + bucket.push(entry) + } else { + entriesByTabId.set(tabId, [entry]) + } } - for (const { paneKey, snapshot } of retained) { - if (seen.has(paneKey)) { + // Live rows — mirror buildAgentRowsForWorktree in useDashboardData.ts. + const worktreeTabs = tabs ?? [] + for (const tab of worktreeTabs) { + const explicitEntries = entriesByTabId.get(tab.id) ?? [] + for (const entry of explicitEntries) { + // Why: decay stale working/blocked/waiting entries to 'idle' when the + // hook stream has gone silent past AGENT_STATUS_STALE_AFTER_MS. Without + // this, an agent that exited without a final update would keep the + // hover's "Running agents" count and the dashboard filters inflated + // with dead work. `done` is terminal and must NOT decay to idle — + // retention (collectRetainedAgentsOnDisappear) only keeps rows whose + // prev state was 'done', so a stale done → idle would silently drop + // the completion signal. Mirrors useDashboardData.buildAgentRowsForWorktree. + const isFresh = isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS) + const shouldDecay = + !isFresh && + (entry.state === 'working' || entry.state === 'blocked' || entry.state === 'waiting') + rows.push({ + paneKey: entry.paneKey, + entry, + tab, + agentType: entry.agentType ?? 'unknown', + state: shouldDecay ? 'idle' : entry.state, + // Why: the oldest stateHistory entry's startedAt is the agent's + // original "first seen" timestamp. When history is empty the entry + // has never transitioned state, so stateStartedAt (the moment the + // current — and only — state began) is the true first-seen + // timestamp. Do NOT fall back to updatedAt: it advances on every + // tool/prompt ping within the same state, which would corrupt + // oldest-first ordering and the "started … ago" display for + // long-running agents between state transitions. Matches + // useDashboardData's semantics exactly. + startedAt: entry.stateHistory[0]?.startedAt ?? entry.stateStartedAt + }) + seenPaneKeys.add(entry.paneKey) + } + } + + // Retained rows — mirror enrichGroupsWithRetained: add a retained snapshot + // only if it belongs to THIS worktree and no live row already occupies its + // paneKey. `retained` is already pre-filtered to this worktree by the + // narrow selector above. + for (const ra of retained) { + if (seenPaneKeys.has(ra.entry.paneKey)) { continue } - collected.push({ - paneKey, - tabId: snapshot.tab.id, - entry: snapshot.entry, - // Why: retained entries are snapshots taken at completion time, so - // their freshness is meaningful only relative to when they were - // retained. Treat them uniformly as 'done' — the dashboard (PR 4) - // will own any richer retained-state vocabulary. - dotState: 'done', - isRetained: true + rows.push({ + paneKey: ra.entry.paneKey, + entry: ra.entry, + tab: ra.tab, + agentType: ra.agentType, + state: 'done', + startedAt: ra.startedAt }) } - // Why: stable ordering using the module-scoped STATE_RANK constant. - // Within a state bucket, newer updates come first. - collected.sort((a, b) => { - const r = STATE_RANK[a.dotState] - STATE_RANK[b.dotState] - if (r !== 0) { - return r - } - return b.entry.updatedAt - a.entry.updatedAt - }) - return collected - // Why: agentStatusEpoch is a cache-busting counter, not data consumed by - // the memo body. It bumps on entry writes AND on stale-boundary ticks - // (see scheduleNextFreshnessExpiry in the agent-status slice), so listing - // it forces recomputation of `dotState` when entries decay to 'idle' even - // though the entries array itself hasn't changed. + // Why: sort oldest-first to match useDashboardData ordering — stable list + // order keeps new agents from shoving the row the user is reading. + rows.sort((a, b) => a.startedAt - b.startedAt) + return rows // eslint-disable-next-line react-hooks/exhaustive-deps - }, [entries, retained, agentStatusEpoch]) + }, [tabs, entries, retained, worktreeId, agentStatusEpoch]) - // Why: dismissing wipes both the live entry (if present) and the retained - // snapshot (if present). In PR 3 only the live removal is reachable, but - // keeping both calls here means PR 4's retention sync doesn't need to patch - // this file. + // Why: mirror AgentDashboard.handleDismissAgent so dismissing in either + // surface has identical effect — removes the live store entry and the + // retained snapshot if either is present. const handleDismissAgent = useCallback( (paneKey: string) => { - removeAgentStatus(paneKey) + dropAgentStatus(paneKey) dismissRetainedAgent(paneKey) }, - [removeAgentStatus, dismissRetainedAgent] + [dropAgentStatus, dismissRetainedAgent] ) // Why: clicking a row activates the specific tab the agent runs in. Retained @@ -343,38 +224,92 @@ const AgentStatusHover = React.memo(function AgentStatusHover({ collapses to ~3% alpha and the card looks borderless. Override to explicit light/dark tokens so the card outline reads the same in both modes. */} + {/* Why: cap the card to the viewport and let its body scroll. When a row + is expanded (tool input, prompt, or assistant message unfurled), the + content can exceed the sidebar's vertical space; without a bounded + card the hover overflows off-screen with no way to reach the rows + below. `max-h-[85vh]` + `flex flex-col` keeps the card within the + viewport, and the inner list below owns the scroll so the "Agent + activity (N)" header stays pinned. */} - {rows.length === 0 ? ( -
No running agents
- ) : ( -
-
- Running agents ({rows.length}) -
- {/* Why: same reason as the card border above — `divide-border/60` - on dark `--border` (0.07 alpha) evaluates to ~4% alpha and - the row separators disappear. Pin explicit light/dark tokens - so the dividers stay legible in either mode. */} -
- {rows.map((row) => ( -
- -
- ))} -
-
- )} +
) }) +type AgentStatusHoverContentProps = { + agents: DashboardAgentRowType[] + onDismiss: (paneKey: string) => void + onActivate: (tabId: string) => void +} + +// Why: split out so `useNow(30_000)` only runs while the hovercard body is +// actually mounted. AgentStatusHover wraps EVERY WorktreeCard in the sidebar +// and stays mounted regardless of whether the card is open, so placing the +// timer on the outer component would run one 30s interval per visible +// worktree for the entire session — strictly worse than pre-hoist, since the +// common path is that the user never opens the hovercard. HoverCardContent is +// portaled by Radix and only mounts while open, so rendering this child there +// naturally gates the timer: 0 intervals while closed, exactly 1 per open +// card. The outer component still owns the narrow store subscriptions and the +// `agents` memo so those don't re-run on every open/close, and to preserve +// the render-amplification protection that originally motivated the narrow +// selectors. +const AgentStatusHoverContent = React.memo(function AgentStatusHoverContent({ + agents, + onDismiss, + onActivate +}: AgentStatusHoverContentProps) { + // Why: own one 30s tick per OPEN hovercard instance and thread it to every + // row we render. Previously each DashboardAgentRow ran its own setInterval, + // so an N-row hovercard fired N staggered re-renders every cycle. Scoping + // this to the inner content (which only mounts while the card is open) + // keeps the overhead bounded to the card the user is actually looking at. + const now = useNow(30_000) + + if (agents.length === 0) { + return
No agent activity
+ } + + return ( +
+ {/* Why: "Agent activity" rather than "Running agents" — the list + now includes retained 'done' snapshots and stale-decayed 'idle' + rows alongside live working/blocked/waiting agents, so + "running" would be semantically inaccurate. */} +
+ Agent activity ({agents.length}) +
+ {/* Why: same reason as the card border above — `divide-border/60` + on dark `--border` (0.07 alpha) evaluates to ~4% alpha and + the row separators disappear. Pin explicit light/dark tokens + so the dividers stay legible in either mode. + Why scroll here (and not on HoverCardContent): keeping the header + pinned above a scrolling list preserves the row count as context + when one row is expanded and pushes the rest below the fold. */} +
+ {agents.map((agent) => ( +
+ +
+ ))} +
+
+ ) +}) + export default AgentStatusHover diff --git a/src/renderer/src/components/sidebar/WorktreeCard.tsx b/src/renderer/src/components/sidebar/WorktreeCard.tsx index 9189763ae..e70f7db3d 100644 --- a/src/renderer/src/components/sidebar/WorktreeCard.tsx +++ b/src/renderer/src/components/sidebar/WorktreeCard.tsx @@ -13,12 +13,9 @@ import AgentStatusHover from './AgentStatusHover' import { cn } from '@/lib/utils' import { activateAndRevealWorktree } from '@/lib/worktree-activation' import { getWorktreeStatus, type WorktreeStatus } from '@/lib/worktree-status' -import { detectAgentStatusFromTitle, isExplicitAgentStatusFresh } from '@/lib/agent-status' -import { - AGENT_STATUS_STALE_AFTER_MS, - type AgentStatusEntry -} from '../../../../shared/agent-status-types' +import { isExplicitAgentStatusFresh } from '@/lib/agent-status' import { AGENT_DASHBOARD_ENABLED } from '../../../../shared/constants' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-types' import { getRepoKindLabel, isFolderRepo } from '../../../../shared/repo-kind' import type { Worktree, Repo, PRInfo, IssueInfo } from '../../../../shared/types' import { @@ -27,7 +24,6 @@ import { CONFLICT_OPERATION_LABELS, EMPTY_TABS, EMPTY_BROWSER_TABS, - EMPTY_AGENT_ENTRIES, FilledBellIcon } from './WorktreeCardHelpers' import { IssueSection, PrSection, CommentSection } from './WorktreeCardMeta' @@ -112,56 +108,6 @@ const WorktreeCard = React.memo(function WorktreeCard({ // ── GRANULAR selectors: only subscribe to THIS worktree's data ── const tabs = useAppStore((s) => s.tabsByWorktree[worktree.id] ?? EMPTY_TABS) const browserTabs = useAppStore((s) => s.browserTabsByWorktree[worktree.id] ?? EMPTY_BROWSER_TABS) - // Why: subscribe only to the entries whose paneKey belongs to one of this - // worktree's tabs. Subscribing to the full `agentStatusByPaneKey` map would - // re-render every card on every status event across all worktrees, which is - // the render-amplification problem the PR's review focus flags. The selector - // reads `tabsByWorktree[worktree.id]` from zustand state (not external - // closure) so it stays reactive to tab-spawn/close events. `useShallow` - // keeps the array reference stable when no relevant entry actually changed, - // so the downstream `status` memo doesn't invalidate on unrelated updates. - const worktreeAgentEntries = useAppStore( - useShallow((s) => { - // Why: short-circuit when the dashboard flag is off — the status memo - // below gates the explicit-status branch on AGENT_DASHBOARD_ENABLED, so - // scanning agentStatusByPaneKey for every worktree on every store change - // is pure overhead while the flag is false. Keeping the flag check inside - // the selector body preserves reactivity if the flag ever becomes dynamic. - if (!AGENT_DASHBOARD_ENABLED) { - return EMPTY_AGENT_ENTRIES - } - const wtTabs = s.tabsByWorktree[worktree.id] - if (!wtTabs || wtTabs.length === 0) { - return EMPTY_AGENT_ENTRIES - } - const liveTabIds = new Set() - for (const t of wtTabs) { - if (t.ptyId) { - liveTabIds.add(t.id) - } - } - if (liveTabIds.size === 0) { - return EMPTY_AGENT_ENTRIES - } - const out: AgentStatusEntry[] = [] - for (const entry of Object.values(s.agentStatusByPaneKey)) { - // Why: paneKey must be `${tabId}:${paneId}`. Parse the prefix once via - // indexOf+slice and look it up in the Set for O(1) membership — the - // previous `startsWith(`${id}:`)` nested loop was O(E × T) per store - // event, matching the AgentStatusHover selector's O(E) approach. - const colonIdx = entry.paneKey.indexOf(':') - if (colonIdx <= 0) { - continue - } - const tabId = entry.paneKey.slice(0, colonIdx) - if (liveTabIds.has(tabId)) { - out.push(entry) - } - } - return out.length > 0 ? out : EMPTY_AGENT_ENTRIES - }) - ) - const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) // Why: split-pane tabs expose per-pane titles that the aggregate // `tab.title` does not preserve (onActivePaneChange overwrites it with the // focused pane's title). getWorktreeStatus needs those pane titles to keep @@ -199,111 +145,83 @@ const WorktreeCard = React.memo(function WorktreeCard({ const isDeleting = deleteState?.isDeleting ?? false - // Derive status — when the dashboard flag is on, explicit agent status - // (OSC 9999) takes precedence over heuristic title parsing per the design - // doc's per-tab precedence rule. When it is off, delegate to the canonical - // `getWorktreeStatus` so the split-pane-aware heuristic path is the single - // source of truth for the sidebar's pre-dashboard behavior. - const status: WorktreeStatus = useMemo(() => { - if (!AGENT_DASHBOARD_ENABLED) { - return getWorktreeStatus(tabs, browserTabs, runtimePaneTitlesForWorktree) - } - - const liveTabs = tabs.filter((tab) => tab.ptyId) - // Why: browser-only worktrees are still active from the user's point of - // view even when they have no PTY-backed terminal. The sidebar filter - // already treats them as active, so every navigation surface must reuse - // that rule instead of showing a misleading inactive dot. - const hasTerminals = liveTabs.length > 0 || browserTabs.length > 0 - if (!hasTerminals) { - return 'inactive' - } - - // Why: precedence is per-tab — explicit status (when fresh) wins over - // heuristics *for that tab only*. Aggregating explicit across all tabs - // before heuristics is wrong: if tab A has a fresh explicit `done` and - // tab B's title heuristically says `working`, the worktree still has a - // live working agent in B. Collect per-tab state, then reduce globally - // with priority permission > working > done. - const now = Date.now() - const freshByTabId = new Map() - for (const entry of worktreeAgentEntries) { - if (!isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { - continue - } - const colonIdx = entry.paneKey.indexOf(':') - // Why: paneKey must be `${tabId}:${paneId}`. Skip malformed entries (no - // colon or leading colon) rather than bucketing under "" — aligns with - // `buildExplicitEntriesByTabId` and the AgentStatusHover selector which - // enforce the same invariant. - if (colonIdx <= 0) { - continue - } - const tabId = entry.paneKey.slice(0, colonIdx) - const bucket = freshByTabId.get(tabId) - if (bucket) { - bucket.push(entry) - } else { - freshByTabId.set(tabId, [entry]) - } - } - - let hasPermission = false - let hasWorking = false - let hasDone = false - for (const tab of liveTabs) { - const fresh = freshByTabId.get(tab.id) - if (fresh && fresh.length > 0) { - if (fresh.some((e) => e.state === 'blocked' || e.state === 'waiting')) { - hasPermission = true - } else if (fresh.some((e) => e.state === 'working')) { - hasWorking = true - } else if (fresh.some((e) => e.state === 'done')) { - hasDone = true + // Why: the sidebar dot overlays the *stable* hook-reported states (blocked, + // waiting, done) onto the title-heuristic base. `working` remains on the + // heuristic because hook pings flip on/off mid-turn and users complained + // that the spinner flickered; the blocked/waiting/done states don't have + // that problem — they're terminal (done) or attention-needed (blocked/ + // waiting) and persist until the user acts. Retained "done" snapshots are + // consulted too so the sky dot keeps glowing after the agent process exits, + // matching the dashboard's retention behavior. + // + // Priority (highest first): permission (blocked/waiting) > done > heuristic. + // permission wins over done because a newer blocked agent in the same + // worktree means the user needs to act now, not admire a previous + // completion. + // Why: collapse live hook entries to booleans inside the selector so the + // snapshot is a stable scalar (useShallow compares element identity — an + // array of freshly-constructed {state,updatedAt} objects would never hit + // the cache and trip React's "getSnapshot should be cached" infinite-loop + // guard). Staleness is applied here too so the selector already reflects + // the 30-min TTL; agentStatusEpoch pulls in the tick that fires when a + // fresh entry crosses the stale boundary. The same useShallow wrapper + // covers hasPermission, hasLiveDone, *and* hasRetainedDone — merging the + // retained scan into the same selector avoids a second full-map iteration + // per card on every retention write (with N sidebar cards on screen a + // standalone retained selector scans Object.values(...) N times per tick). + const { hasPermission, hasLiveDone, hasRetainedDone } = useAppStore( + useShallow((s) => { + // Touch the epoch so this selector re-runs when the freshness scheduler + // ticks — otherwise a stale transition wouldn't flip the booleans until + // some unrelated store write happened to rerun us. + void s.agentStatusEpoch + const wtTabs = s.tabsByWorktree[worktree.id] ?? EMPTY_TABS + let perm = false + let live = false + if (wtTabs.length > 0) { + const tabIds = new Set(wtTabs.map((t) => t.id)) + const now = Date.now() + for (const [paneKey, entry] of Object.entries(s.agentStatusByPaneKey)) { + const sepIdx = paneKey.indexOf(':') + if (sepIdx <= 0) { + continue + } + const tabId = paneKey.slice(0, sepIdx) + if (!tabIds.has(tabId)) { + continue + } + if (!isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)) { + continue + } + if (entry.state === 'blocked' || entry.state === 'waiting') { + perm = true + } else if (entry.state === 'done') { + live = true + } } - continue } - // Why: fall back to the split-pane-aware heuristic for tabs without a - // fresh explicit entry. Consult per-pane titles first (matching - // `getWorktreeStatus`) so an idle focused pane doesn't mask a working - // background pane in the same tab. - const paneTitles = runtimePaneTitlesForWorktree[tab.id] - const titlesToCheck = - paneTitles && Object.keys(paneTitles).length > 0 ? Object.values(paneTitles) : [tab.title] - for (const title of titlesToCheck) { - const heuristic = detectAgentStatusFromTitle(title) - if (heuristic === 'permission') { - hasPermission = true + // Retained scan — one pass in the same selector avoids a second + // Object.values(...) per store tick (one per sidebar card). + let retained = false + for (const ra of Object.values(s.retainedAgentsByPaneKey)) { + if (ra.worktreeId === worktree.id) { + retained = true break } - if (heuristic === 'working') { - hasWorking = true - } } - } + return { hasPermission: perm, hasLiveDone: live, hasRetainedDone: retained } + }) + ) + const status: WorktreeStatus = useMemo(() => { if (hasPermission) { return 'permission' } - if (hasWorking) { - return 'working' - } - // Why: surface 'done' as its own status so the sidebar dot turns blue - // (sky-500/80) — matching the dashboard's done color. A completed agent - // still has a live terminal, so 'inactive' would be misleading; calling - // it 'done' keeps the two surfaces in agreement on what the agent is. - if (hasDone) { + if (hasLiveDone || hasRetainedDone) { return 'done' } - // Why: execution reaches this point only when hasTerminals is true (top guard - // returned inactive otherwise), so any worktree here has at least one live - // PTY or browser tab — both are "active from the user's point of view". - return 'active' - // Why: agentStatusEpoch is a cache-busting counter, not data consumed by - // the memo body. It forces re-derivation when an agent status entry crosses - // the freshness threshold so the visual status updates without polling. - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [tabs, browserTabs, worktreeAgentEntries, runtimePaneTitlesForWorktree, agentStatusEpoch]) + return getWorktreeStatus(tabs, browserTabs, runtimePaneTitlesForWorktree) + }, [tabs, browserTabs, runtimePaneTitlesForWorktree, hasPermission, hasLiveDone, hasRetainedDone]) const showPR = cardProps.includes('pr') const showCI = cardProps.includes('ci') diff --git a/src/renderer/src/components/terminal-pane/TerminalPane.tsx b/src/renderer/src/components/terminal-pane/TerminalPane.tsx index 47bc4e84f..dae5693a5 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPane.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPane.tsx @@ -305,9 +305,11 @@ export default function TerminalPane({ // a single split pane doesn't go through closeTab. useAppStore.getState().setCacheTimerStartedAt(`${tabId}:${paneId}`, null) syncPanePtyLayoutBinding(paneId, null) - // Why: pane teardown can bypass the PTY exit callback ordering, so - // explicit agent status must be cleared on the direct UI close path too. - useAppStore.getState().removeAgentStatus(`${tabId}:${paneId}`) + // Why: Cmd+W on a split pane is user-initiated teardown — drop (not + // remove) so any retained `done` snapshot for this pane is also cleared + // and a same-frame live→gone transition cannot re-snapshot it via the + // retention sync. + useAppStore.getState().dropAgentStatus(`${tabId}:${paneId}`) manager.closePane(paneId) } }, diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index 5ca769258..5cf362e60 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -256,6 +256,14 @@ export function connectPanePty( deps.setCacheTimerStartedAt(cacheKey, null) // Why: the agent process is gone, so its explicit status is no longer meaningful. // Remove the entry so the hover UI does not show stale "working" for a dead agent. + // + // TODO(#1167): this path only fires on idle→shell title transitions, which + // means Ctrl+C'd `working` rows (Codex, Gemini, OpenCode — agents with no + // interrupt hook) linger until the 30-min AGENT_STATUS_STALE_AFTER_MS TTL + // decays them to idle or the pane/tab is closed. PR #1167 replaces this + // heuristic with authoritative foreground-process tracking in main so the + // row drops within 2s of the CLI process exiting. See branch + // brennanb2025/foreground-process-agent-exit. useAppStore.getState().removeAgentStatus(cacheKey) } // Why: inject ORCA_PANE_KEY so global Claude/Codex hooks can attribute their diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts index a67e43d87..a06646ac3 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts @@ -503,10 +503,11 @@ export function useTerminalPaneLifecycle({ syncPanePtyLayoutBinding(paneId, null) clearTabPtyId(tabId, ptyId) } - // Why: closing a pane can destroy the transport before its PTY-exit - // callback runs, so clear pane-scoped agent status during teardown - // instead of relying on PTY lifecycle ordering. - useAppStore.getState().removeAgentStatus(`${tabId}:${paneId}`) + // Why: closing a pane is user-initiated teardown of this row — drop + // (not remove) so any retained `done` snapshot for this pane is also + // cleared and a same-frame live→gone transition cannot re-snapshot + // it via the retention sync. + useAppStore.getState().dropAgentStatus(`${tabId}:${paneId}`) transport.destroy?.() paneTransportsRef.current.delete(paneId) } diff --git a/src/renderer/src/store/slices/agent-status-drop.test.ts b/src/renderer/src/store/slices/agent-status-drop.test.ts new file mode 100644 index 000000000..08a634a6d --- /dev/null +++ b/src/renderer/src/store/slices/agent-status-drop.test.ts @@ -0,0 +1,195 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { type AgentStatusEntry } from '../../../../shared/agent-status-types' +import type { TerminalTab } from '../../../../shared/types' +import type { RetainedAgentEntry } from './agent-status' +import { createTestStore } from './store-test-helpers' + +// Why: split out from agent-status.test.ts to keep each file under the +// repo's 300-line cap for test files. This suite covers the new +// user-dismissal paths (dropAgentStatus, retentionSuppressedPaneKeys, +// clearRetentionSuppressedPaneKeys) introduced alongside the dashboard. + +describe('dropAgentStatus + retention suppressor', () => { + // Why: setAgentStatus schedules a real 30-minute freshness setTimeout via + // queueMicrotask. Use fake timers so the handle does not leak into the + // test process (see agent-status.ts line 90). + afterEach(() => { + vi.useRealTimers() + }) + + it('on a live entry: removes it, writes a suppressor, and bumps both epochs', () => { + vi.useFakeTimers() + const store = createTestStore() + store + .getState() + .setAgentStatus('tab-1:0', { state: 'working', prompt: 'p', agentType: 'claude' }) + + const agentEpochBefore = store.getState().agentStatusEpoch + const sortEpochBefore = store.getState().sortEpoch + + store.getState().dropAgentStatus('tab-1:0') + + const s = store.getState() + expect(s.agentStatusByPaneKey['tab-1:0']).toBeUndefined() + // Why: user-initiated dismissal must plant a one-shot suppressor so the + // retention sync does not resurrect the row on the next render frame. + expect(s.retentionSuppressedPaneKeys['tab-1:0']).toBe(true) + expect(s.agentStatusEpoch).toBe(agentEpochBefore + 1) + expect(s.sortEpoch).toBe(sortEpochBefore + 1) + }) + + it('on a retained-only entry: removes retained row but does NOT write a suppressor and does NOT bump agentStatusEpoch', () => { + vi.useFakeTimers() + const store = createTestStore() + const now = Date.now() + const entry: AgentStatusEntry = { + state: 'done', + prompt: '', + updatedAt: now, + stateStartedAt: now, + paneKey: 'tab-retained:0', + stateHistory: [] + } + const retained: RetainedAgentEntry = { + entry, + worktreeId: 'wt-x', + tab: { id: 'tab-retained', title: 'claude' } as unknown as TerminalTab, + agentType: 'claude', + startedAt: now + } + store.getState().retainAgents([retained]) + + const agentEpochBefore = store.getState().agentStatusEpoch + const sortEpochBefore = store.getState().sortEpoch + + store.getState().dropAgentStatus('tab-retained:0') + + const s = store.getState() + expect(s.retainedAgentsByPaneKey['tab-retained:0']).toBeUndefined() + // Why: the suppressor is consumed by collectRetainedAgentsOnDisappear, + // which only runs on live→gone transitions. A retained-only dismissal has + // no live entry to disappear, so writing a suppressor would leak forever. + expect(s.retentionSuppressedPaneKeys['tab-retained:0']).toBeUndefined() + // Why: hasLive is false, so no epoch bumps. + expect(s.agentStatusEpoch).toBe(agentEpochBefore) + expect(s.sortEpoch).toBe(sortEpochBefore) + }) + + it('drops both live and retained entries when the same paneKey has both', () => { + vi.useFakeTimers() + const store = createTestStore() + // Seed a live entry first. + store + .getState() + .setAgentStatus('tab-1:0', { state: 'working', prompt: 'p', agentType: 'claude' }) + // Seed a retained entry for the SAME paneKey. The retainAgents path is + // what the production retention sync calls on live→gone transitions; here + // we invoke it directly to construct the "both live AND retained for the + // same paneKey" state that the dropAgentStatus hasLive+hasRetained branch + // (agent-status.ts lines 301-311) handles. + const now = Date.now() + const retainedEntry: AgentStatusEntry = { + state: 'done', + prompt: '', + updatedAt: now, + stateStartedAt: now, + paneKey: 'tab-1:0', + stateHistory: [] + } + const retained: RetainedAgentEntry = { + entry: retainedEntry, + worktreeId: 'wt-x', + tab: { id: 'tab-1', title: 'claude' } as unknown as TerminalTab, + agentType: 'claude', + startedAt: now + } + store.getState().retainAgents([retained]) + + // Sanity-check the precondition: both maps carry the paneKey. + expect(store.getState().agentStatusByPaneKey['tab-1:0']).toBeDefined() + expect(store.getState().retainedAgentsByPaneKey['tab-1:0']).toBeDefined() + + const agentEpochBefore = store.getState().agentStatusEpoch + const sortEpochBefore = store.getState().sortEpoch + + store.getState().dropAgentStatus('tab-1:0') + + const s = store.getState() + // Both maps drop the paneKey in the combined branch. + expect(s.agentStatusByPaneKey['tab-1:0']).toBeUndefined() + expect(s.retainedAgentsByPaneKey['tab-1:0']).toBeUndefined() + // Why: hasLive=true, so the suppressor IS planted (mirrors the live-only + // test above). The concurrent retained entry does not change that logic — + // the live→gone transition on the next frame still needs to be suppressed. + expect(s.retentionSuppressedPaneKeys['tab-1:0']).toBe(true) + // Why: hasLive=true means both epochs bump in lockstep (same rationale + // as the live-only case). + expect(s.agentStatusEpoch).toBe(agentEpochBefore + 1) + expect(s.sortEpoch).toBe(sortEpochBefore + 1) + }) + + it('on a paneKey with neither live nor retained entry: no-op (same state reference, no epoch bumps)', () => { + vi.useFakeTimers() + const store = createTestStore() + + const agentEpochBefore = store.getState().agentStatusEpoch + const sortEpochBefore = store.getState().sortEpoch + const suppressorsBefore = store.getState().retentionSuppressedPaneKeys + const liveBefore = store.getState().agentStatusByPaneKey + const retainedBefore = store.getState().retainedAgentsByPaneKey + + store.getState().dropAgentStatus('tab-missing:0') + + const s = store.getState() + expect(s.agentStatusEpoch).toBe(agentEpochBefore) + expect(s.sortEpoch).toBe(sortEpochBefore) + // Why: the short-circuit `return s` must preserve object identity so + // consumers selecting on these slices do not re-render spuriously. + expect(s.retentionSuppressedPaneKeys).toBe(suppressorsBefore) + expect(s.agentStatusByPaneKey).toBe(liveBefore) + expect(s.retainedAgentsByPaneKey).toBe(retainedBefore) + }) + + it('setAgentStatus clears a pending suppressor so the row can be retained normally on next disappearance', () => { + vi.useFakeTimers() + const store = createTestStore() + store + .getState() + .setAgentStatus('tab-1:0', { state: 'working', prompt: 'p', agentType: 'claude' }) + store.getState().dropAgentStatus('tab-1:0') + expect(store.getState().retentionSuppressedPaneKeys['tab-1:0']).toBe(true) + + store + .getState() + .setAgentStatus('tab-1:0', { state: 'working', prompt: 'p2', agentType: 'claude' }) + + // Why: a new status event means the agent is live again — the one-shot + // suppressor must lift so the next disappearance can retain normally. + expect(store.getState().retentionSuppressedPaneKeys['tab-1:0']).toBeUndefined() + }) + + it('clearRetentionSuppressedPaneKeys removes present keys and returns a new map; absent keys are no-op (identity preserved)', () => { + vi.useFakeTimers() + const store = createTestStore() + store + .getState() + .setAgentStatus('tab-1:0', { state: 'working', prompt: 'p', agentType: 'claude' }) + store.getState().dropAgentStatus('tab-1:0') + + const suppressorsBefore = store.getState().retentionSuppressedPaneKeys + expect(suppressorsBefore['tab-1:0']).toBe(true) + + // Present-key removal: new map reference, key gone. + store.getState().clearRetentionSuppressedPaneKeys(['tab-1:0']) + const afterRemove = store.getState().retentionSuppressedPaneKeys + expect(afterRemove['tab-1:0']).toBeUndefined() + expect(afterRemove).not.toBe(suppressorsBefore) + + // Absent-key clear: no-op, same object reference. + store.getState().clearRetentionSuppressedPaneKeys(['tab-does-not-exist:0']) + const afterNoop = store.getState().retentionSuppressedPaneKeys + // Why: preserving object identity on no-op clears avoids spurious + // re-renders in any selector subscribed to retentionSuppressedPaneKeys. + expect(afterNoop).toBe(afterRemove) + }) +}) diff --git a/src/renderer/src/store/slices/agent-status-freshness-scheduler.ts b/src/renderer/src/store/slices/agent-status-freshness-scheduler.ts new file mode 100644 index 000000000..77f6ec785 --- /dev/null +++ b/src/renderer/src/store/slices/agent-status-freshness-scheduler.ts @@ -0,0 +1,73 @@ +import type { AgentStatusEntry } from '../../../../shared/agent-status-types' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../../../shared/agent-status-types' + +export type FreshnessSchedulerDeps = { + getEntries: () => AgentStatusEntry[] + bumpEpochs: () => void +} + +export type FreshnessScheduler = { + schedule: () => void + /** + * Cancel any pending freshness timer. Intended for tests that create a + * fresh store per case — production callers do not need this because the + * zustand store is a module-level singleton that lives until process exit. + */ + dispose: () => void +} + +export function createFreshnessScheduler(deps: FreshnessSchedulerDeps): FreshnessScheduler { + // Why: tests that trigger scheduling must use vi.useFakeTimers() or call + // `dispose()` in teardown — otherwise a real 30-minute setTimeout leaks + // into the test process. + let timer: ReturnType | null = null + + const clear = (): void => { + if (timer !== null) { + clearTimeout(timer) + timer = null + } + } + + const schedule = (): void => { + clear() + const entries = deps.getEntries() + if (entries.length === 0) { + return + } + const now = Date.now() + let nextExpiryAt = Number.POSITIVE_INFINITY + // Why: skip entries already past the stale boundary — they each contribute + // exactly one epoch bump at crossing, and rescheduling on them would spin + // the timer forever because the bump doesn't clear them from the map + // (retention is intentional so freshness-aware selectors can decay). + // + // Invariant: the agent-status slice always writes `updatedAt = Date.now()` + // on insert/update (see `setAgentStatus` in agent-status.ts), so a + // newly-scheduled entry cannot already be stale here. If that invariant + // ever breaks (e.g. persistence rehydrate, IPC-synced backdated entries), + // the scheduler would silently no-op and miss the epoch bump — revisit + // this filter at that time. + for (const entry of entries) { + const expiryAt = entry.updatedAt + AGENT_STATUS_STALE_AFTER_MS + if (expiryAt > now) { + nextExpiryAt = Math.min(nextExpiryAt, expiryAt) + } + } + if (!Number.isFinite(nextExpiryAt)) { + return + } + // Why: +1 ms ensures the timer fires strictly after the stale boundary, + // so isExplicitAgentStatusFresh (which uses `<=`) flips to stale when the + // timer runs. Without the +1, float/rounding could leave the entry "just + // fresh enough" at the tick, delaying the epoch bump by one tick. + const delayMs = nextExpiryAt - now + 1 + timer = setTimeout(() => { + timer = null + deps.bumpEpochs() + schedule() + }, delayMs) + } + + return { schedule, dispose: clear } +} diff --git a/src/renderer/src/store/slices/agent-status.test.ts b/src/renderer/src/store/slices/agent-status.test.ts index 33d967065..4034684c4 100644 --- a/src/renderer/src/store/slices/agent-status.test.ts +++ b/src/renderer/src/store/slices/agent-status.test.ts @@ -254,8 +254,7 @@ describe('agent status retention + prefix sweep', () => { startedAt: now } - store.getState().retainAgent(retainedA) - store.getState().retainAgent(retainedB) + store.getState().retainAgents([retainedA, retainedB]) store.getState().dismissRetainedAgentsByWorktree('wt-a') const retained = store.getState().retainedAgentsByPaneKey @@ -264,6 +263,62 @@ describe('agent status retention + prefix sweep', () => { expect(retained['tab-b:0'].worktreeId).toBe('wt-b') }) + it('dismissRetainedAgentsByWorktree plants retention suppressors for paneKeys that also have a live entry', () => { + // Why: regression guard for the "Dismiss all" resurrection bug. If a + // dismissed paneKey still has a live entry in agentStatusByPaneKey, the + // retention sync (collectRetainedAgentsOnDisappear) would re-retain the + // row the next time the live agent disappears — silently undoing the + // user's bulk dismissal. Mirror dismissRetainedAgent's hasLive-gated + // suppressor logic so the next live→gone transition is ignored. + vi.useFakeTimers() + const store = createTestStore() + const now = Date.now() + const entryA: AgentStatusEntry = { + state: 'done', + prompt: '', + updatedAt: now, + stateStartedAt: now, + paneKey: 'tab-a:0', + stateHistory: [] + } + const entryB: AgentStatusEntry = { + state: 'done', + prompt: '', + updatedAt: now, + stateStartedAt: now, + paneKey: 'tab-a:1', + stateHistory: [] + } + const retainedA: RetainedAgentEntry = { + entry: entryA, + worktreeId: 'wt-a', + tab: { id: 'tab-a', title: 'claude' } as unknown as TerminalTab, + agentType: 'claude', + startedAt: now + } + const retainedB: RetainedAgentEntry = { + entry: entryB, + worktreeId: 'wt-a', + tab: { id: 'tab-a', title: 'claude' } as unknown as TerminalTab, + agentType: 'claude', + startedAt: now + } + + // Set up a live entry for retainedA's paneKey only — retainedB is retained-only. + store + .getState() + .setAgentStatus('tab-a:0', { state: 'working', prompt: 'p', agentType: 'claude' }) + store.getState().retainAgents([retainedA, retainedB]) + store.getState().dismissRetainedAgentsByWorktree('wt-a') + + const suppressed = store.getState().retentionSuppressedPaneKeys + // hasLive → suppressor planted, so the next live→gone will not re-retain. + expect(suppressed['tab-a:0']).toBe(true) + // retained-only (no live entry) → no suppressor, to avoid indefinite + // leaks when no live→gone transition will ever fire for this paneKey. + expect(suppressed['tab-a:1']).toBeUndefined() + }) + it('pruneRetainedAgents keeps only entries whose worktreeId is in the valid set', () => { const store = createTestStore() const now = Date.now() @@ -298,8 +353,7 @@ describe('agent status retention + prefix sweep', () => { startedAt: now } - store.getState().retainAgent(retainedA) - store.getState().retainAgent(retainedB) + store.getState().retainAgents([retainedA, retainedB]) store.getState().pruneRetainedAgents(new Set(['wt-a'])) const retained = store.getState().retainedAgentsByPaneKey diff --git a/src/renderer/src/store/slices/agent-status.ts b/src/renderer/src/store/slices/agent-status.ts index 4d0df2241..7ab880ae6 100644 --- a/src/renderer/src/store/slices/agent-status.ts +++ b/src/renderer/src/store/slices/agent-status.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-lines -- Why: the agent-status slice co-locates live map, retained snapshots, retention-suppression, and tab-prefix sweep so the teardown contract stays readable end-to-end. Splitting across files would scatter the drop/remove/retain interactions that must stay in lockstep. */ import type { StateCreator } from 'zustand' import type { AppState } from '../types' import { @@ -10,6 +11,7 @@ import { } from '../../../../shared/agent-status-types' import type { TerminalTab } from '../../../../shared/types' import { isExplicitAgentStatusFresh } from '@/lib/agent-status' +import { createFreshnessScheduler } from './agent-status-freshness-scheduler' /** Snapshot of a finished (or vanished) agent status entry, kept around so * the dashboard + sidebar hover can continue showing the completion until the @@ -40,6 +42,11 @@ export type AgentStatusSlice = { * agent-status hover so the two surfaces display identical rows. */ retainedAgentsByPaneKey: Record + /** Pane keys explicitly torn down (pane close, tab close, PTY exit, manual + * dismissal) and therefore forbidden from being re-retained on their next + * disappearance. Consumed by the retention sync as a one-shot suppressor. */ + retentionSuppressedPaneKeys: Record + /** Update or insert an agent status entry from a status payload. */ setAgentStatus: ( paneKey: string, @@ -54,8 +61,21 @@ export type AgentStatusSlice = { * Used when a tab is closed — same prefix-sweep as cacheTimerByKey cleanup. */ removeAgentStatusByTabPrefix: (tabIdPrefix: string) => void - /** Retain an agent snapshot (called by the top-level retention sync effect). */ - retainAgent: (retained: RetainedAgentEntry) => void + /** Remove a single entry AND suppress re-retention on its next disappearance. + * Used for USER-INITIATED teardown — the dashboard/hover X button, and + * pane close — where the user is telling us "I'm done with this row". */ + dropAgentStatus: (paneKey: string) => void + + /** Remove all entries under a tab AND suppress re-retention for each. + * Used on tab close — the user is tearing down the whole tab, so any + * remaining agent rows (live or retained) must not reappear. */ + dropAgentStatusByTabPrefix: (tabIdPrefix: string) => void + + /** Retain agent snapshots (called by the top-level retention sync effect). + * Accepts an array so multiple agents disappearing in the same frame + * produce a single set(...) — avoids intermediate states visible + * mid-loop to consumers. */ + retainAgents: (entries: RetainedAgentEntry[]) => void /** Dismiss a retained entry by its paneKey. */ dismissRetainedAgent: (paneKey: string) => void @@ -65,53 +85,24 @@ export type AgentStatusSlice = { /** Prune retained entries whose worktreeId is not in the given set. */ pruneRetainedAgents: (validWorktreeIds: Set) => void + + /** Clear one-shot teardown suppressors after the retention sync observes + * that disappearance and decides not to retain the row. */ + clearRetentionSuppressedPaneKeys: (paneKeys: string[]) => void } export const createAgentStatusSlice: StateCreator = ( set, get ) => { - // Why: tests that call setAgentStatus must use vi.useFakeTimers() or remove the entry before teardown — otherwise a real 30-minute setTimeout leaks into the test process. - let staleExpiryTimer: ReturnType | null = null - - const clearStaleExpiryTimer = (): void => { - if (staleExpiryTimer !== null) { - clearTimeout(staleExpiryTimer) - staleExpiryTimer = null - } - } - - const scheduleNextFreshnessExpiry = (): void => { - clearStaleExpiryTimer() - - const entries = Object.values(get().agentStatusByPaneKey) - if (entries.length === 0) { - return - } - - const now = Date.now() - let nextExpiryAt = Number.POSITIVE_INFINITY - // Why: skip entries already past the stale boundary — they each contribute - // exactly one epoch bump at crossing, and rescheduling on them would spin - // the timer forever because the bump doesn't clear them from the map - // (retention is intentional so freshness-aware selectors can decay). - for (const entry of entries) { - const expiryAt = entry.updatedAt + AGENT_STATUS_STALE_AFTER_MS - if (expiryAt > now) { - nextExpiryAt = Math.min(nextExpiryAt, expiryAt) - } - } - if (!Number.isFinite(nextExpiryAt)) { - return - } - - // Why: +1 ms ensures the timer fires strictly after the stale boundary, - // so isExplicitAgentStatusFresh (which uses `<=`) flips to stale when the - // timer runs. Without the +1, float/rounding could leave the entry "just - // fresh enough" at the tick, delaying the epoch bump by one tick. - const delayMs = nextExpiryAt - now + 1 - staleExpiryTimer = setTimeout(() => { - staleExpiryTimer = null + // Why: the freshness scheduler is intentionally process-lifetime-scoped — + // no dispose path — because it matches the store's own lifetime model + // (the zustand store is a module-level singleton that lives until process + // exit). Adding a teardown hook would require a store-dispose lifecycle + // that does not exist anywhere else in the codebase. + const freshness = createFreshnessScheduler({ + getEntries: () => Object.values(get().agentStatusByPaneKey), + bumpEpochs: () => { // Why: freshness is time-based, not event-based. Advancing these epochs // at the exact stale boundary forces all freshness-aware selectors to // recompute — and re-sorts WorktreeList — even when no new PTY output @@ -121,14 +112,14 @@ export const createAgentStatusSlice: StateCreator { set((s) => { @@ -195,9 +186,9 @@ export const createAgentStatusSlice: StateCreator scheduleNextFreshnessExpiry()) + queueMicrotask(() => freshness.schedule()) }, removeAgentStatus: (paneKey) => { @@ -255,7 +260,7 @@ export const createAgentStatusSlice: StateCreator scheduleNextFreshnessExpiry()) + queueMicrotask(() => freshness.schedule()) }, removeAgentStatusByTabPrefix: (tabIdPrefix) => { @@ -280,29 +285,236 @@ export const createAgentStatusSlice: StateCreator scheduleNextFreshnessExpiry()) + queueMicrotask(() => freshness.schedule()) }, - retainAgent: (retained) => { + dropAgentStatus: (paneKey) => { + // Why: single sync read — zustand set is synchronous, so the value we + // observe inside the set callback is the same one we would re-read via + // get() immediately after. Capture it once from inside the callback + // rather than double-reading the store before and during set. + let liveExisted = false + set((s) => { + const hasLive = paneKey in s.agentStatusByPaneKey + liveExisted = hasLive + const hasRetained = paneKey in s.retainedAgentsByPaneKey + // Why: bail when there is genuinely nothing to do. The old guard + // `!hasLive && !hasRetained && alreadySuppressed` leaked a phantom + // suppressor write in the `!hasLive && !hasRetained && !alreadySuppressed` + // case. With the hasLive-gated suppressor below, a no-op drop on a + // paneKey with no live and no retained entry truly has nothing to + // change, so short-circuit here. + if (!hasLive && !hasRetained) { + return s + } + + const nextLive = hasLive ? { ...s.agentStatusByPaneKey } : s.agentStatusByPaneKey + if (hasLive) { + delete nextLive[paneKey] + } + + const nextRetained = hasRetained + ? { ...s.retainedAgentsByPaneKey } + : s.retainedAgentsByPaneKey + if (hasRetained) { + delete nextRetained[paneKey] + } + + // Why: explicit teardown means "the user is done with this row", so + // the next retention sync must not resurrect it from the previous frame. + // + // Why same-frame race is acceptable: if dropAgentStatus fires in the + // same React frame as setAgentStatus, before useRetainedAgentsSync's + // prevAgentsRef has captured the live entry, the planted suppressor + // may never be consumed by a live→gone transition and would persist. + // In practice suppressors are bounded by user-dismissed paneKeys (a + // small set), so the leak is pragmatically inert — accepting it is + // cheaper than threading frame-level ordering guarantees through the + // retention sync. + // + // Why gate on hasLive: the suppressor is a one-shot flag consumed by + // `collectRetainedAgentsOnDisappear` (useRetainedAgents.ts), which + // iterates the PREVIOUS render's LIVE agents to decide what to + // retain. If we dismiss a retained-only row (no live entry at drop + // time), no live→gone transition will ever fire for this paneKey, so + // the suppressor would never be consumed and would leak indefinitely + // — only clearing if the same paneKey later became live again via + // setAgentStatus. A retained-only dismissal just needs the retained + // entry removed; there is no live-agent resurrection risk to guard + // against. Only spread retentionSuppressedPaneKeys when hasLive. + // + // Why the `!(paneKey in s.retentionSuppressedPaneKeys)` check: if a + // suppressor is already present, re-spreading produces a new object + // reference with identical contents and spuriously re-renders any + // subscriber selecting on retentionSuppressedPaneKeys. Mirror the + // guard used in setAgentStatus. + const needsSuppressorWrite = hasLive && !(paneKey in s.retentionSuppressedPaneKeys) + + return { + agentStatusByPaneKey: nextLive, + retainedAgentsByPaneKey: nextRetained, + ...(needsSuppressorWrite + ? { + retentionSuppressedPaneKeys: { + ...s.retentionSuppressedPaneKeys, + [paneKey]: true + } + } + : {}), + agentStatusEpoch: hasLive ? s.agentStatusEpoch + 1 : s.agentStatusEpoch, + // Why: mirrors removeAgentStatus — dropping a live working/blocked + // agent changes its contribution to the worktree sort score, so the + // sidebar smart-sort must recompute. Without this bump, a user- + // initiated dismissal via the dashboard/hovercard would leave the + // sidebar ordering stale until some unrelated event repaired it. + sortEpoch: hasLive ? s.sortEpoch + 1 : s.sortEpoch + } + }) + // Why: freshness.schedule only matters when the live map changed — + // retained-only and no-op drops don't touch it. Gate on the live + // presence observed inside set() so a noop drop on a paneKey with no + // live and no retained entry (or a retained-only dismissal) skips the + // microtask. + if (liveExisted) { + queueMicrotask(() => freshness.schedule()) + } + }, + + dropAgentStatusByTabPrefix: (tabIdPrefix) => { + const prefix = `${tabIdPrefix}:` + let hadLive = false + set((s) => { + const liveKeys = Object.keys(s.agentStatusByPaneKey).filter((k) => k.startsWith(prefix)) + const retainedKeys = Object.keys(s.retainedAgentsByPaneKey).filter((k) => + k.startsWith(prefix) + ) + if (liveKeys.length === 0 && retainedKeys.length === 0) { + return s + } + hadLive = liveKeys.length > 0 + + const nextLive = + liveKeys.length > 0 ? { ...s.agentStatusByPaneKey } : s.agentStatusByPaneKey + for (const key of liveKeys) { + delete nextLive[key] + } + + const nextRetained = + retainedKeys.length > 0 ? { ...s.retainedAgentsByPaneKey } : s.retainedAgentsByPaneKey + for (const key of retainedKeys) { + delete nextRetained[key] + } + + // Why: plant suppressors only for paneKeys that had a live entry, + // mirroring the hasLive gate in dropAgentStatus — suppressors are + // one-shot flags consumed by collectRetainedAgentsOnDisappear on a + // live→gone transition, so a suppressor on a retained-only paneKey + // would leak because no such transition will ever fire. Also skip + // keys that are already suppressed so we don't spuriously reallocate + // the suppressor map for subscribers that select on its identity. + const suppressorAdds = liveKeys.filter((k) => !(k in s.retentionSuppressedPaneKeys)) + let nextRetentionSuppressedPaneKeys = s.retentionSuppressedPaneKeys + if (suppressorAdds.length > 0) { + nextRetentionSuppressedPaneKeys = { ...s.retentionSuppressedPaneKeys } + for (const key of suppressorAdds) { + nextRetentionSuppressedPaneKeys[key] = true + } + } + + return { + agentStatusByPaneKey: nextLive, + retainedAgentsByPaneKey: nextRetained, + retentionSuppressedPaneKeys: nextRetentionSuppressedPaneKeys, + // Why: mirrors removeAgentStatusByTabPrefix — only bump the live-map + // epoch / sortEpoch when the live map actually changed. Retained-only + // sweeps do not participate in smart-sort or freshness calculations. + agentStatusEpoch: hadLive ? s.agentStatusEpoch + 1 : s.agentStatusEpoch, + sortEpoch: hadLive ? s.sortEpoch + 1 : s.sortEpoch + } + }) + if (hadLive) { + queueMicrotask(() => freshness.schedule()) + } + }, + + retainAgents: (entries) => { // Why: retained entries are a pure read-overlay — consumers read // retainedAgentsByPaneKey directly each render, so no sort/status epoch // bump is needed. Retention does not participate in sort ordering. - set((s) => ({ - retainedAgentsByPaneKey: { - ...s.retainedAgentsByPaneKey, - [retained.entry.paneKey]: retained + // Batching into a single set(...) keeps multi-agent disappearance atomic. + if (entries.length === 0) { + return + } + set((s) => { + // Why: skip the allocation + set(...) entirely when every input entry + // is already present by reference. Consumers of retainedAgentsByPaneKey + // select on its identity (dashboard + hovercard), so a spurious map + // reallocation forces re-renders even when nothing changed. Mirrors + // the identity-preservation pattern used by pruneRetainedAgents and + // clearRetentionSuppressedPaneKeys. + let changed = false + for (const retained of entries) { + if (s.retainedAgentsByPaneKey[retained.entry.paneKey] !== retained) { + changed = true + break + } } - })) + if (!changed) { + return s + } + const next = { ...s.retainedAgentsByPaneKey } + for (const retained of entries) { + // Why: INVARIANT — the map key equals retained.entry.paneKey. This + // lets callers look up a retained row by the same paneKey they use + // for agentStatusByPaneKey and keeps dismissal (dismissRetainedAgent) + // keyed on a single identifier. collectRetainedAgentsOnDisappear + // relies on this invariant too: it checks + // `retainedAgentsByPaneKey[paneKey]` to decide whether a vanished + // agent is already retained. + next[retained.entry.paneKey] = retained + } + return { retainedAgentsByPaneKey: next } + }) }, dismissRetainedAgent: (paneKey) => { + // Why: no agentStatusEpoch / sortEpoch bump here (mirrors retainAgents). + // Retained rows are a pure read-overlay on top of agentStatusByPaneKey — + // they do not contribute to smart-sort scoring (see computeSmartScore* + // in smart-sort.ts, which reads agentStatusByPaneKey only) and dashboard + // selectors re-render on retainedAgentsByPaneKey identity changes + // directly. Bumping epochs would force sidebar re-sorts and selector + // recomputations for a change that cannot affect either result. set((s) => { if (!(paneKey in s.retainedAgentsByPaneKey)) { return s } const next = { ...s.retainedAgentsByPaneKey } delete next[paneKey] - return { retainedAgentsByPaneKey: next } + // Why: mirror dropAgentStatus's hasLive-gated suppressor. If the same + // paneKey has BOTH a retained entry AND a concurrent live entry, simply + // removing the retained row leaves the live entry free to vanish + // cleanly on its next disappearance — and because + // collectRetainedAgentsOnDisappear (useRetainedAgents.ts) only skips + // paneKeys that are currently in retainedAgentsByPaneKey, the + // just-dismissed row would be resurrected by a new retention snapshot. + // Plant a one-shot suppressor so the next live→gone transition for + // this paneKey is ignored by the retention sync. + // + // Gate on `paneKey in agentStatusByPaneKey`: with no live entry there + // is no live→gone transition to guard against, and a stray suppressor + // would leak indefinitely (same rationale as dropAgentStatus). + const hasLive = paneKey in s.agentStatusByPaneKey + if (!hasLive || paneKey in s.retentionSuppressedPaneKeys) { + return { retainedAgentsByPaneKey: next } + } + return { + retainedAgentsByPaneKey: next, + retentionSuppressedPaneKeys: { + ...s.retentionSuppressedPaneKeys, + [paneKey]: true + } + } }) }, @@ -310,18 +522,52 @@ export const createAgentStatusSlice: StateCreator { let changed = false const next: Record = {} + // Why: mirror dismissRetainedAgent's hasLive-gated suppressor logic. + // When a dismissed paneKey ALSO has a concurrent live entry in + // agentStatusByPaneKey, removing the retained row alone lets the next + // live→gone transition for that paneKey re-retain the row via the + // retention sync (collectRetainedAgentsOnDisappear only skips paneKeys + // currently present in retainedAgentsByPaneKey). Without planting a + // suppressor here, "Dismiss all" for a worktree would silently + // resurrect the just-dismissed rows as soon as the live agents + // disappeared. Only plant suppressors for the hasLive subset — a stray + // suppressor on a retained-only paneKey would leak indefinitely + // because no live→gone transition would ever consume it. + const toSuppress: string[] = [] for (const [key, ra] of Object.entries(s.retainedAgentsByPaneKey)) { if (ra.worktreeId === worktreeId) { changed = true + if (key in s.agentStatusByPaneKey && !(key in s.retentionSuppressedPaneKeys)) { + toSuppress.push(key) + } continue } next[key] = ra } - return changed ? { retainedAgentsByPaneKey: next } : s + if (!changed) { + return s + } + if (toSuppress.length === 0) { + return { retainedAgentsByPaneKey: next } + } + const nextSuppressed = { ...s.retentionSuppressedPaneKeys } + for (const key of toSuppress) { + nextSuppressed[key] = true + } + return { + retainedAgentsByPaneKey: next, + retentionSuppressedPaneKeys: nextSuppressed + } }) }, pruneRetainedAgents: (validWorktreeIds) => { + // Why: deliberately does NOT sweep retentionSuppressedPaneKeys for + // pruned worktrees. PaneKeys are minted fresh when a worktree is + // re-created (worktrees keep unique tab IDs), so stale suppressors + // keyed on pruned paneKeys can never be matched by a future live entry + // — they are inert and harmless. Sweeping them would add churn for no + // observable benefit. set((s) => { let changed = false const next: Record = {} @@ -334,6 +580,21 @@ export const createAgentStatusSlice: StateCreator { + set((s) => { + let changed = false + const next = { ...s.retentionSuppressedPaneKeys } + for (const paneKey of paneKeys) { + if (!(paneKey in next)) { + continue + } + delete next[paneKey] + changed = true + } + return changed ? { retentionSuppressedPaneKeys: next } : s + }) } } } diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 72f5a5eea..348ed1dba 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -526,17 +526,13 @@ export const createTerminalSlice: StateCreator pendingColdRestoreByPtyId: nextColdRestores } }) - // Why: sweep live agent-status entries for this tab — the pane/tab state is - // gone, so any remaining status would be stale. Delegate to the agent-status - // slice so the epoch and stale-freshness timer bookkeeping stay consistent - // with other agent-status mutations. - // - // Retained agent entries (retainedAgentsByPaneKey) are INTENTIONALLY NOT - // swept here: they are worktree-scoped so a completed agent card survives - // tab close, and are pruned separately by pruneRetainedAgents when the - // worktree list refreshes, or by dismissRetainedAgentsByWorktree when the - // worktree itself is deleted. - get().removeAgentStatusByTabPrefix(tabId) + // Why: sweep live AND retained agent-status entries for this tab — closing + // the tab is the user telling us "I'm done with this session", so any + // completion snapshots it left behind (in the sidebar/hovercard) must go + // too. Use dropAgentStatusByTabPrefix (not removeAgentStatusByTabPrefix) + // so retention suppressors are planted: a live→gone transition inside the + // same frame as the tab close cannot re-snapshot a row we just dropped. + get().dropAgentStatusByTabPrefix(tabId) for (const tabs of Object.values(get().unifiedTabsByWorktree)) { const workspaceItem = tabs.find( (entry) => entry.contentType === 'terminal' && entry.entityId === tabId diff --git a/src/shared/constants.ts b/src/shared/constants.ts index d0b29ff5c..134c4b01b 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -160,6 +160,7 @@ export function getDefaultSettings(homedir: string): GlobalSettings { openLinksInApp: true, rightSidebarOpenByDefault: true, showTitlebarAgentActivity: true, + showAgentDashboard: true, showTaskProviderIcons: true, notifications: getDefaultNotificationSettings(), diffDefaultView: 'inline', diff --git a/src/shared/types.ts b/src/shared/types.ts index 2afc18397..7f66f2c7b 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -919,6 +919,16 @@ export type GlobalSettings = { rightSidebarOpenByDefault: boolean /** Whether to show the live agent activity count badge in the titlebar. */ showTitlebarAgentActivity: boolean + /** Whether to show the Agent Dashboard panel at the bottom of the right sidebar. + * Why: optional because readers use the `settings?.showAgentDashboard !== false` + * idiom (right-sidebar/index.tsx, AgentsPane.tsx) which presumes the field may + * be undefined — e.g. on first hydrate before main-process defaults apply, or + * when migrating settings persisted before this field existed. A required + * `boolean` here would make those readers' fallback branches dead-on-paper + * while still being reached at runtime, which is exactly the kind of type + * hack that drifts silently. Aligning the declaration with reader intent + * keeps the contract honest. */ + showAgentDashboard?: boolean /** Why: the Tasks sidebar label can be kept cleaner for users who do not * actively use the GitHub/Linear integrations behind it. */ showTaskProviderIcons: boolean