import { useMemo, useSyncExternalStore } from 'react' import type { SessionSummary } from '@/types/api' import { AgentFlavorIcon } from '@/components/AgentFlavorIcon' import { InfoIcon, LoaderIcon, ScheduleIcon, StoppedBadgeIcon } from '@/components/icons' import { HoverTooltip, SESSION_ROW_TOOLTIP_FOCUS_CLASS, useSessionRowTooltipIds } from '@/components/HoverTooltip' import { getAttentionLabel, SessionAttentionIndicator, SessionRequestIcon } from '@/components/SessionAttentionIndicator' import { classifySessionAttention, sessionIsUnread } from '@/lib/sessionAttention' import { getSessionLastSeenAt, getSessionManualUnreadAt } from '@/lib/sessionLastSeen' import { formatRelativeTime } from '@/lib/relativeTime' import { formatScheduledTooltipDetail } from '@/lib/scheduledTime' import { getCodexImportedAt, subscribeCodexImportedSessions } from '@/lib/codexImportedSessions' import { useMinuteTick } from '@/hooks/useMinuteTick' import { getSessionTitle } from '@/lib/sessionTitle' import { useTranslation } from '@/lib/use-translation' import { getWorktreeSessionLabel } from '@/lib/sessionWorktreeLabel' import { attachedJobFraction, formatAttachedJobProgress, isAttachedJobStale } from '@/lib/attachedJob' import { hasUrgentModelError } from '@/components/ModelErrorBanner' function BulbIcon(props: { className?: string }) { return ( ) } function getTodoProgress(session: SessionSummary): { completed: number; total: number } | null { if (!session.todoProgress) return null if (session.todoProgress.completed === session.todoProgress.total) return null return session.todoProgress } function formatCodexImportedRelativeTime( value: number, t: (key: string, params?: Record) => string ): string | null { const ms = value < 1_000_000_000_000 ? value * 1000 : value if (!Number.isFinite(ms)) return null const delta = Date.now() - ms if (delta < 60_000) return t('session.time.importedFromCodex.justNow') const minutes = Math.floor(delta / 60_000) if (minutes < 60) return t('session.time.importedFromCodex.minutesAgo', { n: minutes }) const hours = Math.floor(minutes / 60) if (hours < 24) return t('session.time.importedFromCodex.hoursAgo', { n: hours }) const days = Math.floor(hours / 24) if (days < 7) return t('session.time.importedFromCodex.daysAgo', { n: days }) return formatRelativeTime(value, t) } function getSessionTimeLabel( session: SessionSummary, importedAt: number | null, t: (key: string, params?: Record) => string ): string | null { if (importedAt !== null) { return formatCodexImportedRelativeTime(importedAt, t) } return formatRelativeTime(session.updatedAt, t) } const PRESENCE_BADGE_CLASS = { working: 'bg-[var(--app-badge-success-text)] animate-pulse', background: 'bg-blue-400 animate-pulse', waiting: 'border-2 border-[var(--app-badge-success-text)] bg-[var(--app-bg)]', stopped: 'bg-[var(--app-bg)] text-[var(--app-hint)]', } as const /** * Presentational session row — same chrome as the sidebar SessionItem body * (flavor icon with presence badge, title, request/schedule symbols, todos, * relative time, path, optional attached-job meter). Visual language matches * the native apps for presence. A title-side spinner combines running activity * with unread state; unread at rest uses a foreground dot. The title dims when * the session is not resident. Used by the * session list and by rich-composer mention chip tooltips. */ export function SessionRowSummary(props: { session: SessionSummary showPath?: boolean showDetailedStatus?: boolean selected?: boolean /** * When false, attention has no nested HoverTooltip. * Use false inside an already-open chip tooltip portal. */ nestedTooltips?: boolean /** Pass from parent when the parent owns `aria-describedby` (session list). */ attentionTooltipId?: string /** Recompute local unread attention when the session-list watermark changes. */ lastSeenVersion?: number scheduleTooltipId?: string className?: string /** Rows inside the pinned "in progress" section skip the pending text label. */ inRunningSection?: boolean /** Short project name shown under the title (pinned "in progress" rows). */ projectLabel?: string /** Machine label shown next to the project name (pinned "in progress" rows). */ machineLabel?: string /** Context returned by the opt-in session message-content search. */ contentSnippet?: string /** The indexed message exceeded the search index budget. */ contentSearchTruncated?: boolean /** Extra classes for the right-hand time/progress cluster (e.g. to yield to hover actions). */ trailingClassName?: string }) { const { session: s, showPath = true, showDetailedStatus = true, selected = false, nestedTooltips = true, attentionTooltipId: attentionTooltipIdProp, lastSeenVersion, scheduleTooltipId: scheduleTooltipIdProp, className, inRunningSection = false, projectLabel, machineLabel, contentSnippet, contentSearchTruncated = false, trailingClassName, } = props const { t } = useTranslation() const sessionName = getSessionTitle(s) const worktreeLabel = getWorktreeSessionLabel(s) const todoProgress = getTodoProgress(s) const attention = useMemo( () => showDetailedStatus ? classifySessionAttention(s, { selected, lastSeenAt: getSessionLastSeenAt(s.id), manualUnreadAt: getSessionManualUnreadAt(s.id, s.readState), }) : null, [s, selected, showDetailedStatus, lastSeenVersion] ) const attentionLabel = attention ? getAttentionLabel(attention, t) : null const urgentAttention = attention !== null && (attention.kind === 'permission' || attention.kind === 'input') const modelErrorActive = hasUrgentModelError(s.metadata) const modelErrorLabel = t('session.modelError.listIndicator') const scheduledLabel = s.futureScheduledMessageCount > 1 ? t('session.item.scheduledMessages', { count: s.futureScheduledMessageCount }) : t('session.item.scheduledMessage') const hasScheduleTooltip = showDetailedStatus && s.futureScheduledMessageCount > 0 const ownedIds = useSessionRowTooltipIds( Boolean(attention) && nestedTooltips && !attentionTooltipIdProp, hasScheduleTooltip && nestedTooltips && !scheduleTooltipIdProp ) const attentionId = attentionTooltipIdProp ?? ownedIds.attentionId const scheduleId = scheduleTooltipIdProp ?? ownedIds.scheduleId // Rows are memoized, so the label keeps itself current (also advances job elapsed). useMinuteTick() const nowMs = Date.now() const codexSessionId = s.metadata?.flavor === 'codex' ? s.metadata?.agentSessionId : null const importedAt = useSyncExternalStore(subscribeCodexImportedSessions, () => getCodexImportedAt(codexSessionId)) const timeLabel = getSessionTimeLabel(s, importedAt, t) const attachedJob = s.attachedJob?.status === 'running' ? s.attachedJob : null const jobStale = attachedJob ? isAttachedJobStale(attachedJob, nowMs) : false const jobFraction = attachedJob ? attachedJobFraction(attachedJob) : null const jobProgressLabel = attachedJob ? formatAttachedJobProgress(attachedJob, nowMs, { left: t('session.item.attachedJob.left'), running: t('session.item.attachedJob.running'), noHeartbeat: t('session.item.attachedJob.noHeartbeat'), }) : null // Presence lives on the agent icon and every state has its own mark, so no // state is shown by the absence of one: solid = working (pulsing), ring = // connected and waiting, power mark = stopped or archived. Blue is the // existing background-work state. An outliving attached job counts as // working even when the agent itself is idle or disconnected. // The badge carries *which* state on inspection; the row-level residency // fade below carries *which rows* at a glance. Same predicate (!active), // two scales — a 10px mark doesn't survive a long-list scan on its own. const isRunning = s.active && s.thinking const isBackgroundOnly = s.active && !s.thinking && (s.backgroundTaskCount ?? 0) > 0 const presence: 'working' | 'background' | 'waiting' | 'stopped' = isBackgroundOnly ? 'background' : isRunning || attachedJob ? 'working' : s.active ? 'waiting' : 'stopped' const isUnread = sessionIsUnread(s, { lastSeenAt: getSessionLastSeenAt(s.id), manualUnreadAt: getSessionManualUnreadAt(s.id, s.readState), }) const requestKind = urgentAttention ? attention.kind as 'permission' | 'input' : s.active && (s.pendingRequestsCount ?? 0) > 0 ? (s.pendingRequestKinds?.length && !s.pendingRequestKinds.includes('permission') ? 'input' : 'permission') : null // `thinking` is authoritative for foreground activity. A pending input can // be blocking or async, and summaries do not distinguish the two, so keep // the spinner rather than hiding real work behind the request symbol. // Independent background work/jobs still count, even if the agent is // disconnected. No work running is not a claim of successful completion: // summaries carry no turn-outcome field, and the dot only means unread. const hasRunningWork = Boolean(attachedJob) || (s.active && (s.backgroundTaskCount ?? 0) > 0) || isRunning // While work runs, the spinner colour alone carries unread. A bold title and // accented time are the at-rest unread look, so using them mid-run makes a // working session read as finished. const emphasizeUnread = isUnread && !hasRunningWork const activityLabel = isBackgroundOnly ? t('session.item.background') : t('session.item.running') const pendingRequestId = s.pendingRequests?.[0]?.id const agentIcon = ( {presence === 'stopped' ? : null} ) return (
{attention?.kind === 'background' && nestedTooltips && attentionId ? ( ) : agentIcon}
{/* Fade the disconnected title, keeping activity/unread indicators and outliving job progress at full contrast. */}
{sessionName}
{/* Model error outranks activity/unread: the turn looked finished but failed, so this must not be collapsed into the combined indicator below. */} {modelErrorActive ? ( ) : null} {hasRunningWork ? ( ) : isUnread && !requestKind ? (
{todoProgress ? ( {todoProgress.completed}/{todoProgress.total} ) : null} {!attention && s.active && s.pendingRequestsCount > 0 ? ( {t('session.item.pending')} {s.pendingRequestsCount} ) : null} {timeLabel ? ( {timeLabel} ) : null}
{attachedJob && jobProgressLabel ? (
) : null} {contentSnippet ? (
{contentSnippet} {contentSearchTruncated ? ( ) : null}
) : null} {projectLabel || machineLabel ? (
{[projectLabel, machineLabel].filter(Boolean).join(' · ')}
) : showPath || worktreeLabel ? (
{worktreeLabel ?? s.metadata?.path ?? s.id}
) : null}
) }