feat(agents): Agent Dashboard v2 — hook endpoint discovery, dashboard UI, sidebar status overlay (#1147)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -64,6 +64,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
|
||||
openLinksInApp: false,
|
||||
rightSidebarOpenByDefault: true,
|
||||
showTitlebarAgentActivity: true,
|
||||
showAgentDashboard: true,
|
||||
showTaskProviderIcons: true,
|
||||
diffDefaultView: 'inline',
|
||||
notifications: {
|
||||
|
||||
@@ -58,6 +58,7 @@ function createSettings(overrides: Partial<GlobalSettings> = {}): GlobalSettings
|
||||
openLinksInApp: false,
|
||||
rightSidebarOpenByDefault: true,
|
||||
showTitlebarAgentActivity: true,
|
||||
showAgentDashboard: true,
|
||||
showTaskProviderIcons: true,
|
||||
diffDefaultView: 'inline',
|
||||
notifications: {
|
||||
|
||||
@@ -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 <RetainedAgentsSyncGate /> (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 {
|
||||
}
|
||||
>
|
||||
<TooltipProvider delayDuration={400}>
|
||||
{/* 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. */}
|
||||
<RetainedAgentsSyncGate />
|
||||
{/* 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.
|
||||
|
||||
@@ -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<string | null>(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<Set<string>>(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<HTMLDivElement | null>(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 (
|
||||
<div
|
||||
ref={setContainerRef}
|
||||
tabIndex={-1}
|
||||
className="flex h-full w-full flex-col overflow-hidden outline-none"
|
||||
>
|
||||
{!hasRepos ? (
|
||||
<div className="flex h-full w-full items-center justify-center p-4">
|
||||
<div className="text-center text-[11px] text-muted-foreground">
|
||||
No repos added. Add a repo to see agent activity.
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex shrink-0 flex-col gap-1.5 border-b border-border/40 px-2 py-1.5">
|
||||
<div className="relative flex items-center">
|
||||
<Search className="absolute left-2 size-3.5 text-muted-foreground pointer-events-none" />
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(e) => 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 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
onClick={handleClearSearch}
|
||||
className="absolute right-1 size-5"
|
||||
aria-label="Clear search"
|
||||
>
|
||||
<X className="size-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center justify-center">
|
||||
<DashboardFilterBar value={filter} onChange={setFilter} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto scrollbar-sleek">
|
||||
{hasResults ? (
|
||||
<div className="flex flex-col">
|
||||
{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 (
|
||||
<div
|
||||
key={group.repo.id}
|
||||
// Why: the entire repo group tints on hover (children and
|
||||
// all) so the user sees a clear visual container for the
|
||||
// repo — mirroring the worktree → agent pattern where the
|
||||
// whole worktree tints when hovered and its nested agent
|
||||
// rows tint more strongly on top. No card chrome, just an
|
||||
// ambient hover.
|
||||
className={cn(
|
||||
// Why: light-mode needs to darken the surface (not add
|
||||
// a pale accent to near-white) for the container tint
|
||||
// to register. Use a subtle black alpha in light, keep
|
||||
// the original alpha-on-accent in dark (which already
|
||||
// reads as a faint lift on the dark surface).
|
||||
'transition-colors duration-100 hover:bg-black/[0.02] dark:hover:bg-accent/10',
|
||||
groupIdx !== filteredGroups.length - 1 && 'border-b border-border'
|
||||
)}
|
||||
>
|
||||
{/* 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. */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggleCollapse(group.repo.id)}
|
||||
className={cn(
|
||||
'flex w-full items-center gap-1.5 px-2.5 pt-1.5 pb-1',
|
||||
'text-left text-[11px] text-muted-foreground/80'
|
||||
)}
|
||||
aria-expanded={!isCollapsed}
|
||||
>
|
||||
<Icon className="size-3 shrink-0 text-muted-foreground/60" />
|
||||
{/* Why: mirror the sidebar's worktree list — repos are
|
||||
keyed by the FolderGit2 glyph colored with the repo's
|
||||
own badgeColor, so the dashboard header reads as the
|
||||
same repo entity a user scans for in the sidebar. */}
|
||||
<FolderGit2
|
||||
className="size-3 shrink-0"
|
||||
style={{ color: group.repo.badgeColor }}
|
||||
aria-hidden
|
||||
/>
|
||||
<span className="truncate font-medium text-foreground/80">
|
||||
{group.repo.displayName}
|
||||
</span>
|
||||
<span className="ml-auto flex shrink-0 items-center gap-2 text-[10px] text-muted-foreground">
|
||||
{groupRunning > 0 && (
|
||||
<span>
|
||||
<span className="font-semibold text-emerald-500">{groupRunning}</span>{' '}
|
||||
active
|
||||
</span>
|
||||
)}
|
||||
{groupBlocked > 0 && (
|
||||
<span>
|
||||
<span className="font-semibold text-amber-500">{groupBlocked}</span>{' '}
|
||||
blocked
|
||||
</span>
|
||||
)}
|
||||
{groupDone > 0 && (
|
||||
<span>
|
||||
<span className="font-semibold text-sky-500/80">{groupDone}</span> done
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
{!isCollapsed &&
|
||||
group.worktrees.map((card, i) => (
|
||||
<DashboardWorktreeCard
|
||||
key={card.worktree.id}
|
||||
card={card}
|
||||
isActive={activeWorktreeId === card.worktree.id}
|
||||
onFocus={handleCardFocus}
|
||||
onDismissAgent={handleDismissAgent}
|
||||
onActivateAgentTab={handleActivateAgentTab}
|
||||
isLast={i === group.worktrees.length - 1}
|
||||
now={now}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center pt-4 pb-6 gap-2">
|
||||
<div className="text-[11px] text-muted-foreground/60">
|
||||
{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.'}
|
||||
</div>
|
||||
{showNoResults ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClearSearch}
|
||||
className="text-[11px] text-primary/70 hover:text-primary hover:underline"
|
||||
>
|
||||
Clear search
|
||||
</button>
|
||||
) : (
|
||||
filter !== 'all' && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setFilter('all')}
|
||||
className="text-[11px] text-primary/70 hover:text-primary hover:underline"
|
||||
>
|
||||
Show all
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default AgentDashboard
|
||||
@@ -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<HTMLButtonElement>) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setExpanded((prev) => !prev)
|
||||
}, [])
|
||||
const stopMouseDown = useCallback((e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
}, [])
|
||||
// Why: nested buttons (dismiss X, expand chevron) are real <button>s whose
|
||||
// native Enter/Space handling fires their onClick. Stopping Enter/Space
|
||||
// propagation (not preventDefault) preserves native button activation while
|
||||
// defending against any ancestor key handlers that might otherwise react to
|
||||
// the bubbled event.
|
||||
const stopKeyDown = useCallback((e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.stopPropagation()
|
||||
}
|
||||
}, [])
|
||||
// Why: agent rows navigate directly to the agent's own tab, while the
|
||||
// surrounding worktree card navigates to whatever tab the worktree last had
|
||||
// focused. Stop propagation so the card click handler does not run second
|
||||
// and override our tab activation.
|
||||
const handleActivate = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.stopPropagation()
|
||||
onActivate(agent.tab.id)
|
||||
},
|
||||
[onActivate, agent.tab.id]
|
||||
)
|
||||
const startedAt = agent.startedAt > 0 ? agent.startedAt : null
|
||||
const doneAt = lastEnteredDoneAt(agent)
|
||||
const prompt = agent.entry.prompt.trim()
|
||||
// Why: `agent.entry.prompt` is normalized to '' when the prompt is unknown
|
||||
// (fresh agent, missing telemetry). Rendering the row with an empty primary
|
||||
// slot would collapse the text column and leave the row with no human-
|
||||
// readable label — just a state dot and icon. Fall back to the state label
|
||||
// ("Working", "Done", "Waiting", …) so every row is identifiable at a
|
||||
// glance, matching the old AgentStatusHover.tsx behavior.
|
||||
const displayLabel = prompt || agentStateLabel(asDotState(agent.state))
|
||||
// Why: the tool row describes what the agent is *currently* doing; once it
|
||||
// leaves working, that line goes stale and misleads (a done row showing
|
||||
// "Bash: pnpm test" reads as if the command is still running). Gate tool
|
||||
// fields on `state === 'working'`. The assistant message is the opposite
|
||||
// — it's the reply, most useful on `done`, so we always show it.
|
||||
const isWorking = agent.state === 'working'
|
||||
const toolName = isWorking ? (agent.entry.toolName?.trim() ?? '') : ''
|
||||
const toolInput = isWorking ? (agent.entry.toolInput?.trim() ?? '') : ''
|
||||
const lastAssistantMessage = agent.entry.lastAssistantMessage?.trim() ?? ''
|
||||
|
||||
// Why: always show the chevron to keep the row's right edge stable — a
|
||||
// conditional control would appear/disappear as agent content grows and
|
||||
// shrinks mid-turn, which reads as UI flicker. Expanding a row whose
|
||||
// content already fits is a no-op; the cost of an occasionally inert
|
||||
// toggle is much lower than layout jitter on every live row.
|
||||
|
||||
const tsParts: string[] = []
|
||||
if (startedAt !== null) {
|
||||
tsParts.push(`started ${formatTimeAgo(startedAt, now)}`)
|
||||
}
|
||||
if (doneAt !== null) {
|
||||
tsParts.push(`done ${formatTimeAgo(doneAt, now)}`)
|
||||
}
|
||||
|
||||
return (
|
||||
// Why: NOT role="button" / tabIndex={0}. The row contains real <button>
|
||||
// children (dismiss X, expand chevron) and tooltip triggers that forward
|
||||
// button semantics to their children — nesting them inside an outer
|
||||
// role=button violates ARIA's "no interactive content inside interactive
|
||||
// content" rule and breaks keyboard/AT navigation. Keyboard users reach
|
||||
// the agent via the child buttons and the tab switcher; the outer <div>
|
||||
// stays a plain clickable surface for pointer activation, mirroring the
|
||||
// pattern in DashboardBottomPanel.tsx's collapse header.
|
||||
<div
|
||||
onClick={handleActivate}
|
||||
className={cn(
|
||||
'group relative flex flex-col pl-1 pr-1.5 py-0.5',
|
||||
// Why: hover tints have to go in opposite directions per theme —
|
||||
// dark mode adds light on dark (bg-accent/30), light mode needs to
|
||||
// add *dark* on white. Alpha-on-accent in light mode collapses to
|
||||
// near-nothing because accent (#f5f5f5) is already ~white. Use a
|
||||
// black alpha overlay in light mode (mirrors WorktreeCard.tsx's
|
||||
// active-state pattern) so the lift is symmetric across themes.
|
||||
'cursor-pointer rounded-sm hover:bg-black/[0.06] dark:hover:bg-accent/30'
|
||||
)}
|
||||
title={tsParts.length > 0 ? tsParts.join(' • ') : undefined}
|
||||
>
|
||||
<div className="flex items-center gap-1.5">
|
||||
{/* Why: state indicator lives in the leading gutter so the user's
|
||||
eye can sweep one column and know which rows are working,
|
||||
waiting, or done at a glance — the list-view convention (Linear,
|
||||
GitHub issues, JetBrains TODO). Replaces the earlier left accent
|
||||
bar + right-side dot combo, which double-encoded state. Size md
|
||||
gives the glyph enough presence for the leading slot without
|
||||
overpowering the prompt text. */}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="inline-flex shrink-0 items-center justify-center">
|
||||
<AgentStateDot state={asDotState(agent.state)} size="md" />
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" sideOffset={4}>
|
||||
{agent.entry.interrupted ? 'Interrupted' : agentStateLabel(asDotState(agent.state))}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
{/* Why: identity (Claude/Codex/Gemini/…) sits inline with the prompt
|
||||
so the reader gets "state → who → what they said" left-to-right
|
||||
on the top row. The sub-rows (tool step, assistant response) are
|
||||
about the same agent and do not need the icon repeated next to
|
||||
them — keeping the icon only on the prompt row lets the sub-rows
|
||||
indent under the prompt text cleanly. */}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="inline-flex shrink-0">
|
||||
<AgentIcon agent={agentTypeToIconAgent(agent.agentType)} size={14} />
|
||||
</span>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" sideOffset={4}>
|
||||
{formatAgentTypeLabel(agent.agentType)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
{/* Why: animate between a 1-line clipped height and the content's
|
||||
natural height using Chromium's `interpolate-size: allow-keywords`
|
||||
— this is the only way to transition a `height` property to/from
|
||||
`auto` without measuring sizes in JS. Falls back to an instant
|
||||
swap in engines that don't support it. The inner span keeps
|
||||
overflow-hidden so the truncate→wrap class flip stays clipped
|
||||
during the interpolation.
|
||||
|
||||
Done and waiting rows get "unread" weight (semibold + full
|
||||
foreground) so the user can tell at a glance which rows need
|
||||
their attention. Working/idle stay at the quieter baseline
|
||||
since the state dot (spinner or neutral) is already doing the
|
||||
work. Mirrors the convention in Slack/Gmail/Linear where the
|
||||
row text thickens to signal "you haven't dealt with this yet."
|
||||
|
||||
Rendered unconditionally with a state-label fallback so rows
|
||||
without a prompt (fresh/unknown) still have a human-readable
|
||||
primary label instead of an empty text column. */}
|
||||
<span
|
||||
className={cn(
|
||||
'block min-w-0 flex-1 overflow-hidden text-[11px] leading-snug',
|
||||
'transition-[height] duration-200 ease-out [interpolate-size:allow-keywords]',
|
||||
expanded ? 'h-auto whitespace-pre-wrap break-words' : 'h-[1lh] truncate',
|
||||
agent.state === 'done' || agent.state === 'waiting' || agent.state === 'blocked'
|
||||
? 'font-semibold text-foreground'
|
||||
: 'font-medium text-foreground/90'
|
||||
)}
|
||||
// Why: tooltip should only reveal truncated prompt text — not echo state-word fallbacks
|
||||
// (e.g. "Working"/"Done") that already fit on one line and never overflow.
|
||||
title={expanded || !prompt ? undefined : displayLabel}
|
||||
>
|
||||
{displayLabel}
|
||||
</span>
|
||||
{/* Why: right cluster mirrors the screenshot reference — the status
|
||||
indicator (state dot), identity (agent icon), a muted timestamp,
|
||||
and the dismiss-X all live in one flex group on the right so
|
||||
the eye can find "who/what/when/close" in a single sweep. */}
|
||||
<span className="ml-auto flex shrink-0 items-center gap-1.5">
|
||||
{/* Why: call out cancellations explicitly — a `done` that was
|
||||
interrupted looks visually identical to a clean finish without a
|
||||
label, but the user cares a lot about the difference (their turn
|
||||
didn't complete). The tag sits before the timestamp so it reads
|
||||
as a qualifier on "done 3m ago". */}
|
||||
{agent.entry.interrupted && (
|
||||
<span className="rounded-sm bg-rose-500/15 px-1 py-px text-[9px] font-medium leading-none text-rose-400/90">
|
||||
interrupted
|
||||
</span>
|
||||
)}
|
||||
{/* Why: timestamp and dismiss-X share a single slot so passive
|
||||
rows show "time ago" and hovered rows swap in the X — no
|
||||
reserved-space gap, no competing columns. Grid stacks both
|
||||
children in cell 1,1 so the slot width is the larger of the
|
||||
two (usually the timestamp, e.g. "just now" / "12m ago"),
|
||||
which keeps the chevron's column stable whether or not the
|
||||
row is hovered. Using opacity (not display:none) lets us
|
||||
fade the crossfade instead of snapping, and keyboard focus
|
||||
on the hidden X still activates it because `opacity-0`
|
||||
doesn't remove it from the tab order. */}
|
||||
{(startedAt !== null || doneAt !== null) && (
|
||||
<span className="relative grid grid-cols-1 grid-rows-1 shrink-0 items-center justify-items-end">
|
||||
<span
|
||||
className={cn(
|
||||
'[grid-area:1/1] pointer-events-none text-[10px] leading-none text-muted-foreground/60',
|
||||
'transition-opacity duration-150',
|
||||
'group-hover:opacity-0'
|
||||
)}
|
||||
aria-hidden
|
||||
>
|
||||
{doneAt !== null
|
||||
? formatTimeAgo(doneAt, now)
|
||||
: startedAt !== null
|
||||
? formatTimeAgo(startedAt, now)
|
||||
: null}
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDismiss}
|
||||
onMouseDown={stopMouseDown}
|
||||
onKeyDown={stopKeyDown}
|
||||
className={cn(
|
||||
'[grid-area:1/1] inline-flex items-center justify-center text-muted-foreground/70 hover:text-foreground',
|
||||
'opacity-0 transition-opacity duration-150',
|
||||
'group-hover:opacity-100 focus-visible:opacity-100'
|
||||
)}
|
||||
aria-label="Dismiss agent"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" sideOffset={4}>
|
||||
Dismiss
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</span>
|
||||
)}
|
||||
{/* 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 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDismiss}
|
||||
onMouseDown={stopMouseDown}
|
||||
onKeyDown={stopKeyDown}
|
||||
className={cn(
|
||||
'inline-flex shrink-0 items-center justify-center text-muted-foreground/70 hover:text-foreground',
|
||||
'opacity-0 transition-opacity duration-150',
|
||||
'group-hover:opacity-100 focus-visible:opacity-100'
|
||||
)}
|
||||
aria-label="Dismiss agent"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="top" sideOffset={4}>
|
||||
Dismiss
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
{/* 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. */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleToggleExpand}
|
||||
onMouseDown={stopMouseDown}
|
||||
onKeyDown={stopKeyDown}
|
||||
className="inline-flex shrink-0 items-center justify-center text-muted-foreground/60 hover:text-foreground"
|
||||
aria-label={expanded ? 'Collapse details' : 'Expand details'}
|
||||
aria-expanded={expanded}
|
||||
>
|
||||
<ChevronDown
|
||||
className={cn('size-3.5 transition-transform duration-150', expanded && 'rotate-180')}
|
||||
/>
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
{/* 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 && (
|
||||
<div className="mt-0.5 min-w-0 pl-5 text-[10px] leading-snug text-muted-foreground/70">
|
||||
{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. */}
|
||||
<div
|
||||
className={cn('flex min-w-0 items-center gap-1', !expanded && 'overflow-hidden')}
|
||||
>
|
||||
<Wrench className="size-2.5 shrink-0" />
|
||||
<code className="shrink-0 font-mono text-[10px]">{toolName}</code>
|
||||
{!expanded && toolInput && (
|
||||
<span className="min-w-0 truncate text-muted-foreground/60" title={toolInput}>
|
||||
{toolInput}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{/* 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 && (
|
||||
<div
|
||||
className={cn(
|
||||
'grid transition-[grid-template-rows,margin-top] duration-200 ease-out',
|
||||
expanded ? 'mt-0.5 grid-rows-[1fr]' : 'grid-rows-[0fr]'
|
||||
)}
|
||||
>
|
||||
<pre className="min-h-0 overflow-hidden whitespace-pre-wrap break-words font-mono text-[10px] text-muted-foreground/60">
|
||||
{toolInput}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
' '
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* 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 ? (
|
||||
<CommentMarkdown
|
||||
content={lastAssistantMessage}
|
||||
// Why: animate between a 1-line clipped height and the content's
|
||||
// natural height using Chromium's `interpolate-size: allow-keywords`
|
||||
// so the message body expands/collapses smoothly instead of
|
||||
// snapping. Height transition + overflow-hidden keeps the inline-
|
||||
// flattened preview clipped during the interpolation. Render the
|
||||
// markdown in both states; in the collapsed view we force every
|
||||
// nested element inline so `truncate` can ellipsize the whole
|
||||
// thing on one line. The [&_*]:inline descendant selector flattens
|
||||
// the markdown tree (lists, pre, headings, blockquotes) into inline
|
||||
// flow; block margins and list markers are suppressed by
|
||||
// [&_*]:!m-0 / [&_ul]:list-none so the preview reads as a single
|
||||
// clean line.
|
||||
className={cn(
|
||||
'mt-0.5 overflow-hidden pl-5 text-[10px] leading-snug text-muted-foreground/80',
|
||||
'transition-[height] duration-200 ease-out [interpolate-size:allow-keywords]',
|
||||
expanded ? 'h-auto' : 'h-[1lh]',
|
||||
// Why: in collapsed mode we need a single truncated line. Markdown
|
||||
// blocks (pre, lists, headings) are flattened inline and forced
|
||||
// to inherit `white-space: nowrap` so <pre>/<code>'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 && (
|
||||
<div className="mt-0.5 pl-5 text-[10px] leading-snug text-muted-foreground/70"> </div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default DashboardAgentRow
|
||||
@@ -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
|
||||
type="single"
|
||||
value={value}
|
||||
onValueChange={(v) => {
|
||||
// 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) => (
|
||||
<ToggleGroupItem key={f.value} value={f.value} className="text-[11px] px-2.5 py-1 h-7">
|
||||
{f.label}
|
||||
</ToggleGroupItem>
|
||||
))}
|
||||
</ToggleGroup>
|
||||
)
|
||||
})
|
||||
|
||||
export default DashboardFilterBar
|
||||
@@ -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 <button>s (dismiss X, chevron),
|
||||
// and ARIA forbids interactive descendants inside a role=button ancestor
|
||||
// (screen readers flatten it, leaving the inner buttons unreachable). The
|
||||
// dashboard's keyboard hook (useDashboardKeyboard.ts) owns Enter/arrow-key
|
||||
// routing via `closest('[data-worktree-id]')`, so activation is handled
|
||||
// there — we only need the surface to be programmatically focusable
|
||||
// (tabIndex={-1}) so arrow-key navigation's `cardEl.focus()` works. This
|
||||
// mirrors the DashboardBottomPanel.tsx:247-253 pattern.
|
||||
return (
|
||||
<div
|
||||
tabIndex={-1}
|
||||
data-worktree-id={card.worktree.id}
|
||||
onClick={handleClick}
|
||||
onFocus={handleFocus}
|
||||
className={cn(
|
||||
'cursor-pointer px-2.5 py-1 transition-colors duration-100',
|
||||
// Why: light-mode hovers have to darken (not lighten) the surface —
|
||||
// `--accent` is #f5f5f5 so adding it to white lifts nothing. Use a
|
||||
// black alpha overlay in light mode and keep the original
|
||||
// alpha-on-accent for dark mode, mirroring WorktreeCard's active
|
||||
// state pattern. Focus/focused are each one step stronger than
|
||||
// hover, keeping the same hierarchy dark mode already reads.
|
||||
'hover:bg-black/[0.04] dark:hover:bg-accent/20',
|
||||
'focus-visible:outline-none focus-visible:bg-black/[0.06] dark:focus-visible:bg-accent/30',
|
||||
// Why: the persistent tint tracks the *active* worktree (the one the
|
||||
// user is viewing), not the last card that happened to receive focus.
|
||||
// Focus state sticks around after click and never clears, so using
|
||||
// it for the persistent highlight made every clicked row appear
|
||||
// selected forever; tying it to activeWorktreeId keeps the highlight
|
||||
// in sync with what the user actually has open.
|
||||
isActive && 'bg-black/[0.05] dark:bg-accent/25',
|
||||
!isLast && 'border-b border-border/80'
|
||||
)}
|
||||
>
|
||||
{/* Worktree header row. Why: workspace name + branch share one line
|
||||
to save vertical space — the branch is a secondary qualifier that
|
||||
reads fine as a muted suffix rather than its own line. */}
|
||||
<div className="flex items-baseline gap-1.5 min-w-0">
|
||||
<span className="text-[11px] font-semibold text-foreground truncate leading-tight shrink-0 max-w-[60%]">
|
||||
{card.worktree.displayName}
|
||||
</span>
|
||||
{branchName && (
|
||||
<span className="text-[10px] text-muted-foreground/60 truncate min-w-0 leading-tight">
|
||||
{branchName}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Agent rows with activity blocks */}
|
||||
{card.agents.length > 0 && (
|
||||
<div className="mt-1.5 flex flex-col divide-y divide-border">
|
||||
{card.agents.map((agent, index) => (
|
||||
<div key={agent.paneKey} className={cn(index === 0 ? 'pb-1' : 'py-1')}>
|
||||
<DashboardAgentRow
|
||||
agent={agent}
|
||||
onDismiss={onDismissAgent}
|
||||
onActivate={handleActivateAgent}
|
||||
now={now}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default DashboardWorktreeCard
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useDashboardData } from './useDashboardData'
|
||||
import { useRetainedAgentsSync } from './useRetainedAgents'
|
||||
|
||||
// Why: isolate the dashboard retention subscriptions in a leaf component that
|
||||
// renders null, so the high-churn slices read by useDashboardData
|
||||
// (agentStatusByPaneKey + agentStatusEpoch, which tick at PTY event frequency)
|
||||
// do not re-render the entire App tree. Retention must still run at the App
|
||||
// level — if it only ran when the dashboard is mounted, "done" agents would
|
||||
// vanish from the sidebar hovercard whenever the panel is collapsed.
|
||||
//
|
||||
// The hooks inside still early-return when AGENT_DASHBOARD_ENABLED is false,
|
||||
// so this gate is cheap when the feature is off.
|
||||
export default function RetainedAgentsSyncGate(): null {
|
||||
const dashboardLiveGroups = useDashboardData()
|
||||
useRetainedAgentsSync(dashboardLiveGroups)
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { isExplicitAgentStatusFresh } from '@/lib/agent-status'
|
||||
import {
|
||||
AGENT_STATUS_STALE_AFTER_MS,
|
||||
type AgentStatusEntry,
|
||||
type AgentStatusState,
|
||||
type AgentType
|
||||
} from '../../../../shared/agent-status-types'
|
||||
import { AGENT_DASHBOARD_ENABLED } from '../../../../shared/constants'
|
||||
import type { Repo, Worktree, TerminalTab } from '../../../../shared/types'
|
||||
|
||||
// ─── Dashboard data types ─────────────────────────────────────────────────────
|
||||
|
||||
export type DashboardAgentRow = {
|
||||
paneKey: string
|
||||
entry: AgentStatusEntry
|
||||
tab: TerminalTab
|
||||
agentType: AgentType
|
||||
state: AgentStatusState | 'idle'
|
||||
/** When this agent first began reporting status. Derived from the oldest
|
||||
* stateHistory entry, falling back to updatedAt when no history exists yet.
|
||||
* Used to sort agents by when they started. */
|
||||
startedAt: number
|
||||
}
|
||||
|
||||
export type DashboardWorktreeCard = {
|
||||
repo: Repo
|
||||
worktree: Worktree
|
||||
agents: DashboardAgentRow[]
|
||||
/** Highest-priority agent state for filtering.
|
||||
* Priority: blocked > working > done > idle.
|
||||
* `waiting` is folded into `blocked` — both are attention-needed states. */
|
||||
dominantState: 'working' | 'blocked' | 'done' | 'idle'
|
||||
/** Earliest startedAt across all agents in this worktree. Once the worktree
|
||||
* has at least one agent, this value is stable — new agents starting in
|
||||
* the same worktree do not change it. Sorting worktrees by this value
|
||||
* asc keeps list order stable while the user is reading. */
|
||||
earliestStartedAt: number
|
||||
}
|
||||
|
||||
export type DashboardRepoGroup = {
|
||||
repo: Repo
|
||||
worktrees: DashboardWorktreeCard[]
|
||||
}
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export function computeDominantState(
|
||||
agents: DashboardAgentRow[]
|
||||
): DashboardWorktreeCard['dominantState'] {
|
||||
if (agents.length === 0) {
|
||||
return 'idle'
|
||||
}
|
||||
let hasWorking = false
|
||||
let hasDone = false
|
||||
for (const agent of agents) {
|
||||
if (agent.state === 'blocked' || agent.state === 'waiting') {
|
||||
return 'blocked'
|
||||
}
|
||||
if (agent.state === 'working') {
|
||||
hasWorking = true
|
||||
}
|
||||
if (agent.state === 'done') {
|
||||
hasDone = true
|
||||
}
|
||||
}
|
||||
if (hasWorking) {
|
||||
return 'working'
|
||||
}
|
||||
if (hasDone) {
|
||||
return 'done'
|
||||
}
|
||||
return 'idle'
|
||||
}
|
||||
|
||||
// Why: the dashboard only surfaces agents that have reported state via a hook.
|
||||
// A tab hosting a shell, a REPL before its first turn, or an agent we have no
|
||||
// hook integration for will have no entry here — and that's correct. The
|
||||
// dashboard's job is to show *agent work in progress*, not to guess which
|
||||
// terminals might contain an agent.
|
||||
function buildAgentRowsForWorktree(
|
||||
worktreeId: string,
|
||||
tabsByWorktree: Record<string, TerminalTab[]>,
|
||||
entriesByTabId: Map<string, AgentStatusEntry[]>,
|
||||
now: number
|
||||
): DashboardAgentRow[] {
|
||||
const tabs = tabsByWorktree[worktreeId] ?? []
|
||||
const rows: DashboardAgentRow[] = []
|
||||
|
||||
for (const tab of tabs) {
|
||||
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 (30 min TTL).
|
||||
// Without this, an agent process that exited without sending a final
|
||||
// update would remain "working" forever — the Active/Blocked filters and
|
||||
// the sidebar's running-agents count would mislead the user into chasing
|
||||
// dead work. `done` is terminal and must NOT decay to idle: retention
|
||||
// (collectRetainedAgentsOnDisappear) only retains rows whose prev state
|
||||
// was 'done', so decaying a stale done → idle would silently drop the
|
||||
// completion signal when the entry later disappears.
|
||||
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. See
|
||||
// agent-status.ts (stateStartedAt carry-forward on same-state pings).
|
||||
startedAt: entry.stateHistory[0]?.startedAt ?? entry.stateStartedAt
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
function buildDashboardData(
|
||||
repos: Repo[],
|
||||
worktreesByRepo: Record<string, Worktree[]>,
|
||||
tabsByWorktree: Record<string, TerminalTab[]>,
|
||||
agentStatusByPaneKey: Record<string, AgentStatusEntry>,
|
||||
now: number
|
||||
): DashboardRepoGroup[] {
|
||||
// Why: build a tabId -> entries index once per dashboard computation 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).
|
||||
const entriesByTabId = new Map<string, AgentStatusEntry[]>()
|
||||
for (const [paneKey, entry] of Object.entries(agentStatusByPaneKey)) {
|
||||
const colonIndex = paneKey.indexOf(':')
|
||||
if (colonIndex === -1) {
|
||||
continue
|
||||
}
|
||||
const tabId = paneKey.slice(0, colonIndex)
|
||||
const bucket = entriesByTabId.get(tabId)
|
||||
if (bucket) {
|
||||
bucket.push(entry)
|
||||
} else {
|
||||
entriesByTabId.set(tabId, [entry])
|
||||
}
|
||||
}
|
||||
|
||||
return repos.map((repo) => {
|
||||
const worktrees = (worktreesByRepo[repo.id] ?? [])
|
||||
.filter((w) => !w.isArchived)
|
||||
.map((worktree) => {
|
||||
const agents = buildAgentRowsForWorktree(worktree.id, tabsByWorktree, entriesByTabId, now)
|
||||
// Why: sort agents within a worktree oldest-first by startedAt. A new
|
||||
// agent appears at the BOTTOM so it doesn't shove the row the user
|
||||
// is currently reading down the list. Stable order also means
|
||||
// retained/live transitions don't reshuffle siblings. Users care
|
||||
// less about "which is newest" than "let this list stop moving
|
||||
// while I read it".
|
||||
agents.sort((a, b) => a.startedAt - b.startedAt)
|
||||
// Why: earliestStartedAt (oldest agent in the worktree) is stable once
|
||||
// the worktree has any agent at all. Using it for outer sorts means
|
||||
// a brand-new agent in a different worktree no longer shoves this
|
||||
// card around while the user is reading.
|
||||
const earliestStartedAt = agents.length > 0 ? agents[0].startedAt : 0
|
||||
return {
|
||||
repo,
|
||||
worktree,
|
||||
agents,
|
||||
dominantState: computeDominantState(agents),
|
||||
earliestStartedAt
|
||||
} satisfies DashboardWorktreeCard
|
||||
})
|
||||
|
||||
return { repo, worktrees } satisfies DashboardRepoGroup
|
||||
})
|
||||
}
|
||||
|
||||
// ─── Hook ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function useDashboardData(): DashboardRepoGroup[] {
|
||||
const repos = useAppStore((s) => s.repos)
|
||||
const worktreesByRepo = useAppStore((s) => s.worktreesByRepo)
|
||||
const tabsByWorktree = useAppStore((s) => s.tabsByWorktree)
|
||||
const agentStatusByPaneKey = useAppStore((s) => s.agentStatusByPaneKey)
|
||||
// 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.
|
||||
const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch)
|
||||
|
||||
return useMemo(
|
||||
// Why: Date.now() is read inside the memo (not as a dep) so stale-decay
|
||||
// recalculates whenever agentStatusEpoch ticks. The epoch bumps when the
|
||||
// freshness boundary crosses, driving re-evaluation without coupling to
|
||||
// wall-clock time directly.
|
||||
() => {
|
||||
// Why: feature flag gate inside the memo avoids the O(repos × worktrees ×
|
||||
// agents) rebuild on every store update when the dashboard is disabled.
|
||||
// Store selectors still subscribe to keep rules-of-hooks satisfied even
|
||||
// if the flag becomes runtime-dynamic.
|
||||
if (!AGENT_DASHBOARD_ENABLED) {
|
||||
return []
|
||||
}
|
||||
return buildDashboardData(
|
||||
repos,
|
||||
worktreesByRepo,
|
||||
tabsByWorktree,
|
||||
agentStatusByPaneKey,
|
||||
Date.now()
|
||||
)
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[repos, worktreesByRepo, tabsByWorktree, agentStatusByPaneKey, agentStatusEpoch]
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { useState, useMemo } from 'react'
|
||||
import type {
|
||||
DashboardRepoGroup,
|
||||
DashboardWorktreeCard,
|
||||
DashboardAgentRow
|
||||
} from './useDashboardData'
|
||||
|
||||
export type DashboardFilter = 'active' | 'all' | 'blocked' | 'done'
|
||||
|
||||
export type FilteredDashboardGroup = {
|
||||
repo: DashboardRepoGroup['repo']
|
||||
worktrees: DashboardWorktreeCard[]
|
||||
/** Earliest startedAt across all worktrees in this group. Stable once the
|
||||
* group has any agent — used for deterministic ordering between groups. */
|
||||
earliestStartedAt: number
|
||||
/**
|
||||
* Why: per-repo agent state counts are computed here (inside the filter
|
||||
* memo) rather than inline in the render body of AgentDashboard. Inline
|
||||
* iteration re-walked every agent in every worktree on each `now` tick,
|
||||
* search change, or store update; precomputing keeps that O(N) scan scoped
|
||||
* to actual changes in `groups`/`filter`/`searchQuery`. Counts reflect the
|
||||
* *filtered* agents the user actually sees, which matches the header
|
||||
* numbers to the rendered rows.
|
||||
*/
|
||||
running: number
|
||||
blocked: number
|
||||
done: number
|
||||
}
|
||||
|
||||
// Why: filters apply to individual AGENTS, not worktrees. Previously we filtered
|
||||
// by the worktree's dominantState, so a done agent stayed visible under the
|
||||
// 'active' tab if a sibling agent in the same worktree was working — which
|
||||
// defeats the point of the filter. Agent-level filtering keeps the worktree
|
||||
// grouping intact but hides rows whose state doesn't match.
|
||||
function matchesAgent(agent: DashboardAgentRow, filter: DashboardFilter): boolean {
|
||||
switch (filter) {
|
||||
case 'all':
|
||||
return true
|
||||
case 'active':
|
||||
return agent.state === 'working'
|
||||
case 'blocked':
|
||||
return agent.state === 'blocked' || agent.state === 'waiting'
|
||||
case 'done':
|
||||
return agent.state === 'done'
|
||||
}
|
||||
}
|
||||
|
||||
// Why: search also matches per-agent — so a typo'd prompt in one agent doesn't
|
||||
// drag its unrelated siblings into the visible set. Repo/worktree/branch hits
|
||||
// still surface the whole worktree row (keep all its agents) because at that
|
||||
// point the user is looking for the *worktree*, not a specific agent inside it.
|
||||
function worktreeMetaMatches(card: DashboardWorktreeCard, q: string): boolean {
|
||||
if (card.repo.displayName.toLowerCase().includes(q)) {
|
||||
return true
|
||||
}
|
||||
if (card.worktree.displayName.toLowerCase().includes(q)) {
|
||||
return true
|
||||
}
|
||||
const branch = card.worktree.branch?.toLowerCase() ?? ''
|
||||
return branch.includes(q)
|
||||
}
|
||||
|
||||
function agentMatchesSearch(agent: DashboardAgentRow, q: string): boolean {
|
||||
if (agent.entry.prompt?.toLowerCase().includes(q)) {
|
||||
return true
|
||||
}
|
||||
if (agent.entry.toolName?.toLowerCase().includes(q)) {
|
||||
return true
|
||||
}
|
||||
if (agent.entry.toolInput?.toLowerCase().includes(q)) {
|
||||
return true
|
||||
}
|
||||
if (agent.entry.lastAssistantMessage?.toLowerCase().includes(q)) {
|
||||
return true
|
||||
}
|
||||
return agent.agentType.toLowerCase().includes(q)
|
||||
}
|
||||
|
||||
export function useDashboardFilter(
|
||||
groups: DashboardRepoGroup[],
|
||||
searchQuery: string
|
||||
): {
|
||||
filter: DashboardFilter
|
||||
setFilter: (f: DashboardFilter) => void
|
||||
filteredGroups: FilteredDashboardGroup[]
|
||||
hasResults: boolean
|
||||
} {
|
||||
const [filter, setFilter] = useState<DashboardFilter>('all')
|
||||
|
||||
const filteredGroups = useMemo(() => {
|
||||
const q = searchQuery.trim().toLowerCase()
|
||||
const out: FilteredDashboardGroup[] = []
|
||||
for (const group of groups) {
|
||||
const worktrees: DashboardWorktreeCard[] = []
|
||||
// Why: accumulate per-repo state counts while we already iterate the
|
||||
// filtered agents — avoids a second pass (and avoids re-walking every
|
||||
// agent in the AgentDashboard render body on every `now` tick).
|
||||
let running = 0
|
||||
let blocked = 0
|
||||
let done = 0
|
||||
for (const wt of group.worktrees) {
|
||||
const stateMatched = wt.agents.filter((a) => matchesAgent(a, filter))
|
||||
if (stateMatched.length === 0) {
|
||||
continue
|
||||
}
|
||||
const agents: DashboardAgentRow[] =
|
||||
q.length === 0 || worktreeMetaMatches(wt, q)
|
||||
? stateMatched
|
||||
: stateMatched.filter((a) => agentMatchesSearch(a, q))
|
||||
// Why: drop worktrees whose agents are all filtered out — an empty
|
||||
// row would just be noise in the list.
|
||||
if (agents.length === 0) {
|
||||
continue
|
||||
}
|
||||
for (const agent of agents) {
|
||||
if (agent.state === 'working') {
|
||||
running++
|
||||
} else if (agent.state === 'blocked' || agent.state === 'waiting') {
|
||||
blocked++
|
||||
} else if (agent.state === 'done') {
|
||||
done++
|
||||
}
|
||||
}
|
||||
// Why: recompute earliestStartedAt from the filtered agents so the
|
||||
// sort key below reflects the agents this worktree actually displays.
|
||||
// Otherwise a filter that removes the earliest-starting agent leaves
|
||||
// a phantom sort key from useDashboardData's un-filtered list and
|
||||
// worktrees drift out of order when filters/search are applied.
|
||||
// agents.length > 0 is guaranteed by the early-continue above, and
|
||||
// agents are pre-sorted asc by startedAt upstream, so agents[0] is
|
||||
// the minimum. startedAt is always set (useDashboardData derives it
|
||||
// from stateStartedAt, which is set on every entry), so no fallback
|
||||
// to wt.earliestStartedAt is needed — and using that upstream value
|
||||
// would reintroduce the exact phantom sort key this block avoids.
|
||||
const filteredEarliest = agents[0].startedAt
|
||||
// Why: preserve worktree card identity in the no-op case so
|
||||
// React.memo on DashboardWorktreeCard can short-circuit. `filter`
|
||||
// always allocates a new array even when no elements are removed, so
|
||||
// reference equality against `wt.agents` is never true — length
|
||||
// equality is our proxy for "nothing was filtered out" (safe because
|
||||
// .filter preserves order, so equal length means every element
|
||||
// passed). When agents are full AND earliestStartedAt is unchanged,
|
||||
// the upstream `wt` object is already the correct card and spreading
|
||||
// would only defeat memoization, causing every `now` tick or
|
||||
// unrelated store update to re-render all cards.
|
||||
const stateMatchedAll = stateMatched.length === wt.agents.length
|
||||
const agentsAreFull = stateMatchedAll && agents.length === wt.agents.length
|
||||
const passthrough = agentsAreFull && filteredEarliest === wt.earliestStartedAt
|
||||
worktrees.push(passthrough ? wt : { ...wt, agents, earliestStartedAt: filteredEarliest })
|
||||
}
|
||||
if (worktrees.length === 0) {
|
||||
continue
|
||||
}
|
||||
// Why: sort worktrees within a group by earliest-started agent asc.
|
||||
// Stable once populated — a new agent starting in a sibling worktree
|
||||
// doesn't reshuffle this one while the user reads.
|
||||
worktrees.sort((a, b) => a.earliestStartedAt - b.earliestStartedAt)
|
||||
out.push({
|
||||
repo: group.repo,
|
||||
worktrees,
|
||||
earliestStartedAt: worktrees[0]?.earliestStartedAt ?? 0,
|
||||
running,
|
||||
blocked,
|
||||
done
|
||||
})
|
||||
}
|
||||
// Why: sort groups by the earliest-started worktree asc for the same
|
||||
// "stop moving while I read" reason. Repos with no activity yet get 0
|
||||
// and fall to the top, which is fine since they render empty anyway.
|
||||
out.sort((a, b) => a.earliestStartedAt - b.earliestStartedAt)
|
||||
return out
|
||||
}, [groups, filter, searchQuery])
|
||||
|
||||
// Why: filteredGroups drops any group whose worktrees array is empty (see the
|
||||
// early-continue above), so a non-empty groups array guarantees at least one
|
||||
// visible worktree. Avoids an extra flatMap just to check length.
|
||||
const hasResults = filteredGroups.length > 0
|
||||
|
||||
return {
|
||||
filter,
|
||||
setFilter,
|
||||
filteredGroups,
|
||||
hasResults
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
import { useEffect, useCallback, useRef, useState } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import type { DashboardWorktreeCard } from './useDashboardData'
|
||||
import type { DashboardFilter } from './useDashboardFilter'
|
||||
|
||||
type UseDashboardKeyboardParams = {
|
||||
filteredWorktrees: DashboardWorktreeCard[]
|
||||
focusedWorktreeId: string | null
|
||||
setFocusedWorktreeId: (id: string | null) => void
|
||||
filter: DashboardFilter
|
||||
setFilter: (f: DashboardFilter) => void
|
||||
}
|
||||
|
||||
// Why: the listener must be scoped to the dashboard container so keystrokes
|
||||
// (Arrow keys, digits 1-4, Enter, Escape) only fire when focus is inside the
|
||||
// dashboard. Attaching to window intercepts terminal/xterm navigation (arrow
|
||||
// keys for command history) and shell digit entry while the dashboard pane
|
||||
// is merely open, which breaks those unrelated inputs.
|
||||
//
|
||||
// Why return a callback ref (and not accept a RefObject): AgentDashboard has
|
||||
// an early-return branch that renders an empty state WITHOUT the container
|
||||
// div when there are no repos. On initial render with no repos, a plain
|
||||
// `useRef` would be null, our attach-effect would no-op, and then when repos
|
||||
// later appear and the container mounts, React would NOT re-run the effect
|
||||
// (a RefObject has stable identity, so its mutation doesn't trigger effects).
|
||||
// The result: the keyboard listener would silently never attach on that path.
|
||||
// A callback ref fires synchronously on attach/detach; storing the element in
|
||||
// useState makes the effect re-run whenever the container appears or goes
|
||||
// away, fixing the gap without any `ref.current`-as-dep anti-patterns.
|
||||
type ContainerCallbackRef = (el: HTMLDivElement | null) => void
|
||||
|
||||
const FILTER_KEYS: Record<string, DashboardFilter> = {
|
||||
'1': 'all',
|
||||
'2': 'active',
|
||||
'3': 'blocked',
|
||||
'4': 'done'
|
||||
}
|
||||
|
||||
export function useDashboardKeyboard({
|
||||
filteredWorktrees,
|
||||
focusedWorktreeId,
|
||||
setFocusedWorktreeId,
|
||||
filter,
|
||||
setFilter
|
||||
}: UseDashboardKeyboardParams): ContainerCallbackRef {
|
||||
const setActiveWorktree = useAppStore((s) => s.setActiveWorktree)
|
||||
const setActiveView = useAppStore((s) => s.setActiveView)
|
||||
// Why: no `rightSidebarOpen` guard needed. The keydown listener is attached
|
||||
// to the dashboard container element (see attach-effect below), which lives
|
||||
// inside the right sidebar. When the sidebar is closed it collapses to 0
|
||||
// width with overflow hidden, so focus cannot land inside the dashboard,
|
||||
// and keydown events from the focused element (typically the terminal) are
|
||||
// never dispatched to the dashboard container. Subscribing to the flag here
|
||||
// would only cause this hook to recompute and re-attach the listener on
|
||||
// every sidebar toggle without adding any safety.
|
||||
|
||||
// Why: track the container element in state so the attach-effect re-runs
|
||||
// whenever the element mounts or unmounts. See the file-level comment for
|
||||
// why a plain RefObject is insufficient here.
|
||||
const [containerEl, setContainerEl] = useState<HTMLDivElement | null>(null)
|
||||
|
||||
// Why: stash data the handler reads in refs so it doesn't re-bind on every
|
||||
// agent-status update (which produces a fresh filteredWorktrees array most
|
||||
// renders). Without this, the listener is add/removed at PTY event rate.
|
||||
const filteredWorktreesRef = useRef(filteredWorktrees)
|
||||
const focusedWorktreeIdRef = useRef(focusedWorktreeId)
|
||||
const filterRef = useRef(filter)
|
||||
const containerElRef = useRef<HTMLDivElement | null>(null)
|
||||
// Why: mirror the three render-driven inputs into refs in a single
|
||||
// commit-phase effect so the stable handleKeyDown callback always reads
|
||||
// the latest values without re-binding the listener at PTY event rate.
|
||||
useEffect(() => {
|
||||
filteredWorktreesRef.current = filteredWorktrees
|
||||
focusedWorktreeIdRef.current = focusedWorktreeId
|
||||
filterRef.current = filter
|
||||
})
|
||||
useEffect(() => {
|
||||
// Why: mirror the element into a ref so the (stable) handleKeyDown
|
||||
// callback can query inside the current container without needing to
|
||||
// re-bind when the element identity changes.
|
||||
containerElRef.current = containerEl
|
||||
}, [containerEl])
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent) => {
|
||||
// Don't intercept when focus is in an editable element
|
||||
const target = e.target as HTMLElement
|
||||
if (
|
||||
target.isContentEditable ||
|
||||
target.tagName === 'INPUT' ||
|
||||
target.tagName === 'TEXTAREA' ||
|
||||
target.tagName === 'SELECT'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
// Don't intercept when a modifier key is held (let app shortcuts through)
|
||||
if (e.metaKey || e.ctrlKey || e.altKey) {
|
||||
return
|
||||
}
|
||||
|
||||
// Filter quick-select: 1-4 keys.
|
||||
// Why: only fire when focus is on the dashboard container or a worktree
|
||||
// card, not on interactive descendants (dismiss X, expand chevron,
|
||||
// filter toggle, clear-search). Otherwise pressing a digit while such
|
||||
// a button is focused would silently change the filter — a foot-gun,
|
||||
// since buttons are common focus targets after clicks/keyboard nav.
|
||||
if (FILTER_KEYS[e.key]) {
|
||||
const onCardOrContainer =
|
||||
target === containerElRef.current || !!target.closest('[data-worktree-id]')
|
||||
if (!onCardOrContainer) {
|
||||
return
|
||||
}
|
||||
// Why: if the target itself is an interactive descendant of the worktree
|
||||
// card (dismiss X, expand chevron, filter toggle, clear-search button),
|
||||
// a digit keystroke would change the filter even though the user has a
|
||||
// nested button focused. Reject those so filter keys only fire from the
|
||||
// card surface itself or the dashboard container. (The container-is-target
|
||||
// fast path is already handled above.)
|
||||
if (target !== containerElRef.current) {
|
||||
const interactiveAncestor = target.closest(
|
||||
'button, a, input, textarea, select, [role="button"], [role="switch"], [role="tab"], [contenteditable="true"]'
|
||||
)
|
||||
if (interactiveAncestor && interactiveAncestor !== containerElRef.current) {
|
||||
return
|
||||
}
|
||||
}
|
||||
e.preventDefault()
|
||||
setFilter(FILTER_KEYS[e.key])
|
||||
return
|
||||
}
|
||||
|
||||
// Escape: reset filter to 'all' (the default)
|
||||
if (e.key === 'Escape') {
|
||||
if (filterRef.current !== 'all') {
|
||||
e.preventDefault()
|
||||
setFilter('all')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Arrow key navigation
|
||||
if (['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
|
||||
e.preventDefault()
|
||||
const worktrees = filteredWorktreesRef.current
|
||||
const ids = worktrees.map((wt) => wt.worktree.id)
|
||||
if (ids.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const focused = focusedWorktreeIdRef.current
|
||||
const currentIndex = focused ? ids.indexOf(focused) : -1
|
||||
|
||||
let nextIndex: number
|
||||
if (e.key === 'ArrowDown' || e.key === 'ArrowRight') {
|
||||
nextIndex = currentIndex < ids.length - 1 ? currentIndex + 1 : 0
|
||||
} else {
|
||||
nextIndex = currentIndex > 0 ? currentIndex - 1 : ids.length - 1
|
||||
}
|
||||
|
||||
const nextId = ids[nextIndex]
|
||||
setFocusedWorktreeId(nextId)
|
||||
|
||||
// Focus the corresponding DOM card. Why: scope the lookup to the
|
||||
// dashboard container so we don't accidentally match a card rendered
|
||||
// elsewhere in the app (and so the query fails closed when the
|
||||
// container is unmounted).
|
||||
// Why: worktreeId is `${repoId}::${path}` (see src/shared/types.ts)
|
||||
// and filesystem paths can contain characters like `"` or `\` that
|
||||
// would otherwise break the attribute-selector string and throw a
|
||||
// SyntaxError, silently killing arrow-key navigation. CSS.escape()
|
||||
// safely encodes those special characters.
|
||||
const cardEl = containerElRef.current?.querySelector(
|
||||
`[data-worktree-id="${CSS.escape(nextId)}"]`
|
||||
) as HTMLElement | null
|
||||
cardEl?.focus()
|
||||
return
|
||||
}
|
||||
|
||||
// Enter: navigate to focused worktree.
|
||||
// Why: only fire when the native keydown target is the card itself OR
|
||||
// is nested inside one — but never on interactive descendants like the
|
||||
// dismiss X, expand chevron, clear-search button, or filter toggle,
|
||||
// whose own handlers would be blocked by preventDefault. Today the card
|
||||
// has no focusable descendants (the action buttons stopPropagation and
|
||||
// are reached via mouse, not keyboard Tab from the card), so using
|
||||
// `closest('[data-worktree-id]')` is safe AND robust against future
|
||||
// changes that might add focusable descendants elsewhere in the card.
|
||||
if (e.key === 'Enter' && focusedWorktreeIdRef.current) {
|
||||
const enterTarget = e.target as HTMLElement | null
|
||||
if (!enterTarget || !enterTarget.closest('[data-worktree-id]')) {
|
||||
return
|
||||
}
|
||||
e.preventDefault()
|
||||
setActiveWorktree(focusedWorktreeIdRef.current)
|
||||
setActiveView('terminal')
|
||||
}
|
||||
},
|
||||
[setFocusedWorktreeId, setFilter, setActiveWorktree, setActiveView]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
// Why: attach to the dashboard container rather than window so these
|
||||
// shortcuts only fire when focus is inside the dashboard. This prevents
|
||||
// Arrow keys and digits 1-4 from hijacking the terminal (xterm history
|
||||
// navigation) and shell input while the dashboard pane is open.
|
||||
//
|
||||
// Why depend on `containerEl` (state) not a ref: the container is not
|
||||
// rendered on the empty-state branch, so it mounts *after* this hook
|
||||
// first runs once repos appear. State-backed tracking via the callback
|
||||
// ref guarantees this effect re-runs at that mount.
|
||||
if (!containerEl) {
|
||||
return
|
||||
}
|
||||
containerEl.addEventListener('keydown', handleKeyDown)
|
||||
return () => containerEl.removeEventListener('keydown', handleKeyDown)
|
||||
}, [handleKeyDown, containerEl])
|
||||
|
||||
// Why: return a stable callback ref so the caller can spread it onto the
|
||||
// container's `ref` prop. useState's setter identity is stable across
|
||||
// renders, so this doesn't churn React's ref-assignment cycle.
|
||||
return setContainerEl
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
// Why: relative timestamps drift once mounted. A 30s tick keeps the "Xm
|
||||
// ago" labels honest without burning a render every second.
|
||||
//
|
||||
// Hoisted to a shared hook so container components (AgentDashboard,
|
||||
// AgentStatusHover) can own a single tick and thread `now` down to every
|
||||
// DashboardAgentRow. Previously each row instantiated its own interval,
|
||||
// which meant N timers firing at staggered mount times for N rows on
|
||||
// screen — turning one logical tick into N independent React commits.
|
||||
export function useNow(intervalMs: number): number {
|
||||
const [now, setNow] = useState(() => Date.now())
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setNow(Date.now()), intervalMs)
|
||||
return () => clearInterval(id)
|
||||
}, [intervalMs])
|
||||
return now
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
|
||||
import { collectRetainedAgentsOnDisappear } from './useRetainedAgents'
|
||||
|
||||
function makeAgentRow(args: {
|
||||
paneKey: string
|
||||
state: 'working' | 'blocked' | 'waiting' | 'done'
|
||||
interrupted?: boolean
|
||||
}) {
|
||||
const entry: AgentStatusEntry = {
|
||||
state: args.state,
|
||||
prompt: 'Fix it',
|
||||
updatedAt: 100,
|
||||
stateStartedAt: 100,
|
||||
paneKey: args.paneKey,
|
||||
terminalTitle: 'Claude',
|
||||
stateHistory: [],
|
||||
agentType: 'claude',
|
||||
interrupted: args.interrupted
|
||||
}
|
||||
|
||||
return {
|
||||
paneKey: args.paneKey,
|
||||
entry,
|
||||
tab: {
|
||||
id: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
title: 'Terminal',
|
||||
ptyId: null,
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
},
|
||||
agentType: 'claude' as const,
|
||||
state: args.state,
|
||||
startedAt: 1
|
||||
}
|
||||
}
|
||||
|
||||
describe('collectRetainedAgentsOnDisappear', () => {
|
||||
it('retains a clean done row that disappeared naturally', () => {
|
||||
const previousAgents = new Map([
|
||||
['tab-1:1', { row: makeAgentRow({ paneKey: 'tab-1:1', state: 'done' }), worktreeId: 'wt-1' }]
|
||||
])
|
||||
|
||||
const result = collectRetainedAgentsOnDisappear({
|
||||
previousAgents,
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toHaveLength(1)
|
||||
expect(result.toRetain[0]?.entry.paneKey).toBe('tab-1:1')
|
||||
expect(result.consumedSuppressedPaneKeys).toEqual([])
|
||||
})
|
||||
|
||||
it('does not retain an interrupted done row', () => {
|
||||
const previousAgents = new Map([
|
||||
[
|
||||
'tab-1:1',
|
||||
{
|
||||
row: makeAgentRow({ paneKey: 'tab-1:1', state: 'done', interrupted: true }),
|
||||
worktreeId: 'wt-1'
|
||||
}
|
||||
]
|
||||
])
|
||||
|
||||
const result = collectRetainedAgentsOnDisappear({
|
||||
previousAgents,
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toEqual([])
|
||||
})
|
||||
|
||||
it('refreshes the retained snapshot when a reused paneKey starts a newer run', () => {
|
||||
// Why: a reused paneKey (same tab+pane, fresh agent start after a prior
|
||||
// retained run) produces a newer startedAt. Without the freshness check
|
||||
// the loop would early-continue because retainedAgentsByPaneKey[paneKey]
|
||||
// is still truthy from the prior run — leaving stale completion data
|
||||
// visible forever for the reused pane.
|
||||
const prevRow = makeAgentRow({ paneKey: 'tab-1:1', state: 'done' })
|
||||
prevRow.startedAt = 200
|
||||
const previousAgents = new Map([['tab-1:1', { row: prevRow, worktreeId: 'wt-1' }]])
|
||||
|
||||
const staleRetained = {
|
||||
entry: { ...prevRow.entry, updatedAt: 50, stateStartedAt: 50 },
|
||||
worktreeId: 'wt-1',
|
||||
tab: prevRow.tab,
|
||||
agentType: 'claude' as const,
|
||||
startedAt: 100
|
||||
}
|
||||
|
||||
const result = collectRetainedAgentsOnDisappear({
|
||||
previousAgents,
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: { 'tab-1:1': staleRetained },
|
||||
retentionSuppressedPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toHaveLength(1)
|
||||
expect(result.toRetain[0]?.startedAt).toBe(200)
|
||||
})
|
||||
|
||||
it('does not re-retain when the existing retained snapshot is for the same run', () => {
|
||||
const prevRow = makeAgentRow({ paneKey: 'tab-1:1', state: 'done' })
|
||||
prevRow.startedAt = 100
|
||||
const previousAgents = new Map([['tab-1:1', { row: prevRow, worktreeId: 'wt-1' }]])
|
||||
|
||||
const sameRunRetained = {
|
||||
entry: prevRow.entry,
|
||||
worktreeId: 'wt-1',
|
||||
tab: prevRow.tab,
|
||||
agentType: 'claude' as const,
|
||||
startedAt: 100
|
||||
}
|
||||
|
||||
const result = collectRetainedAgentsOnDisappear({
|
||||
previousAgents,
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: { 'tab-1:1': sameRunRetained },
|
||||
retentionSuppressedPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toEqual([])
|
||||
})
|
||||
|
||||
it('does not retain a clean done row when teardown suppressed that pane', () => {
|
||||
const previousAgents = new Map([
|
||||
['tab-1:1', { row: makeAgentRow({ paneKey: 'tab-1:1', state: 'done' }), worktreeId: 'wt-1' }]
|
||||
])
|
||||
|
||||
const result = collectRetainedAgentsOnDisappear({
|
||||
previousAgents,
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: { 'tab-1:1': true }
|
||||
})
|
||||
|
||||
expect(result.toRetain).toEqual([])
|
||||
expect(result.consumedSuppressedPaneKeys).toEqual(['tab-1:1'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,245 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import {
|
||||
computeDominantState,
|
||||
type DashboardRepoGroup,
|
||||
type DashboardAgentRow,
|
||||
type DashboardWorktreeCard
|
||||
} from './useDashboardData'
|
||||
import type { RetainedAgentEntry } from '@/store/slices/agent-status'
|
||||
import { AGENT_DASHBOARD_ENABLED } from '../../../../shared/constants'
|
||||
|
||||
// Why: when an agent finishes or its terminal closes, the store cleans up the
|
||||
// explicit status entry and the agent vanishes from useDashboardData. Retaining
|
||||
// the last-known "done" snapshot in the store (not in component state) lets the
|
||||
// dashboard AND the sidebar hovercard render the exact same set of rows — the
|
||||
// two surfaces must be consistent so the user sees the same completion in both
|
||||
// places, and dismissal in one reflects in the other.
|
||||
|
||||
export function useRetainedAgentsSync(liveGroups: DashboardRepoGroup[]): void {
|
||||
const retainAgents = useAppStore((s) => s.retainAgents)
|
||||
const pruneRetainedAgents = useAppStore((s) => s.pruneRetainedAgents)
|
||||
const clearRetentionSuppressedPaneKeys = useAppStore((s) => s.clearRetentionSuppressedPaneKeys)
|
||||
const prevAgentsRef = useRef<Map<string, { row: DashboardAgentRow; worktreeId: string }>>(
|
||||
new Map()
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
// Why: the feature-flag gate lives inside the effect (not around the hook
|
||||
// declarations above) so rules-of-hooks stays satisfied — the store
|
||||
// selectors and useRef must always run. When the dashboard is disabled,
|
||||
// skip all retention work to avoid touching the store for a feature the
|
||||
// user cannot see. Keeping this check here (rather than in App.tsx) makes
|
||||
// the hook self-contained and safe to call unconditionally from any site.
|
||||
if (!AGENT_DASHBOARD_ENABLED) {
|
||||
return
|
||||
}
|
||||
const current = new Map<string, { row: DashboardAgentRow; worktreeId: string }>()
|
||||
const existingWorktreeIds = new Set<string>()
|
||||
for (const group of liveGroups) {
|
||||
for (const wt of group.worktrees) {
|
||||
existingWorktreeIds.add(wt.worktree.id)
|
||||
for (const agent of wt.agents) {
|
||||
current.set(agent.paneKey, { row: agent, worktreeId: wt.worktree.id })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Why: read retention state via getState() instead of subscribing. This
|
||||
// effect's driving input is liveGroups — retention decisions only need to
|
||||
// happen when an agent appears/disappears from the live set. Subscribing
|
||||
// to retainedAgentsByPaneKey would create a feedback loop (this effect
|
||||
// calls retainAgents which updates that map, re-firing the effect).
|
||||
// retentionSuppressedPaneKeys is only acted on when the corresponding
|
||||
// pane disappears from liveGroups, so its changes are naturally picked
|
||||
// up on the next liveGroups-driven run via this fresh getState() read.
|
||||
const { retainedAgentsByPaneKey: retainedNow, retentionSuppressedPaneKeys } =
|
||||
useAppStore.getState()
|
||||
const { toRetain, consumedSuppressedPaneKeys } = collectRetainedAgentsOnDisappear({
|
||||
previousAgents: prevAgentsRef.current,
|
||||
currentAgents: current,
|
||||
retainedAgentsByPaneKey: retainedNow,
|
||||
retentionSuppressedPaneKeys
|
||||
})
|
||||
// Why: batch retention into a single store mutation. Looping retainAgent
|
||||
// would trigger N set(...) calls and N subscriber notifications when
|
||||
// several agents vanish in the same frame (e.g. tab close, worktree
|
||||
// teardown), exposing intermediate maps to consumers mid-loop. A single
|
||||
// atomic update keeps the dashboard + sidebar hovercard visually stable.
|
||||
retainAgents(toRetain)
|
||||
|
||||
prevAgentsRef.current = current
|
||||
pruneRetainedAgents(existingWorktreeIds)
|
||||
if (consumedSuppressedPaneKeys.length > 0) {
|
||||
clearRetentionSuppressedPaneKeys(consumedSuppressedPaneKeys)
|
||||
}
|
||||
}, [liveGroups, retainAgents, pruneRetainedAgents, clearRetentionSuppressedPaneKeys])
|
||||
}
|
||||
|
||||
export function useRetainedAgents(liveGroups: DashboardRepoGroup[]): {
|
||||
enrichedGroups: DashboardRepoGroup[]
|
||||
dismissAgent: (paneKey: string) => void
|
||||
} {
|
||||
// Why: the retention sync runs at App level (see useRetainedAgentsSync in
|
||||
// App.tsx) so retained entries persist across dashboard mounts. This hook
|
||||
// only reads + dismisses individual rows; bulk worktree-level dismissal
|
||||
// was removed because silently dropping retained done agents when the
|
||||
// user clicks a worktree can erase completion signals for other agents
|
||||
// (e.g. a done Codex row while a live Claude row triggered the click).
|
||||
const retained = useAppStore((s) => s.retainedAgentsByPaneKey)
|
||||
const dismissRetainedAgent = useAppStore((s) => s.dismissRetainedAgent)
|
||||
|
||||
const enrichedGroups = useMemo(
|
||||
() => enrichGroupsWithRetained(liveGroups, retained),
|
||||
[liveGroups, retained]
|
||||
)
|
||||
|
||||
const dismissAgent = useCallback(
|
||||
(paneKey: string) => {
|
||||
dismissRetainedAgent(paneKey)
|
||||
},
|
||||
[dismissRetainedAgent]
|
||||
)
|
||||
|
||||
return { enrichedGroups, dismissAgent }
|
||||
}
|
||||
|
||||
export function enrichGroupsWithRetained(
|
||||
liveGroups: DashboardRepoGroup[],
|
||||
retained: Record<string, RetainedAgentEntry>
|
||||
): DashboardRepoGroup[] {
|
||||
const retainedList = Object.values(retained)
|
||||
if (retainedList.length === 0) {
|
||||
return liveGroups
|
||||
}
|
||||
|
||||
const byWorktree = new Map<string, RetainedAgentEntry[]>()
|
||||
for (const ra of retainedList) {
|
||||
const list = byWorktree.get(ra.worktreeId) ?? []
|
||||
list.push(ra)
|
||||
byWorktree.set(ra.worktreeId, list)
|
||||
}
|
||||
|
||||
// Why: if the same paneKey is both live and retained during a render seam,
|
||||
// the live row wins so we never double-render an agent mid-transition.
|
||||
const livePaneKeys = new Set<string>()
|
||||
for (const group of liveGroups) {
|
||||
for (const wt of group.worktrees) {
|
||||
for (const agent of wt.agents) {
|
||||
livePaneKeys.add(agent.paneKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return liveGroups.map((group) => {
|
||||
// Why: preserve reference identity at the group level when no worktree
|
||||
// inside it has retained rows. Returning a fresh group/worktrees array
|
||||
// unconditionally invalidates downstream React.memo across the entire
|
||||
// tree whenever retainedAgentsByPaneKey changes — even for groups whose
|
||||
// worktrees are untouched.
|
||||
let anyChanged = false
|
||||
const worktrees: DashboardWorktreeCard[] = []
|
||||
for (const wt of group.worktrees) {
|
||||
const retainedForWt = byWorktree
|
||||
.get(wt.worktree.id)
|
||||
?.filter((ra) => !livePaneKeys.has(ra.entry.paneKey))
|
||||
if (!retainedForWt?.length) {
|
||||
worktrees.push(wt)
|
||||
continue
|
||||
}
|
||||
anyChanged = true
|
||||
|
||||
const retainedRows: DashboardAgentRow[] = retainedForWt.map(retainedToRow)
|
||||
|
||||
// Why: re-sort after merging retained rows ascending by startedAt so
|
||||
// the list order matches useDashboardData (oldest first, new rows
|
||||
// append at the bottom) and doesn't reshuffle rows the user is
|
||||
// currently reading.
|
||||
const mergedAgents = [...wt.agents, ...retainedRows].sort((a, b) => a.startedAt - b.startedAt)
|
||||
worktrees.push({
|
||||
...wt,
|
||||
agents: mergedAgents,
|
||||
// Why: share computeDominantState with useDashboardData so the
|
||||
// dashboard (live-only) and the retained-enriched view apply the
|
||||
// exact same blocked > working > done > idle priority. Keeping two
|
||||
// copies risks drift where a priority tweak in one surface silently
|
||||
// diverges the two — the two surfaces must stay in sync.
|
||||
dominantState: computeDominantState(mergedAgents),
|
||||
// Why: earliestStartedAt should anchor to the oldest start across live
|
||||
// and retained rows — retained entries can be *older* than current
|
||||
// live agents (they're what's lingering from a prior run), so the
|
||||
// min keeps the worktree's list position stable as retained rows
|
||||
// merge in.
|
||||
earliestStartedAt: Math.min(
|
||||
wt.earliestStartedAt > 0 ? wt.earliestStartedAt : Number.POSITIVE_INFINITY,
|
||||
...retainedForWt.map((ra) => ra.startedAt)
|
||||
)
|
||||
} satisfies DashboardWorktreeCard)
|
||||
}
|
||||
|
||||
if (!anyChanged) {
|
||||
return group
|
||||
}
|
||||
return { ...group, worktrees } satisfies DashboardRepoGroup
|
||||
})
|
||||
}
|
||||
|
||||
function retainedToRow(ra: RetainedAgentEntry): DashboardAgentRow {
|
||||
return {
|
||||
paneKey: ra.entry.paneKey,
|
||||
entry: ra.entry,
|
||||
tab: ra.tab,
|
||||
agentType: ra.agentType,
|
||||
state: 'done',
|
||||
startedAt: ra.startedAt
|
||||
}
|
||||
}
|
||||
|
||||
export function collectRetainedAgentsOnDisappear(args: {
|
||||
previousAgents: Map<string, { row: DashboardAgentRow; worktreeId: string }>
|
||||
currentAgents: Map<string, { row: DashboardAgentRow; worktreeId: string }>
|
||||
retainedAgentsByPaneKey: Record<string, RetainedAgentEntry>
|
||||
retentionSuppressedPaneKeys: Record<string, true>
|
||||
}): {
|
||||
toRetain: RetainedAgentEntry[]
|
||||
consumedSuppressedPaneKeys: string[]
|
||||
} {
|
||||
const toRetain: RetainedAgentEntry[] = []
|
||||
const consumedSuppressedPaneKeys: string[] = []
|
||||
|
||||
for (const [paneKey, prev] of args.previousAgents) {
|
||||
if (args.currentAgents.has(paneKey)) {
|
||||
continue
|
||||
}
|
||||
// Why: skip only when the retained snapshot is for the SAME (or newer) run.
|
||||
// A reused paneKey (same tab+pane, fresh agent start after a prior run was
|
||||
// retained) produces a newer startedAt — we must overwrite so stale
|
||||
// completion data doesn't linger forever for the reused pane.
|
||||
const alreadyRetained = args.retainedAgentsByPaneKey[paneKey]
|
||||
if (alreadyRetained && alreadyRetained.startedAt >= prev.row.startedAt) {
|
||||
continue
|
||||
}
|
||||
if (args.retentionSuppressedPaneKeys[paneKey]) {
|
||||
consumedSuppressedPaneKeys.push(paneKey)
|
||||
continue
|
||||
}
|
||||
// Why: only keep a sticky snapshot when the agent finished cleanly
|
||||
// (state === 'done' and not interrupted). Explicit teardown paths mark
|
||||
// pane keys as suppression candidates, so a close/quit/crash cannot
|
||||
// resurrect a stale `done` row on the next sync.
|
||||
const lastState = prev.row.state
|
||||
const wasInterrupted = prev.row.entry.interrupted === true
|
||||
if (lastState !== 'done' || wasInterrupted) {
|
||||
continue
|
||||
}
|
||||
toRetain.push({
|
||||
entry: prev.row.entry,
|
||||
worktreeId: prev.worktreeId,
|
||||
tab: prev.row.tab,
|
||||
agentType: prev.row.agentType,
|
||||
startedAt: prev.row.startedAt
|
||||
})
|
||||
}
|
||||
|
||||
return { toRetain, consumedSuppressedPaneKeys }
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
import React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
||||
import { ChevronDown, ChevronUp } from 'lucide-react'
|
||||
import AgentDashboard from '../dashboard/AgentDashboard'
|
||||
|
||||
const MIN_HEIGHT = 140
|
||||
const DEFAULT_HEIGHT = 220
|
||||
const HEADER_HEIGHT = 28
|
||||
// Why: leave room for the tab content above the dashboard — used in both the drag max and the layout-effect measure, must stay in sync.
|
||||
const RESERVED_ABOVE_PX = 160
|
||||
const STORAGE_KEY = 'orca.dashboardSidebarPanel'
|
||||
|
||||
type PersistedState = {
|
||||
height: number
|
||||
collapsed: boolean
|
||||
}
|
||||
|
||||
function loadPersistedState(): PersistedState {
|
||||
if (typeof window === 'undefined') {
|
||||
return { height: DEFAULT_HEIGHT, collapsed: false }
|
||||
}
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) {
|
||||
return { height: DEFAULT_HEIGHT, collapsed: false }
|
||||
}
|
||||
const parsed = JSON.parse(raw) as Partial<PersistedState>
|
||||
// Why: stale or tampered localStorage can hold NaN, negative, zero, or
|
||||
// absurdly large heights. The runtime clamp in onResizeMove only fires
|
||||
// during an active drag, so without validation here the initial render
|
||||
// can produce a zero-height strip or a panel that eats the whole sidebar
|
||||
// before the user ever touches the resize handle. We can't clamp the
|
||||
// upper bound yet (sidebarHeight isn't known until mount), but enforcing
|
||||
// finite + MIN_HEIGHT eliminates the worst-case visual breakage.
|
||||
const rawHeight =
|
||||
typeof parsed.height === 'number' && Number.isFinite(parsed.height)
|
||||
? parsed.height
|
||||
: DEFAULT_HEIGHT
|
||||
return {
|
||||
height: Math.max(MIN_HEIGHT, rawHeight),
|
||||
collapsed: typeof parsed.collapsed === 'boolean' ? parsed.collapsed : false
|
||||
}
|
||||
} catch {
|
||||
return { height: DEFAULT_HEIGHT, collapsed: false }
|
||||
}
|
||||
}
|
||||
|
||||
// Why: a persistent bottom section of the right sidebar that always shows the
|
||||
// agent dashboard, independent of which activity tab the user has open. The
|
||||
// user drags the top edge to resize upward and can fully collapse to a
|
||||
// single header row.
|
||||
export default function DashboardBottomPanel(): React.JSX.Element {
|
||||
// Why: read localStorage once per mount; multi-window state diverges intentionally.
|
||||
const initial = useMemo(loadPersistedState, [])
|
||||
const [height, setHeight] = useState<number>(initial.height)
|
||||
const [collapsed, setCollapsed] = useState<boolean>(initial.collapsed)
|
||||
// Why: tracks the sidebar-derived upper bound used to clamp rendering only.
|
||||
// We deliberately keep this separate from `height` so the user's persisted
|
||||
// preference is never overwritten by a transient small-window measurement
|
||||
// (see the useLayoutEffect below for the full rationale).
|
||||
const [measuredMaxHeight, setMeasuredMaxHeight] = useState<number | null>(null)
|
||||
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const resizeStateRef = useRef<{
|
||||
startY: number
|
||||
startHeight: number
|
||||
maxHeight: number
|
||||
} | null>(null)
|
||||
|
||||
// Why: mirror `height`/`collapsed` into refs so callbacks and the unmount
|
||||
// flush can read the latest value without being re-created on every change.
|
||||
// `onResizeStart` previously listed `height` in its deps, which meant every
|
||||
// mousemove (which calls setHeight) recreated the callback — pure waste on
|
||||
// the hot drag path. Refs keep the callback identity stable.
|
||||
const heightRef = useRef(height)
|
||||
const collapsedRef = useRef(collapsed)
|
||||
useEffect(() => {
|
||||
heightRef.current = height
|
||||
}, [height])
|
||||
useEffect(() => {
|
||||
collapsedRef.current = collapsed
|
||||
}, [collapsed])
|
||||
|
||||
// Why: persist height + collapsed via localStorage (renderer-only) so the
|
||||
// layout survives reloads. Debounce writes so continuous drag doesn't spam.
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
try {
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify({ height, collapsed }))
|
||||
} catch {
|
||||
// ignore quota / privacy-mode errors
|
||||
}
|
||||
}, 150)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [height, collapsed])
|
||||
|
||||
// Why: the debounced write above clears its pending timeout on every deps
|
||||
// change AND on unmount — so the user's final drag value is lost if the
|
||||
// component unmounts within the 150ms debounce window (hot reload, hiding
|
||||
// the dashboard, closing the window). This separate mount-lifecycle effect
|
||||
// has empty deps, so its cleanup runs ONLY on true unmount (never on deps
|
||||
// re-run), and it flushes the latest values synchronously to localStorage.
|
||||
// Reading via refs ensures we write the final state, not a stale snapshot.
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
STORAGE_KEY,
|
||||
JSON.stringify({ height: heightRef.current, collapsed: collapsedRef.current })
|
||||
)
|
||||
} catch {
|
||||
// ignore quota / privacy-mode errors
|
||||
}
|
||||
}
|
||||
// Why: empty deps are intentional — adding [height, collapsed] would turn
|
||||
// this unmount-only flush into a per-change write, defeating the debounce.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
const onResizeMove = useCallback((event: MouseEvent) => {
|
||||
const state = resizeStateRef.current
|
||||
if (!state) {
|
||||
return
|
||||
}
|
||||
const deltaY = state.startY - event.clientY
|
||||
const next = Math.max(MIN_HEIGHT, Math.min(state.maxHeight, state.startHeight + deltaY))
|
||||
setHeight(next)
|
||||
}, [])
|
||||
|
||||
// Why: keyboard support for the resize separator is required for a11y —
|
||||
// pointer-only resize locks out keyboard and assistive-tech users. Mirrors
|
||||
// the clamp logic in onResizeMove (MIN_HEIGHT lower, measuredMaxHeight
|
||||
// upper) so arrow/Home/End nudges obey the same bounds as mouse drags.
|
||||
// Step sizes (10px default, 40px with Shift) match common separator-widget
|
||||
// conventions for coarse vs. fine adjustment.
|
||||
const onResizeKeyDown = useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
const step = event.shiftKey ? 40 : 10
|
||||
const upperBound = measuredMaxHeight
|
||||
const clamp = (value: number): number => {
|
||||
const lowered = Math.max(MIN_HEIGHT, value)
|
||||
return upperBound !== null ? Math.min(upperBound, lowered) : lowered
|
||||
}
|
||||
switch (event.key) {
|
||||
case 'ArrowUp':
|
||||
event.preventDefault()
|
||||
setHeight((prev) => clamp(prev + step))
|
||||
break
|
||||
case 'ArrowDown':
|
||||
event.preventDefault()
|
||||
setHeight((prev) => clamp(prev - step))
|
||||
break
|
||||
case 'Home':
|
||||
event.preventDefault()
|
||||
setHeight(MIN_HEIGHT)
|
||||
break
|
||||
case 'End':
|
||||
if (upperBound !== null) {
|
||||
event.preventDefault()
|
||||
setHeight(upperBound)
|
||||
}
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
},
|
||||
[measuredMaxHeight]
|
||||
)
|
||||
|
||||
const onResizeEnd = useCallback(() => {
|
||||
resizeStateRef.current = null
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
window.removeEventListener('mousemove', onResizeMove)
|
||||
window.removeEventListener('mouseup', onResizeEnd)
|
||||
}, [onResizeMove])
|
||||
|
||||
const onResizeStart = useCallback(
|
||||
(event: React.MouseEvent<HTMLDivElement>) => {
|
||||
event.preventDefault()
|
||||
// Why: no `collapsed` guard here — the resize handle is only rendered
|
||||
// when `!collapsed` (see below), so this callback is unreachable while
|
||||
// collapsed. Keeping a `setCollapsed(false)` branch would be dead code
|
||||
// and would mislead future readers into thinking the handle can fire
|
||||
// in the collapsed state.
|
||||
// Why: cap expansion so the dashboard can't push the active panel
|
||||
// content to a zero-height strip. Leave 160px for the panel above.
|
||||
const sidebarEl = containerRef.current?.parentElement
|
||||
const sidebarHeight = sidebarEl?.getBoundingClientRect().height ?? 800
|
||||
const maxHeight = Math.max(MIN_HEIGHT, sidebarHeight - RESERVED_ABOVE_PX)
|
||||
resizeStateRef.current = {
|
||||
startY: event.clientY,
|
||||
// Why: use the CLAMPED height, not the raw persisted value. If the
|
||||
// stored height exceeds the current sidebar max (e.g. reopening in a
|
||||
// smaller window), the panel renders at `maxHeight` but drag math
|
||||
// would start from the raw value, so the handle appears unresponsive
|
||||
// until the cursor travels the difference. Clamping here keeps the
|
||||
// drag feel 1:1 with what's on screen.
|
||||
startHeight: Math.min(heightRef.current, maxHeight),
|
||||
maxHeight
|
||||
}
|
||||
document.body.style.cursor = 'row-resize'
|
||||
document.body.style.userSelect = 'none'
|
||||
window.addEventListener('mousemove', onResizeMove)
|
||||
window.addEventListener('mouseup', onResizeEnd)
|
||||
},
|
||||
// Why: `height` intentionally omitted — we read it via `heightRef` so the
|
||||
// callback identity stays stable during a drag. Including `height` would
|
||||
// recreate this callback on every mousemove (see heightRef declaration).
|
||||
[onResizeMove, onResizeEnd]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
window.removeEventListener('mousemove', onResizeMove)
|
||||
window.removeEventListener('mouseup', onResizeEnd)
|
||||
// Why: if the component unmounts mid-drag (e.g. user hides the
|
||||
// dashboard from settings while dragging, or a hot-reload swaps the
|
||||
// tree), onResizeEnd never fires. Without this restore, document.body
|
||||
// would stay stuck on `row-resize` with text selection disabled
|
||||
// app-wide until the next full reload.
|
||||
if (resizeStateRef.current !== null) {
|
||||
document.body.style.cursor = ''
|
||||
document.body.style.userSelect = ''
|
||||
}
|
||||
}
|
||||
}, [onResizeMove, onResizeEnd])
|
||||
|
||||
// Why: complements the lower-bound clamp in loadPersistedState. At load
|
||||
// time we can't compute the sidebar's max height because the parent isn't
|
||||
// measured yet, so a persisted `height` of e.g. 99999 (from a prior absurd
|
||||
// drag, a browser dimension change, or tampering) would render taller than
|
||||
// the entire sidebar, pushing the active panel (Explorer/Search/
|
||||
// SourceControl) to zero height and placing the resize handle off-screen
|
||||
// where the user can't easily recover.
|
||||
//
|
||||
// CRITICAL: we measure to clamp for RENDERING only, and NEVER overwrite
|
||||
// the persisted `height` preference. An earlier version called
|
||||
// `setHeight((prev) => Math.min(prev, max))` here, which caused a nasty
|
||||
// regression: a user who had dragged to 500px in a large window and later
|
||||
// opened the app in a smaller window would have their stored preference
|
||||
// silently shrunk (via the debounced localStorage-write effect) to whatever
|
||||
// `max` happened to be. Resizing the window back up would NOT restore the
|
||||
// original 500px — the preference was gone. By storing the measurement in
|
||||
// a separate `measuredMaxHeight` state and clamping only at render time,
|
||||
// the user's intent survives every window-size change.
|
||||
//
|
||||
// useLayoutEffect (not useEffect) runs before first paint to avoid a
|
||||
// visual flash of an oversized panel. The window-resize listener keeps
|
||||
// the clamp adaptive when the user shrinks the window after mount; it
|
||||
// MUST only update `measuredMaxHeight`, never `height`.
|
||||
useLayoutEffect(() => {
|
||||
const measure = (): void => {
|
||||
const sidebarEl = containerRef.current?.parentElement
|
||||
const sidebarHeight = sidebarEl?.getBoundingClientRect().height
|
||||
if (typeof sidebarHeight !== 'number' || !Number.isFinite(sidebarHeight)) {
|
||||
return
|
||||
}
|
||||
const max = Math.max(MIN_HEIGHT, sidebarHeight - RESERVED_ABOVE_PX)
|
||||
setMeasuredMaxHeight(max)
|
||||
}
|
||||
measure()
|
||||
window.addEventListener('resize', measure)
|
||||
return () => {
|
||||
window.removeEventListener('resize', measure)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const effectiveHeight = collapsed
|
||||
? HEADER_HEIGHT
|
||||
: measuredMaxHeight !== null
|
||||
? Math.min(height, measuredMaxHeight)
|
||||
: height
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="relative flex shrink-0 flex-col border-t border-border bg-sidebar"
|
||||
style={{ height: effectiveHeight }}
|
||||
>
|
||||
{/* Resize handle — hidden while collapsed so the user must expand first.
|
||||
Why: exposed as role="separator" with keyboard support (Arrow keys,
|
||||
Home/End) so keyboard and assistive-tech users can resize the panel.
|
||||
Without tabIndex + onKeyDown a mouse-only drag handle is an a11y gap:
|
||||
sighted keyboard users (and screen-reader users navigating widgets)
|
||||
would have no way to adjust the split. aria-value* advertises the
|
||||
current height and its bounds to assistive tech. */}
|
||||
{!collapsed && (
|
||||
<div
|
||||
role="separator"
|
||||
tabIndex={0}
|
||||
aria-orientation="horizontal"
|
||||
// Why: advertise the clamped rendered height, not the raw persisted value — otherwise valuenow can exceed valuemax when the persisted preference is larger than the current sidebar.
|
||||
aria-valuenow={Math.round(effectiveHeight)}
|
||||
aria-valuemin={MIN_HEIGHT}
|
||||
// Why: WAI-ARIA best practice is to always expose a finite range
|
||||
// alongside aria-valuenow so assistive tech can announce a
|
||||
// consistent bound. `measuredMaxHeight` is null until the
|
||||
// useLayoutEffect runs on mount, so fall back to the current
|
||||
// rendered `height` — it's guaranteed finite and correctly
|
||||
// represents the max the user can currently observe (valuenow ==
|
||||
// valuemax pre-measurement), avoiding an omitted upper bound.
|
||||
aria-valuemax={measuredMaxHeight ?? height}
|
||||
className="absolute left-0 right-0 z-10 -mt-[3px] h-[6px] cursor-row-resize transition-colors hover:bg-ring/20 active:bg-ring/30"
|
||||
onMouseDown={onResizeStart}
|
||||
onKeyDown={onResizeKeyDown}
|
||||
aria-label="Resize dashboard panel"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Header: title + collapse toggle (click anywhere to toggle).
|
||||
Why: the entire header is a single <button> rather than a <div>
|
||||
wrapping a nested <button>. Nesting interactive elements is invalid
|
||||
HTML and breaks screen readers — previously the inner button had no
|
||||
onClick of its own and relied on click bubbling to the div, so
|
||||
assistive tech announced a button that appeared to do nothing. */}
|
||||
<button
|
||||
type="button"
|
||||
className="flex w-full shrink-0 select-none items-center gap-1 px-2 text-left"
|
||||
style={{ height: HEADER_HEIGHT }}
|
||||
onClick={() => setCollapsed((prev) => !prev)}
|
||||
aria-expanded={!collapsed}
|
||||
aria-label={collapsed ? 'Expand dashboard' : 'Collapse dashboard'}
|
||||
>
|
||||
<span className="flex h-5 w-5 items-center justify-center text-muted-foreground">
|
||||
{collapsed ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
|
||||
</span>
|
||||
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
|
||||
Agents
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{/* Body: full AgentDashboard */}
|
||||
{!collapsed && (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
<AgentDashboard />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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' && <FileExplorer />}
|
||||
{effectiveTab === 'search' && <SearchPanel />}
|
||||
{effectiveTab === 'source-control' && <SourceControl />}
|
||||
{effectiveTab === 'checks' && <ChecksPanel />}
|
||||
{effectiveTab === 'ports' && <PortsPanel />}
|
||||
{/* 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. */}
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-hidden">
|
||||
{effectiveTab === 'explorer' && <FileExplorer />}
|
||||
{effectiveTab === 'search' && <SearchPanel />}
|
||||
{effectiveTab === 'source-control' && <SourceControl />}
|
||||
{effectiveTab === 'checks' && <ChecksPanel />}
|
||||
{effectiveTab === 'ports' && <PortsPanel />}
|
||||
</div>
|
||||
{AGENT_DASHBOARD_ENABLED && showAgentDashboard && <DashboardBottomPanel />}
|
||||
</div>
|
||||
)
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<div className="space-y-8">
|
||||
{/* Dashboard visibility */}
|
||||
{AGENT_DASHBOARD_ENABLED && (
|
||||
<section>
|
||||
<div className="flex items-center justify-between gap-4 px-1 py-2">
|
||||
<div className="space-y-0.5">
|
||||
<span id="show-agent-dashboard-label" className="text-sm font-medium">
|
||||
Show Agent Dashboard
|
||||
</span>
|
||||
<p id="show-agent-dashboard-desc" className="text-xs text-muted-foreground">
|
||||
Show the live agent activity panel docked at the bottom of the right sidebar —
|
||||
surfaces working, blocked, and done agents across all open worktrees.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={showDashboard}
|
||||
aria-labelledby="show-agent-dashboard-label"
|
||||
aria-describedby="show-agent-dashboard-desc"
|
||||
onClick={() => updateSettings({ showAgentDashboard: !showDashboard })}
|
||||
className={cn(
|
||||
'relative inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border border-transparent transition-colors',
|
||||
showDashboard ? 'bg-foreground' : 'bg-muted-foreground/30'
|
||||
)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'pointer-events-none block size-3.5 rounded-full bg-background shadow-sm transition-transform',
|
||||
showDashboard ? 'translate-x-4' : 'translate-x-0.5'
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Default agent picker */}
|
||||
<section className="space-y-4">
|
||||
<div className="space-y-1">
|
||||
|
||||
@@ -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<AgentDotState, number> = {
|
||||
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<HTMLButtonElement>) => {
|
||||
// Why: the activate button sits next to this one inside a shared row
|
||||
// container (not a nested button — nesting <button> inside <button> is
|
||||
// invalid HTML and causes inconsistent click dispatch across browsers).
|
||||
// Still stop propagation defensively in case the row gains a click
|
||||
// handler in a future change.
|
||||
e.stopPropagation()
|
||||
onDismiss(paneKey)
|
||||
},
|
||||
[onDismiss, paneKey]
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'group flex w-full items-center gap-2 rounded px-1 py-1',
|
||||
// Why: hover tints go in opposite directions per theme — dark mode
|
||||
// adds light (bg-accent/60 over the dark popover reads instantly);
|
||||
// light mode must darken the surface because accent (#f5f5f5) on
|
||||
// near-white renders effectively transparent. Use a black alpha
|
||||
// overlay in light and the original alpha-on-accent in dark.
|
||||
'hover:bg-black/[0.06] dark:hover:bg-accent/60'
|
||||
)}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleActivateClick}
|
||||
className={cn(
|
||||
'flex min-w-0 flex-1 items-center gap-2 text-left',
|
||||
'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring'
|
||||
)}
|
||||
aria-label={`Activate ${entry.prompt || agentStateLabel(dotState)}`}
|
||||
>
|
||||
<span className="flex size-4 shrink-0 items-center justify-center text-muted-foreground">
|
||||
<AgentIcon agent={iconAgent} size={14} />
|
||||
</span>
|
||||
<AgentStateDot state={dotState} size="sm" />
|
||||
<span
|
||||
className={cn(
|
||||
'min-w-0 flex-1 truncate text-xs',
|
||||
isRetained ? 'text-muted-foreground' : 'text-foreground'
|
||||
)}
|
||||
title={entry.prompt || agentStateLabel(dotState)}
|
||||
>
|
||||
{label}
|
||||
</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Dismiss agent"
|
||||
onClick={handleDismissClick}
|
||||
className={cn(
|
||||
'flex size-4 shrink-0 items-center justify-center rounded text-muted-foreground/60',
|
||||
'opacity-0 transition-opacity group-hover:opacity-100 hover:bg-accent hover:text-foreground',
|
||||
'focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring'
|
||||
)}
|
||||
>
|
||||
<X className="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
// 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<HoverAgentRow[]>(() => {
|
||||
if (entries.length === 0 && retained.length === 0) {
|
||||
return []
|
||||
}
|
||||
const agents = useMemo<DashboardAgentRowType[]>(() => {
|
||||
const rows: DashboardAgentRowType[] = []
|
||||
const seenPaneKeys = new Set<string>()
|
||||
// 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<string>()
|
||||
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<string, AgentStatusEntry[]>()
|
||||
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. */}
|
||||
<HoverCardContent
|
||||
side="right"
|
||||
align="start"
|
||||
className="w-72 border-neutral-200 bg-popover p-3 text-xs dark:border-white/10"
|
||||
className="flex w-72 max-h-[85vh] flex-col border-neutral-200 bg-popover p-3 text-xs dark:border-white/10"
|
||||
>
|
||||
{rows.length === 0 ? (
|
||||
<div className="py-1 text-center text-muted-foreground">No running agents</div>
|
||||
) : (
|
||||
<div className="flex flex-col">
|
||||
<div className="mb-1 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
|
||||
Running agents ({rows.length})
|
||||
</div>
|
||||
{/* 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. */}
|
||||
<div className="flex flex-col divide-y divide-neutral-200 dark:divide-white/10">
|
||||
{rows.map((row) => (
|
||||
<div key={row.paneKey} className="py-1">
|
||||
<InlineAgentRow
|
||||
row={row}
|
||||
onDismiss={handleDismissAgent}
|
||||
onActivate={handleActivateAgentTab}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<AgentStatusHoverContent
|
||||
agents={agents}
|
||||
onDismiss={handleDismissAgent}
|
||||
onActivate={handleActivateAgentTab}
|
||||
/>
|
||||
</HoverCardContent>
|
||||
</HoverCard>
|
||||
)
|
||||
})
|
||||
|
||||
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 <div className="py-1 text-center text-muted-foreground">No agent activity</div>
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
{/* 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. */}
|
||||
<div className="mb-1 shrink-0 text-[10px] font-medium uppercase tracking-wider text-muted-foreground/60">
|
||||
Agent activity ({agents.length})
|
||||
</div>
|
||||
{/* 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. */}
|
||||
<div className="flex min-h-0 flex-1 flex-col divide-y divide-neutral-200 overflow-y-auto dark:divide-white/10">
|
||||
{agents.map((agent) => (
|
||||
<div key={agent.paneKey} className="py-1">
|
||||
<DashboardAgentRow
|
||||
agent={agent}
|
||||
onDismiss={onDismiss}
|
||||
onActivate={onActivate}
|
||||
now={now}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
|
||||
export default AgentStatusHover
|
||||
|
||||
@@ -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<string>()
|
||||
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<string, AgentStatusEntry[]>()
|
||||
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')
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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<typeof setTimeout> | 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 }
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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<string, RetainedAgentEntry>
|
||||
|
||||
/** 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<string, true>
|
||||
|
||||
/** 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<string>) => 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<AppState, [], [], AgentStatusSlice> = (
|
||||
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<typeof setTimeout> | 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<AppState, [], [], AgentStatusS
|
||||
agentStatusEpoch: s.agentStatusEpoch + 1,
|
||||
sortEpoch: s.sortEpoch + 1
|
||||
}))
|
||||
scheduleNextFreshnessExpiry()
|
||||
}, delayMs)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
agentStatusByPaneKey: {},
|
||||
agentStatusEpoch: 0,
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: {},
|
||||
|
||||
setAgentStatus: (paneKey, payload, terminalTitle) => {
|
||||
set((s) => {
|
||||
@@ -195,9 +186,9 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
// stomped by a later ping that lost the identity (e.g. legacy/partial
|
||||
// integrations).
|
||||
agentType:
|
||||
payload.agentType && payload.agentType !== 'unknown'
|
||||
(payload.agentType && payload.agentType !== 'unknown'
|
||||
? payload.agentType
|
||||
: existing?.agentType,
|
||||
: existing?.agentType) ?? 'unknown',
|
||||
paneKey,
|
||||
terminalTitle: effectiveTitle,
|
||||
stateHistory: history,
|
||||
@@ -228,15 +219,29 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
const wasFresh =
|
||||
!!existing && isExplicitAgentStatusFresh(existing, now, AGENT_STATUS_STALE_AFTER_MS)
|
||||
const sortRelevantChange = !existing || existing.state !== payload.state || !wasFresh
|
||||
// Why: a new status event means the agent is live again — lift any
|
||||
// one-shot retention suppressor so the row can be retained normally
|
||||
// on its next disappearance. setAgentStatus fires on every PTY status
|
||||
// update (high frequency), so only clone retentionSuppressedPaneKeys
|
||||
// when there is actually a suppressor to remove — otherwise every
|
||||
// status ping would churn that map reference and force spurious
|
||||
// re-renders in any subscriber selecting on it.
|
||||
const hasSuppressor = paneKey in s.retentionSuppressedPaneKeys
|
||||
let nextRetentionSuppressedPaneKeys = s.retentionSuppressedPaneKeys
|
||||
if (hasSuppressor) {
|
||||
nextRetentionSuppressedPaneKeys = { ...s.retentionSuppressedPaneKeys }
|
||||
delete nextRetentionSuppressedPaneKeys[paneKey]
|
||||
}
|
||||
return {
|
||||
agentStatusByPaneKey: { ...s.agentStatusByPaneKey, [paneKey]: entry },
|
||||
retentionSuppressedPaneKeys: nextRetentionSuppressedPaneKeys,
|
||||
agentStatusEpoch: s.agentStatusEpoch + 1,
|
||||
sortEpoch: sortRelevantChange ? s.sortEpoch + 1 : s.sortEpoch
|
||||
}
|
||||
})
|
||||
// Why: schedule after set completes so the timer reads the updated map.
|
||||
// queueMicrotask avoids re-entry into the zustand store during set.
|
||||
queueMicrotask(() => scheduleNextFreshnessExpiry())
|
||||
queueMicrotask(() => freshness.schedule())
|
||||
},
|
||||
|
||||
removeAgentStatus: (paneKey) => {
|
||||
@@ -255,7 +260,7 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
sortEpoch: s.sortEpoch + 1
|
||||
}
|
||||
})
|
||||
queueMicrotask(() => scheduleNextFreshnessExpiry())
|
||||
queueMicrotask(() => freshness.schedule())
|
||||
},
|
||||
|
||||
removeAgentStatusByTabPrefix: (tabIdPrefix) => {
|
||||
@@ -280,29 +285,236 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
sortEpoch: s.sortEpoch + 1
|
||||
}
|
||||
})
|
||||
queueMicrotask(() => 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<AppState, [], [], AgentStatusS
|
||||
set((s) => {
|
||||
let changed = false
|
||||
const next: Record<string, RetainedAgentEntry> = {}
|
||||
// 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<string, RetainedAgentEntry> = {}
|
||||
@@ -334,6 +580,21 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
}
|
||||
return changed ? { retainedAgentsByPaneKey: next } : s
|
||||
})
|
||||
},
|
||||
|
||||
clearRetentionSuppressedPaneKeys: (paneKeys) => {
|
||||
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
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -526,17 +526,13 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
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
|
||||
|
||||
@@ -160,6 +160,7 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
|
||||
openLinksInApp: true,
|
||||
rightSidebarOpenByDefault: true,
|
||||
showTitlebarAgentActivity: true,
|
||||
showAgentDashboard: true,
|
||||
showTaskProviderIcons: true,
|
||||
notifications: getDefaultNotificationSettings(),
|
||||
diffDefaultView: 'inline',
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user