feat(sidebar): agent-status plumbing behind AGENT_DASHBOARD_ENABLED (dark launch) (#1070)
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
import React from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
// Why: shared state-dot primitive so the dashboard and the sidebar's agent
|
||||
// hover render the same state vocabulary identically. The dot sits next to the
|
||||
// agent icon (Claude/Codex/etc.) — they are two distinct glyphs: one for *who*
|
||||
// (icon) and one for *what state* (dot). Keeping them separate keeps each
|
||||
// glyph scannable at a glance instead of fused into a single decorated icon.
|
||||
|
||||
export type AgentDotState =
|
||||
| 'working'
|
||||
| 'blocked'
|
||||
| 'waiting'
|
||||
| 'done'
|
||||
| 'idle'
|
||||
// Why: the sidebar's title-based status flow (StatusIndicator/WorktreeCard)
|
||||
// collapses blocked + waiting into a single "needs attention" state. Keep
|
||||
// this as a distinct member so that flow can render without inventing a new
|
||||
// vocabulary, but treat it identically to `blocked` visually.
|
||||
| 'permission'
|
||||
|
||||
export function agentStateLabel(state: AgentDotState): string {
|
||||
switch (state) {
|
||||
case 'working':
|
||||
return 'Working'
|
||||
case 'blocked':
|
||||
return 'Blocked'
|
||||
case 'waiting':
|
||||
return 'Waiting for input'
|
||||
case 'done':
|
||||
return 'Done'
|
||||
case 'idle':
|
||||
return 'Idle'
|
||||
case 'permission':
|
||||
return 'Needs attention'
|
||||
}
|
||||
}
|
||||
|
||||
type Props = {
|
||||
state: AgentDotState
|
||||
size?: 'sm' | 'md'
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const AgentStateDot = React.memo(function AgentStateDot({
|
||||
state,
|
||||
size = 'sm',
|
||||
className
|
||||
}: Props): React.JSX.Element {
|
||||
const box = size === 'md' ? 'h-3 w-3' : 'h-2.5 w-2.5'
|
||||
const inner = size === 'md' ? 'size-2' : 'size-1.5'
|
||||
|
||||
if (state === 'working') {
|
||||
return (
|
||||
<span
|
||||
className={cn('inline-flex shrink-0 items-center justify-center', box, className)}
|
||||
aria-label={agentStateLabel(state)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'block rounded-full border-2 border-emerald-500 border-t-transparent animate-spin',
|
||||
inner
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
className={cn('inline-flex shrink-0 items-center justify-center', box, className)}
|
||||
aria-label={agentStateLabel(state)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
'block rounded-full',
|
||||
inner,
|
||||
state === 'blocked' || state === 'waiting' || state === 'permission'
|
||||
? 'bg-red-500 animate-pulse'
|
||||
: state === 'done'
|
||||
? 'bg-sky-500/80'
|
||||
: 'bg-neutral-500/40'
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,380 @@
|
||||
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 {
|
||||
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>
|
||||
)
|
||||
})
|
||||
|
||||
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 entries = useAppStore(
|
||||
useShallow((s) => {
|
||||
const wtTabs = s.tabsByWorktree[worktreeId] ?? EMPTY_TABS
|
||||
if (wtTabs.length === 0) {
|
||||
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(':')
|
||||
if (sepIdx <= 0) {
|
||||
continue
|
||||
}
|
||||
const tabId = paneKey.slice(0, sepIdx)
|
||||
if (!tabIds.has(tabId)) {
|
||||
continue
|
||||
}
|
||||
out.push(entry)
|
||||
}
|
||||
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 })
|
||||
}
|
||||
}
|
||||
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.
|
||||
const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch)
|
||||
const removeAgentStatus = useAppStore((s) => s.removeAgentStatus)
|
||||
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 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).
|
||||
for (const entry of entries) {
|
||||
const paneKey = entry.paneKey
|
||||
const sepIdx = paneKey.indexOf(':')
|
||||
if (sepIdx <= 0) {
|
||||
continue
|
||||
}
|
||||
const tabId = paneKey.slice(0, sepIdx)
|
||||
collected.push({
|
||||
paneKey,
|
||||
tabId,
|
||||
entry,
|
||||
dotState: liveEntryToDotState(entry, now),
|
||||
isRetained: false
|
||||
})
|
||||
seen.add(paneKey)
|
||||
}
|
||||
|
||||
for (const { paneKey, snapshot } of retained) {
|
||||
if (seen.has(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
|
||||
})
|
||||
}
|
||||
|
||||
// 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.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [entries, retained, 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.
|
||||
const handleDismissAgent = useCallback(
|
||||
(paneKey: string) => {
|
||||
removeAgentStatus(paneKey)
|
||||
dismissRetainedAgent(paneKey)
|
||||
},
|
||||
[removeAgentStatus, dismissRetainedAgent]
|
||||
)
|
||||
|
||||
// Why: clicking a row activates the specific tab the agent runs in. Retained
|
||||
// rows can outlive their tab, so fall back to worktree-only activation when
|
||||
// the tab is no longer present.
|
||||
const handleActivateAgentTab = useCallback(
|
||||
(tabId: string) => {
|
||||
setActiveWorktree(worktreeId)
|
||||
setActiveView('terminal')
|
||||
const tabs = useAppStore.getState().tabsByWorktree[worktreeId] ?? []
|
||||
if (tabs.some((t) => t.id === tabId)) {
|
||||
setActiveTab(tabId)
|
||||
}
|
||||
},
|
||||
[worktreeId, setActiveWorktree, setActiveTab, setActiveView]
|
||||
)
|
||||
|
||||
return (
|
||||
<HoverCard openDelay={300}>
|
||||
<HoverCardTrigger asChild>{children}</HoverCardTrigger>
|
||||
{/* Why: the shared HoverCard uses `border-border/50`, but `--border`
|
||||
already carries very different alpha per theme (#e5e5e5 opaque in
|
||||
light, rgb(255 255 255 / 0.07) in dark). At /50 the dark-mode edge
|
||||
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. */}
|
||||
<HoverCardContent
|
||||
side="right"
|
||||
align="start"
|
||||
className="w-72 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>
|
||||
)}
|
||||
</HoverCardContent>
|
||||
</HoverCard>
|
||||
)
|
||||
})
|
||||
|
||||
export default AgentStatusHover
|
||||
@@ -2,20 +2,26 @@ import React from 'react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { WorktreeStatus } from '@/lib/worktree-status'
|
||||
|
||||
// Why: re-export WorktreeStatus under the existing `Status` alias so the
|
||||
// sidebar component and the canonical lib share one source of truth — the
|
||||
// previous local union could silently drift if one side added a new state
|
||||
// (e.g., 'error') and the other didn't.
|
||||
export type Status = WorktreeStatus
|
||||
|
||||
type StatusIndicatorProps = React.ComponentProps<'span'> & {
|
||||
status: WorktreeStatus
|
||||
status: Status
|
||||
}
|
||||
|
||||
const StatusIndicator = React.memo(function StatusIndicator({
|
||||
status,
|
||||
className,
|
||||
...props
|
||||
...rest
|
||||
}: StatusIndicatorProps) {
|
||||
if (status === 'working') {
|
||||
return (
|
||||
<span
|
||||
className={cn('inline-flex h-3 w-3 shrink-0 items-center justify-center', className)}
|
||||
{...props}
|
||||
{...rest}
|
||||
>
|
||||
<span className="block size-2 rounded-full border-2 border-emerald-500 border-t-transparent animate-spin" />
|
||||
</span>
|
||||
@@ -25,7 +31,7 @@ const StatusIndicator = React.memo(function StatusIndicator({
|
||||
return (
|
||||
<span
|
||||
className={cn('inline-flex h-3 w-3 shrink-0 items-center justify-center', className)}
|
||||
{...props}
|
||||
{...rest}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
@@ -34,7 +40,11 @@ const StatusIndicator = React.memo(function StatusIndicator({
|
||||
? 'bg-emerald-500'
|
||||
: status === 'permission'
|
||||
? 'bg-red-500'
|
||||
: 'bg-neutral-500/40'
|
||||
: status === 'done'
|
||||
? // Why: sky-500/80 matches the dashboard AgentStateDot's
|
||||
// `done` color so the two surfaces read as the same state.
|
||||
'bg-sky-500/80'
|
||||
: 'bg-neutral-500/40'
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
@@ -42,4 +52,3 @@ const StatusIndicator = React.memo(function StatusIndicator({
|
||||
})
|
||||
|
||||
export default StatusIndicator
|
||||
export type { WorktreeStatus as Status }
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable max-lines -- Why: the worktree card centralizes sidebar card state (selection, drag, agent status, git info, context menu) in one cohesive component so sidebar rendering doesn't fan out across files. */
|
||||
import React, { useEffect, useMemo, useCallback, useState } from 'react'
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
import { useAppStore } from '@/store'
|
||||
@@ -8,9 +9,16 @@ import StatusIndicator from './StatusIndicator'
|
||||
import CacheTimer from './CacheTimer'
|
||||
import WorktreeContextMenu from './WorktreeContextMenu'
|
||||
import { SshDisconnectedDialog } from './SshDisconnectedDialog'
|
||||
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 { AGENT_DASHBOARD_ENABLED } from '../../../../shared/constants'
|
||||
import { getRepoKindLabel, isFolderRepo } from '../../../../shared/repo-kind'
|
||||
import type { Worktree, Repo, PRInfo, IssueInfo } from '../../../../shared/types'
|
||||
import {
|
||||
@@ -19,6 +27,7 @@ import {
|
||||
CONFLICT_OPERATION_LABELS,
|
||||
EMPTY_TABS,
|
||||
EMPTY_BROWSER_TABS,
|
||||
EMPTY_AGENT_ENTRIES,
|
||||
FilledBellIcon
|
||||
} from './WorktreeCardHelpers'
|
||||
import { IssueSection, PrSection, CommentSection } from './WorktreeCardMeta'
|
||||
@@ -103,6 +112,56 @@ 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
|
||||
@@ -140,11 +199,111 @@ const WorktreeCard = React.memo(function WorktreeCard({
|
||||
|
||||
const isDeleting = deleteState?.isDeleting ?? false
|
||||
|
||||
// Derive status
|
||||
const status: WorktreeStatus = useMemo(
|
||||
() => getWorktreeStatus(tabs, browserTabs, runtimePaneTitlesForWorktree),
|
||||
[tabs, browserTabs, runtimePaneTitlesForWorktree]
|
||||
)
|
||||
// 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
|
||||
}
|
||||
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
|
||||
break
|
||||
}
|
||||
if (heuristic === 'working') {
|
||||
hasWorking = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
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])
|
||||
|
||||
const showPR = cardProps.includes('pr')
|
||||
const showCI = cardProps.includes('ci')
|
||||
@@ -272,7 +431,24 @@ const WorktreeCard = React.memo(function WorktreeCard({
|
||||
{/* Status indicator on the left */}
|
||||
{(cardProps.includes('status') || cardProps.includes('unread')) && (
|
||||
<div className="flex flex-col items-center justify-start pt-[2px] gap-2 shrink-0">
|
||||
{cardProps.includes('status') && <StatusIndicator status={status} />}
|
||||
{cardProps.includes('status') &&
|
||||
(AGENT_DASHBOARD_ENABLED ? (
|
||||
<AgentStatusHover worktreeId={worktree.id}>
|
||||
{/* Why: make the hover trigger keyboard-focusable so
|
||||
keyboard-only users can open the hover panel (Radix
|
||||
HoverCardTrigger asChild does not promote a
|
||||
non-interactive child to focusable). */}
|
||||
<span
|
||||
tabIndex={0}
|
||||
role="button"
|
||||
aria-label={`Worktree status: ${status}. Show running agents.`}
|
||||
>
|
||||
<StatusIndicator status={status} />
|
||||
</span>
|
||||
</AgentStatusHover>
|
||||
) : (
|
||||
<StatusIndicator status={status} />
|
||||
))}
|
||||
|
||||
{cardProps.includes('unread') && (
|
||||
<Tooltip>
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
GitConflictOperation,
|
||||
TerminalTab
|
||||
} from '../../../../shared/types'
|
||||
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
|
||||
|
||||
// ── Pure helper functions ────────────────────────────────────────────
|
||||
|
||||
@@ -39,6 +40,7 @@ export const CONFLICT_OPERATION_LABELS: Record<Exclude<GitConflictOperation, 'un
|
||||
|
||||
export const EMPTY_TABS: TerminalTab[] = []
|
||||
export const EMPTY_BROWSER_TABS: { id: string }[] = []
|
||||
export const EMPTY_AGENT_ENTRIES: AgentStatusEntry[] = []
|
||||
|
||||
// ── SVG icon components ──────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -15,7 +15,12 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { Worktree, Repo } from '../../../../shared/types'
|
||||
import { isGitRepoKind } from '../../../../shared/repo-kind'
|
||||
import { buildWorktreeComparator } from './smart-sort'
|
||||
import { AGENT_DASHBOARD_ENABLED } from '../../../../shared/constants'
|
||||
import {
|
||||
buildExplicitEntriesByTabId,
|
||||
buildWorktreeComparator,
|
||||
computeSmartScore
|
||||
} from './smart-sort'
|
||||
import {
|
||||
type GroupHeaderRow,
|
||||
type Row,
|
||||
@@ -521,8 +526,51 @@ const WorktreeList = React.memo(function WorktreeList() {
|
||||
}
|
||||
|
||||
const currentTabs = state.tabsByWorktree
|
||||
const now = Date.now()
|
||||
// Why precompute: this is the hot sidebar sort. Array.sort invokes the
|
||||
// comparator O(N log N) times, and the smart-score computation would
|
||||
// otherwise scan `agentStatusByPaneKey` (O(E)) or do per-worktree O(T)
|
||||
// index lookups on every call. Two layered optimizations:
|
||||
// 1. Build the tabId → explicit-entries index ONCE (O(E)) so the
|
||||
// per-worktree scoring does cheap lookups instead of rescanning.
|
||||
// 2. Precompute scores once per worktree (decorate-sort-undecorate) so
|
||||
// the comparator does O(1) map lookups instead of re-scoring per
|
||||
// comparison.
|
||||
// Combined: O(E) index + O(N×T) scoring + O(N log N) sort, instead of
|
||||
// O(N × E × T) per sortEpoch bump. Only smart mode uses the score map;
|
||||
// other modes ignore it.
|
||||
const agentStatusForSort = AGENT_DASHBOARD_ENABLED ? state.agentStatusByPaneKey : undefined
|
||||
const explicitByTabId =
|
||||
sortBy === 'smart' ? buildExplicitEntriesByTabId(agentStatusForSort) : undefined
|
||||
const precomputedScores =
|
||||
sortBy === 'smart'
|
||||
? new Map<string, number>(
|
||||
nonArchivedWorktrees.map((w) => [
|
||||
w.id,
|
||||
computeSmartScore(
|
||||
w,
|
||||
currentTabs,
|
||||
repoMap,
|
||||
state.prCache,
|
||||
now,
|
||||
agentStatusForSort,
|
||||
explicitByTabId
|
||||
)
|
||||
])
|
||||
)
|
||||
: undefined
|
||||
nonArchivedWorktrees.sort(
|
||||
buildWorktreeComparator(sortBy, currentTabs, repoMap, state.prCache, Date.now())
|
||||
buildWorktreeComparator(
|
||||
sortBy,
|
||||
currentTabs,
|
||||
repoMap,
|
||||
state.prCache,
|
||||
now,
|
||||
null,
|
||||
agentStatusForSort,
|
||||
precomputedScores,
|
||||
explicitByTabId
|
||||
)
|
||||
)
|
||||
return nonArchivedWorktrees.map((w) => w.id)
|
||||
// debouncedSortEpoch is an intentional trigger: it's not read inside the
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Repo, TerminalTab, Worktree } from '../../../../shared/types'
|
||||
import { buildWorktreeComparator, computeSmartScore, type SmartSortOverride } from './smart-sort'
|
||||
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
|
||||
|
||||
const NOW = new Date('2026-03-27T12:00:00.000Z').getTime()
|
||||
|
||||
@@ -53,6 +54,21 @@ function makeTab(overrides: Partial<TerminalTab> = {}): TerminalTab {
|
||||
}
|
||||
}
|
||||
|
||||
function makeAgentStatusEntry(
|
||||
overrides: Partial<AgentStatusEntry> & { paneKey: string }
|
||||
): AgentStatusEntry {
|
||||
return {
|
||||
state: overrides.state ?? 'working',
|
||||
prompt: overrides.prompt ?? '',
|
||||
updatedAt: overrides.updatedAt ?? NOW - 30_000,
|
||||
stateStartedAt: overrides.stateStartedAt ?? overrides.updatedAt ?? NOW - 30_000,
|
||||
agentType: overrides.agentType ?? 'codex',
|
||||
paneKey: overrides.paneKey,
|
||||
terminalTitle: overrides.terminalTitle,
|
||||
stateHistory: overrides.stateHistory ?? []
|
||||
}
|
||||
}
|
||||
|
||||
describe('computeSmartScore', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
@@ -158,6 +174,39 @@ describe('computeSmartScore', () => {
|
||||
computeSmartScore(plain, null, repoMap, {})
|
||||
)
|
||||
})
|
||||
|
||||
it('does not let stale explicit status mask a live heuristic permission prompt', () => {
|
||||
const worktree = makeWorktree({ id: 'wt-1' })
|
||||
const tabsByWorktree = {
|
||||
[worktree.id]: [makeTab({ worktreeId: worktree.id, title: 'codex permission needed' })]
|
||||
}
|
||||
const score = computeSmartScore(worktree, tabsByWorktree, repoMap, null, NOW, {
|
||||
'tab-1:1': makeAgentStatusEntry({
|
||||
paneKey: 'tab-1:1',
|
||||
state: 'done',
|
||||
updatedAt: NOW - 45 * 60_000
|
||||
})
|
||||
})
|
||||
|
||||
expect(score).toBeGreaterThanOrEqual(35)
|
||||
})
|
||||
|
||||
it('does not stack heuristic working on top of fresh explicit done for the same tab', () => {
|
||||
const worktree = makeWorktree({ id: 'wt-1' })
|
||||
const tabsByWorktree = {
|
||||
[worktree.id]: [makeTab({ worktreeId: worktree.id, title: 'codex working' })]
|
||||
}
|
||||
|
||||
expect(
|
||||
computeSmartScore(worktree, tabsByWorktree, repoMap, null, NOW, {
|
||||
'tab-1:1': makeAgentStatusEntry({
|
||||
paneKey: 'tab-1:1',
|
||||
state: 'done',
|
||||
updatedAt: NOW - 60_000
|
||||
})
|
||||
})
|
||||
).toBe(12)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildWorktreeComparator', () => {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { detectAgentStatusFromTitle } from '@/lib/agent-status'
|
||||
import { detectAgentStatusFromTitle, isExplicitAgentStatusFresh } from '@/lib/agent-status'
|
||||
import { branchName } from '@/lib/git-utils'
|
||||
import type { Worktree, Repo, TerminalTab } from '../../../../shared/types'
|
||||
import {
|
||||
AGENT_STATUS_STALE_AFTER_MS,
|
||||
type AgentStatusEntry
|
||||
} from '../../../../shared/agent-status-types'
|
||||
|
||||
type SortBy = 'name' | 'smart' | 'recent' | 'repo'
|
||||
|
||||
@@ -11,6 +15,38 @@ export type SmartSortOverride = {
|
||||
hasRecentPRSignal: boolean
|
||||
}
|
||||
|
||||
// Why: building this index once at the sort call site reduces the smart-
|
||||
// score computation from O(N × E × T) to O(E) build + O(T) lookups per
|
||||
// worktree. Before, each worktree's score computation scanned the full
|
||||
// agentStatusByPaneKey map, which made the decorate-sort-undecorate
|
||||
// precompute pay the scan N times even though the map is global. Entries are
|
||||
// keyed by the `tabId` prefix of their paneKey (paneKey format: `${tabId}:…`).
|
||||
export function buildExplicitEntriesByTabId(
|
||||
agentStatusByPaneKey: Record<string, AgentStatusEntry> | undefined
|
||||
): Map<string, AgentStatusEntry[]> {
|
||||
const byTab = new Map<string, AgentStatusEntry[]>()
|
||||
if (!agentStatusByPaneKey) {
|
||||
return byTab
|
||||
}
|
||||
for (const entry of Object.values(agentStatusByPaneKey)) {
|
||||
const colon = entry.paneKey.indexOf(':')
|
||||
// Why: paneKey must be `${tabId}:${paneId}`. Skip malformed entries (no
|
||||
// colon or leading colon) rather than bucketing them under an empty tabId,
|
||||
// where they would never match a real tab and just waste memory.
|
||||
if (colon <= 0) {
|
||||
continue
|
||||
}
|
||||
const tabId = entry.paneKey.slice(0, colon)
|
||||
const bucket = byTab.get(tabId)
|
||||
if (bucket) {
|
||||
bucket.push(entry)
|
||||
} else {
|
||||
byTab.set(tabId, [entry])
|
||||
}
|
||||
}
|
||||
return byTab
|
||||
}
|
||||
|
||||
export function hasRecentPRSignal(
|
||||
worktree: Worktree,
|
||||
repoMap: Map<string, Repo>,
|
||||
@@ -35,18 +71,65 @@ function computeSmartScoreFromSignals(
|
||||
worktree: Worktree,
|
||||
tabs: TerminalTab[],
|
||||
hasRecentPR: boolean,
|
||||
now: number
|
||||
now: number,
|
||||
agentStatusByPaneKey?: Record<string, AgentStatusEntry>,
|
||||
explicitByTabId?: Map<string, AgentStatusEntry[]>
|
||||
): number {
|
||||
const liveTabs = tabs.filter((t) => t.ptyId)
|
||||
|
||||
let score = 0
|
||||
|
||||
const isRunning = liveTabs.some((t) => detectAgentStatusFromTitle(t.title) === 'working')
|
||||
// Why: explicit agent status (OSC 9999) is authoritative over heuristic title
|
||||
// parsing. Check explicit status first; fall through to heuristics for tabs
|
||||
// that have no explicit status entry.
|
||||
//
|
||||
// Why the index parameter: when the caller precomputes the tabId → entries
|
||||
// index once (via buildExplicitEntriesByTabId) and threads it through, each
|
||||
// worktree does O(T) lookups instead of scanning the full map O(E) times.
|
||||
// This matters because `sortWorktreesSmart` calls this function N times in a
|
||||
// decorate-sort-undecorate pass; without the shared index we'd pay O(N×E×T)
|
||||
// overall. When the index is absent and `agentStatusByPaneKey` is provided
|
||||
// we build it inline to preserve backward compatibility for callers (tests,
|
||||
// palette) that haven't adopted the optimization.
|
||||
const resolvedExplicitByTabId =
|
||||
explicitByTabId ?? buildExplicitEntriesByTabId(agentStatusByPaneKey)
|
||||
|
||||
let hasExplicitWorking = false
|
||||
let hasExplicitBlocked = false
|
||||
let hasHeuristicWorking = false
|
||||
let hasHeuristicBlocked = false
|
||||
|
||||
for (const tab of liveTabs) {
|
||||
const tabExplicitEntries = resolvedExplicitByTabId.get(tab.id) ?? []
|
||||
// Why: compute freshness once per entry instead of recomputing inside each
|
||||
// of the three `.some(...)` passes below. Freshness is a pure function of
|
||||
// (entry, now) so filtering up front is equivalent and cheaper.
|
||||
const freshEntries = tabExplicitEntries.filter((entry) =>
|
||||
isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)
|
||||
)
|
||||
|
||||
if (freshEntries.length > 0) {
|
||||
hasExplicitWorking ||= freshEntries.some((entry) => entry.state === 'working')
|
||||
hasExplicitBlocked ||= freshEntries.some(
|
||||
(entry) => entry.state === 'blocked' || entry.state === 'waiting'
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
const heuristicState = detectAgentStatusFromTitle(tab.title)
|
||||
hasHeuristicWorking ||= heuristicState === 'working'
|
||||
hasHeuristicBlocked ||= heuristicState === 'permission'
|
||||
}
|
||||
|
||||
// Explicit working → +60, same weight as heuristic working
|
||||
// Explicit blocked/waiting → +35, same weight as heuristic permission
|
||||
// Explicit done → no bonus (task complete, no attention needed)
|
||||
const isRunning = hasExplicitWorking || hasHeuristicWorking
|
||||
if (isRunning) {
|
||||
score += 60
|
||||
}
|
||||
|
||||
const needsAttention = liveTabs.some((t) => detectAgentStatusFromTitle(t.title) === 'permission')
|
||||
const needsAttention = hasExplicitBlocked || hasHeuristicBlocked
|
||||
if (needsAttention) {
|
||||
score += 35
|
||||
}
|
||||
@@ -99,6 +182,21 @@ function getSmartSortCandidate(
|
||||
|
||||
/**
|
||||
* Build a comparator for sorting worktrees based on the current sort mode.
|
||||
*
|
||||
* `precomputedScores` is the decorate-sort-undecorate optimization for the
|
||||
* `smart` mode: callers should compute each worktree's smart score once and
|
||||
* pass the map in, since `Array.prototype.sort` invokes the comparator
|
||||
* O(N log N) times and recomputing the score each call scans the
|
||||
* `agentStatusByPaneKey` map O(N log N × E) times. When omitted, the
|
||||
* comparator falls back to computing scores per-comparison so existing call
|
||||
* sites that haven't adopted the optimization keep working.
|
||||
*
|
||||
* `explicitByTabId` is a secondary optimization: when `precomputedScores` is
|
||||
* absent (fallback path), the comparator still has to call
|
||||
* `computeSmartScoreFromSignals` per comparison. Passing the prebuilt tabId
|
||||
* index avoids rescanning the full `agentStatusByPaneKey` map on every call.
|
||||
* When this index is also absent, the inner function builds one inline per
|
||||
* invocation to preserve backward compatibility.
|
||||
*/
|
||||
export function buildWorktreeComparator(
|
||||
sortBy: SortBy,
|
||||
@@ -106,8 +204,23 @@ export function buildWorktreeComparator(
|
||||
repoMap: Map<string, Repo>,
|
||||
prCache: Record<string, PRCacheEntry> | null,
|
||||
now: number = Date.now(),
|
||||
smartSortOverrides: Record<string, SmartSortOverride> | null = null
|
||||
smartSortOverrides: Record<string, SmartSortOverride> | null = null,
|
||||
agentStatusByPaneKey?: Record<string, AgentStatusEntry>,
|
||||
precomputedScores?: Map<string, number>,
|
||||
explicitByTabId?: Map<string, AgentStatusEntry[]>
|
||||
): (a: Worktree, b: Worktree) => number {
|
||||
// Why: when the caller does not pre-build the tabId index but does provide
|
||||
// the source map, build it ONCE here and close over it. Array.sort invokes
|
||||
// the comparator O(N log N) times in the fallback path (no precomputed
|
||||
// scores), and `computeSmartScoreFromSignals` would otherwise rebuild the
|
||||
// O(E) index on every comparison — re-introducing the O(N log N × E) cost
|
||||
// the precompute was meant to avoid. Only matters for the smart mode; for
|
||||
// other modes we skip construction.
|
||||
const resolvedExplicitByTabId =
|
||||
sortBy === 'smart' && !explicitByTabId && agentStatusByPaneKey
|
||||
? buildExplicitEntriesByTabId(agentStatusByPaneKey)
|
||||
: explicitByTabId
|
||||
|
||||
return (a, b) => {
|
||||
switch (sortBy) {
|
||||
case 'name':
|
||||
@@ -127,19 +240,42 @@ export function buildWorktreeComparator(
|
||||
prCache,
|
||||
smartSortOverrides
|
||||
)
|
||||
// Why precomputedScores: the smart-score computation iterates
|
||||
// `agentStatusByPaneKey` (O(E) per call) when no tabId index is
|
||||
// threaded in, and still does O(T) lookups per worktree when one is.
|
||||
// The comparator is invoked O(N log N) times by Array.sort, so without
|
||||
// memoization we pay O(N log N × E) (or O(N log N × T) with the
|
||||
// index). When the caller supplies a precomputed score map we get
|
||||
// O(1) lookups; when it doesn't we preserve the old behavior and pass
|
||||
// the optional `explicitByTabId` index to the inner function so the
|
||||
// fallback path avoids the full-map scan as well. Overrides bypass the
|
||||
// precomputed map because the override intentionally freezes the
|
||||
// candidate's inputs (tabs, hasRecentPRSignal) which may differ from
|
||||
// the live score.
|
||||
const scoreA =
|
||||
precomputedScores && !smartSortOverrides?.[a.id]
|
||||
? (precomputedScores.get(a.id) ?? 0)
|
||||
: computeSmartScoreFromSignals(
|
||||
smartA.worktree,
|
||||
smartA.tabs,
|
||||
smartA.hasRecentPRSignal,
|
||||
now,
|
||||
agentStatusByPaneKey,
|
||||
resolvedExplicitByTabId
|
||||
)
|
||||
const scoreB =
|
||||
precomputedScores && !smartSortOverrides?.[b.id]
|
||||
? (precomputedScores.get(b.id) ?? 0)
|
||||
: computeSmartScoreFromSignals(
|
||||
smartB.worktree,
|
||||
smartB.tabs,
|
||||
smartB.hasRecentPRSignal,
|
||||
now,
|
||||
agentStatusByPaneKey,
|
||||
resolvedExplicitByTabId
|
||||
)
|
||||
return (
|
||||
computeSmartScoreFromSignals(
|
||||
smartB.worktree,
|
||||
smartB.tabs,
|
||||
smartB.hasRecentPRSignal,
|
||||
now
|
||||
) -
|
||||
computeSmartScoreFromSignals(
|
||||
smartA.worktree,
|
||||
smartA.tabs,
|
||||
smartA.hasRecentPRSignal,
|
||||
now
|
||||
) ||
|
||||
scoreB - scoreA ||
|
||||
smartB.worktree.lastActivityAt - smartA.worktree.lastActivityAt ||
|
||||
a.displayName.localeCompare(b.displayName)
|
||||
)
|
||||
@@ -179,7 +315,8 @@ export function sortWorktreesSmart(
|
||||
worktrees: Worktree[],
|
||||
tabsByWorktree: Record<string, TerminalTab[]>,
|
||||
repoMap: Map<string, Repo>,
|
||||
prCache: Record<string, PRCacheEntry> | null
|
||||
prCache: Record<string, PRCacheEntry> | null,
|
||||
agentStatusByPaneKey?: Record<string, AgentStatusEntry>
|
||||
): Worktree[] {
|
||||
const hasAnyLivePty = Object.values(tabsByWorktree)
|
||||
.flat()
|
||||
@@ -192,8 +329,52 @@ export function sortWorktreesSmart(
|
||||
)
|
||||
}
|
||||
|
||||
// Why precompute: Array.sort calls the comparator O(N log N) times and the
|
||||
// smart-score computation needs to look up explicit-status entries per tab.
|
||||
// We apply two layered optimizations:
|
||||
// 1. Build the `explicitByTabId` index ONCE up front (O(E) work). Without
|
||||
// it, each per-worktree score would scan the full `agentStatusByPaneKey`
|
||||
// map to find matching entries, which is O(N × E × T) across all
|
||||
// worktrees — the same cost the decorate-sort-undecorate pass was
|
||||
// supposed to avoid.
|
||||
// 2. Precompute each worktree's score once (decorate-sort-undecorate) so
|
||||
// the comparator does O(1) map lookups instead of re-scoring per
|
||||
// comparison.
|
||||
// Combined cost: O(E) index build + O(N × T) scoring + O(N log N) sort,
|
||||
// instead of the prior O(N × E × T + N log N).
|
||||
const now = Date.now()
|
||||
const explicitByTabId = buildExplicitEntriesByTabId(agentStatusByPaneKey)
|
||||
const precomputedScores = new Map<string, number>(
|
||||
worktrees.map((w) => [
|
||||
w.id,
|
||||
computeSmartScore(
|
||||
w,
|
||||
tabsByWorktree,
|
||||
repoMap,
|
||||
prCache,
|
||||
now,
|
||||
agentStatusByPaneKey,
|
||||
explicitByTabId
|
||||
)
|
||||
])
|
||||
)
|
||||
|
||||
// Why: agentStatusByPaneKey is forwarded so the smart-score comparator can
|
||||
// use explicit agent status (OSC 9999) when ranking worktrees by recency.
|
||||
// `explicitByTabId` is forwarded too so the comparator's fallback path (used
|
||||
// for worktrees covered by smartSortOverrides) avoids rebuilding the index.
|
||||
return [...worktrees].sort(
|
||||
buildWorktreeComparator('smart', tabsByWorktree, repoMap, prCache, Date.now())
|
||||
buildWorktreeComparator(
|
||||
'smart',
|
||||
tabsByWorktree,
|
||||
repoMap,
|
||||
prCache,
|
||||
now,
|
||||
null,
|
||||
agentStatusByPaneKey,
|
||||
precomputedScores,
|
||||
explicitByTabId
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -215,7 +396,9 @@ export function computeSmartScore(
|
||||
tabsByWorktree: Record<string, TerminalTab[]> | null,
|
||||
repoMap: Map<string, Repo> | null,
|
||||
prCache: Record<string, PRCacheEntry> | null,
|
||||
now: number = Date.now()
|
||||
now: number = Date.now(),
|
||||
agentStatusByPaneKey?: Record<string, AgentStatusEntry>,
|
||||
explicitByTabId?: Map<string, AgentStatusEntry[]>
|
||||
): number {
|
||||
return computeSmartScoreFromSignals(
|
||||
worktree,
|
||||
@@ -225,6 +408,8 @@ export function computeSmartScore(
|
||||
// only while that branch cache entry is still cold so smart sorting stays
|
||||
// stable on launch without reviving stale PRs after a cache miss resolves.
|
||||
repoMap ? hasRecentPRSignal(worktree, repoMap, prCache) : worktree.linkedPR !== null,
|
||||
now
|
||||
now,
|
||||
agentStatusByPaneKey,
|
||||
explicitByTabId
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Worktree, Repo, TerminalTab } from '../../../../shared/types'
|
||||
import type { AppState } from '@/store/types'
|
||||
import { AGENT_DASHBOARD_ENABLED } from '../../../../shared/constants'
|
||||
import { matchesSearch } from './worktree-list-groups'
|
||||
import { buildWorktreeComparator, sortWorktreesSmart } from './smart-sort'
|
||||
import { useAppStore } from '@/store'
|
||||
@@ -119,10 +120,15 @@ export function getVisibleWorktreeIds(): string[] {
|
||||
|
||||
let sortedIds: string[]
|
||||
|
||||
const agentStatusForSort = AGENT_DASHBOARD_ENABLED ? state.agentStatusByPaneKey : undefined
|
||||
if (state.sortBy === 'smart') {
|
||||
sortedIds = sortWorktreesSmart(allWorktrees, state.tabsByWorktree, repoMap, state.prCache).map(
|
||||
(w) => w.id
|
||||
)
|
||||
sortedIds = sortWorktreesSmart(
|
||||
allWorktrees,
|
||||
state.tabsByWorktree,
|
||||
repoMap,
|
||||
state.prCache,
|
||||
agentStatusForSort
|
||||
).map((w) => w.id)
|
||||
} else {
|
||||
const sorted = [...allWorktrees].sort(
|
||||
buildWorktreeComparator(
|
||||
@@ -130,7 +136,9 @@ export function getVisibleWorktreeIds(): string[] {
|
||||
state.tabsByWorktree,
|
||||
repoMap,
|
||||
state.prCache,
|
||||
Date.now()
|
||||
Date.now(),
|
||||
null,
|
||||
agentStatusForSort
|
||||
)
|
||||
)
|
||||
sortedIds = sorted.map((w) => w.id)
|
||||
|
||||
@@ -255,9 +255,16 @@ export function AgentIcon({
|
||||
agent,
|
||||
size = 14
|
||||
}: {
|
||||
agent: TuiAgent
|
||||
agent: TuiAgent | null | undefined
|
||||
size?: number
|
||||
}): React.JSX.Element {
|
||||
// Why: render a neutral question-mark glyph when the agent identity is not
|
||||
// yet known. Before, the caller coerced null → 'claude', which caused Codex
|
||||
// panes to briefly show the Claude icon until the first hook callback
|
||||
// arrived.
|
||||
if (!agent) {
|
||||
return <AgentLetterIcon letter="?" size={size} />
|
||||
}
|
||||
if (agent === 'claude') {
|
||||
return <ClaudeIcon size={size} />
|
||||
}
|
||||
|
||||
@@ -560,8 +560,8 @@ describe('mapAgentStatusStateToVisualStatus', () => {
|
||||
expect(mapAgentStatusStateToVisualStatus('waiting')).toBe('permission')
|
||||
})
|
||||
|
||||
it("maps 'done' to 'active'", () => {
|
||||
expect(mapAgentStatusStateToVisualStatus('done')).toBe('active')
|
||||
it("maps 'done' to 'done'", () => {
|
||||
expect(mapAgentStatusStateToVisualStatus('done')).toBe('done')
|
||||
})
|
||||
|
||||
it('returns a non-empty string for every valid state', () => {
|
||||
|
||||
@@ -176,7 +176,7 @@ export function isExplicitAgentStatusFresh(
|
||||
* | working | working | agent actively executing |
|
||||
* | blocked | permission | agent needs user attention |
|
||||
* | waiting | permission | agent needs user attention |
|
||||
* | done | active | task complete but pane live |
|
||||
* | done | done | task complete but pane live |
|
||||
*/
|
||||
export function mapAgentStatusStateToVisualStatus(state: AgentStatusState): WorktreeStatus {
|
||||
switch (state) {
|
||||
@@ -186,7 +186,7 @@ export function mapAgentStatusStateToVisualStatus(state: AgentStatusState): Work
|
||||
case 'waiting':
|
||||
return 'permission'
|
||||
case 'done':
|
||||
return 'active'
|
||||
return 'done'
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { detectAgentStatusFromTitle } from '@/lib/agent-status'
|
||||
import type { TerminalTab } from '../../../shared/types'
|
||||
|
||||
export type WorktreeStatus = 'active' | 'working' | 'permission' | 'inactive'
|
||||
export type WorktreeStatus = 'active' | 'working' | 'permission' | 'done' | 'inactive'
|
||||
|
||||
const STATUS_LABELS: Record<WorktreeStatus, string> = {
|
||||
active: 'Active',
|
||||
working: 'Working',
|
||||
permission: 'Needs permission',
|
||||
done: 'Done',
|
||||
inactive: 'Inactive'
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,9 @@ describe('agent status freshness expiry', () => {
|
||||
vi.setSystemTime(new Date('2026-04-09T12:00:00.000Z'))
|
||||
|
||||
const store = createTestStore()
|
||||
store.getState().setAgentStatus('tab-1:1', { state: 'working', prompt: 'Fix tests' }, 'codex')
|
||||
store
|
||||
.getState()
|
||||
.setAgentStatus('tab-1:1', { state: 'working', prompt: 'Fix tests', agentType: 'codex' })
|
||||
|
||||
// setAgentStatus bumps epoch once synchronously
|
||||
expect(store.getState().agentStatusEpoch).toBe(1)
|
||||
@@ -43,7 +45,9 @@ describe('agent status freshness expiry', () => {
|
||||
vi.setSystemTime(new Date('2026-04-09T12:00:00.000Z'))
|
||||
|
||||
const store = createTestStore()
|
||||
store.getState().setAgentStatus('tab-1:1', { state: 'working', prompt: 'Fix tests' }, 'codex')
|
||||
store
|
||||
.getState()
|
||||
.setAgentStatus('tab-1:1', { state: 'working', prompt: 'Fix tests', agentType: 'codex' })
|
||||
// set bumps to 1, remove bumps to 2
|
||||
store.getState().removeAgentStatus('tab-1:1')
|
||||
expect(store.getState().agentStatusEpoch).toBe(2)
|
||||
@@ -68,17 +72,14 @@ describe('agent status tool + assistant fields', () => {
|
||||
it('writes toolName, toolInput, and lastAssistantMessage straight onto the entry', () => {
|
||||
vi.useFakeTimers()
|
||||
const store = createTestStore()
|
||||
store.getState().setAgentStatus(
|
||||
'tab-1:1',
|
||||
{
|
||||
state: 'working',
|
||||
prompt: 'Edit the config',
|
||||
toolName: 'Edit',
|
||||
toolInput: '/src/config.ts',
|
||||
lastAssistantMessage: 'Edited config.ts'
|
||||
},
|
||||
'claude'
|
||||
)
|
||||
store.getState().setAgentStatus('tab-1:1', {
|
||||
state: 'working',
|
||||
prompt: 'Edit the config',
|
||||
agentType: 'claude',
|
||||
toolName: 'Edit',
|
||||
toolInput: '/src/config.ts',
|
||||
lastAssistantMessage: 'Edited config.ts'
|
||||
})
|
||||
const entry = store.getState().agentStatusByPaneKey['tab-1:1']
|
||||
expect(entry.toolName).toBe('Edit')
|
||||
expect(entry.toolInput).toBe('/src/config.ts')
|
||||
@@ -88,21 +89,20 @@ describe('agent status tool + assistant fields', () => {
|
||||
it('clears fields to undefined when a later payload omits them', () => {
|
||||
vi.useFakeTimers()
|
||||
const store = createTestStore()
|
||||
store.getState().setAgentStatus(
|
||||
'tab-1:1',
|
||||
{
|
||||
state: 'working',
|
||||
prompt: 'Edit the config',
|
||||
toolName: 'Edit',
|
||||
toolInput: '/src/config.ts',
|
||||
lastAssistantMessage: 'Edited config.ts'
|
||||
},
|
||||
'claude'
|
||||
)
|
||||
store.getState().setAgentStatus('tab-1:1', {
|
||||
state: 'working',
|
||||
prompt: 'Edit the config',
|
||||
agentType: 'claude',
|
||||
toolName: 'Edit',
|
||||
toolInput: '/src/config.ts',
|
||||
lastAssistantMessage: 'Edited config.ts'
|
||||
})
|
||||
// Why: the main-process cache is the source of truth for tool/assistant
|
||||
// fields — a fresh-turn reset surfaces as undefined on the payload, and
|
||||
// the store must not fall back to the prior entry's values.
|
||||
store.getState().setAgentStatus('tab-1:1', { state: 'working', prompt: 'Next step' }, 'claude')
|
||||
store
|
||||
.getState()
|
||||
.setAgentStatus('tab-1:1', { state: 'working', prompt: 'Next step', agentType: 'claude' })
|
||||
const entry = store.getState().agentStatusByPaneKey['tab-1:1']
|
||||
expect(entry.toolName).toBeUndefined()
|
||||
expect(entry.toolInput).toBeUndefined()
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type ParsedAgentStatusPayload
|
||||
} from '../../../../shared/agent-status-types'
|
||||
import type { TerminalTab } from '../../../../shared/types'
|
||||
import { isExplicitAgentStatusFresh } from '@/lib/agent-status'
|
||||
|
||||
/** Snapshot of a finished (or vanished) agent status entry, kept around so
|
||||
* the dashboard + sidebar hover can continue showing the completion until the
|
||||
@@ -209,15 +210,28 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
// it when a new turn starts (working → Stop reprices it).
|
||||
interrupted: payload.interrupted
|
||||
}
|
||||
// Why: `agentStatusEpoch` bumps on every update because visual +
|
||||
// freshness selectors (WorktreeCard status, hover content) care about
|
||||
// tool-name/prompt/assistant-message churn within a turn. `sortEpoch`,
|
||||
// on the other hand, bumps only when sort-relevant inputs change —
|
||||
// avoiding sidebar re-sorts on every tool/prompt event would stress
|
||||
// the smart-sort debounce for no reason. Sort-relevant inputs are:
|
||||
// 1. `state` transitions — sort score is a function of state.
|
||||
// 2. Freshness transitions (stale → fresh) — `computeSmartScoreFromSignals`
|
||||
// in smart-sort.ts filters entries through
|
||||
// `isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)`
|
||||
// (30-min TTL). A stale entry that refreshes with the SAME state
|
||||
// goes from "not contributing" to contributing +60 (working) or
|
||||
// +35 (blocked/waiting) to the score — order must update. The new
|
||||
// entry below always has `updatedAt = now`, so it is fresh; we
|
||||
// only need to detect the stale→fresh flip on `existing`.
|
||||
const wasFresh =
|
||||
!!existing && isExplicitAgentStatusFresh(existing, now, AGENT_STATUS_STALE_AFTER_MS)
|
||||
const sortRelevantChange = !existing || existing.state !== payload.state || !wasFresh
|
||||
return {
|
||||
agentStatusByPaneKey: { ...s.agentStatusByPaneKey, [paneKey]: entry },
|
||||
// Why: bump both epochs so WorktreeCard re-derives its visual status
|
||||
// and WorktreeList re-sorts immediately when an agent reports status.
|
||||
// The freshness-expiry timer and the remove* paths bump both epochs
|
||||
// for the same reason — agent transitions (new, stale, removed) can
|
||||
// all legitimately change worktree sort order.
|
||||
agentStatusEpoch: s.agentStatusEpoch + 1,
|
||||
sortEpoch: s.sortEpoch + 1
|
||||
sortEpoch: sortRelevantChange ? s.sortEpoch + 1 : s.sortEpoch
|
||||
}
|
||||
})
|
||||
// Why: schedule after set completes so the timer reads the updated map.
|
||||
|
||||
Reference in New Issue
Block a user