import { useAtomMount } from "@effect/atom-react"; import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; import { ThreadHoverCard, ThreadHoverCardPopup } from "../ThreadHoverCard"; import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators"; import { discardComposerDraft } from "../../lib/discardComposerDraft"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { requestCustomSnooze } from "../CustomSnoozeDialog"; import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; import { useDeadlinePassed } from "~/hooks/useDeadline"; import { resolveThreadCurrentPullRequestLink } from "@t3tools/client-runtime/thread-pull-requests"; import { useDraggable } from "@dnd-kit/core"; import { useSortable } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { canSnooze, hasQueuedTurnStart, QUEUED_TURN_START_GRACE_MS, } from "@t3tools/client-runtime/state/thread-settled"; import { formatDiffCount } from "@t3tools/client-runtime/diff-count"; import { resolveSettledThreadTimestamp, resolveThreadActivityTimestamp, } from "@t3tools/client-runtime/state/thread-sort"; import { type EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search"; import { formatWorkingDurationLabel, resolveThreadProviderStack, } from "@t3tools/client-runtime/state/models"; import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment"; import { toServerClock } from "@t3tools/client-runtime/clock"; import { AuthOrchestrationOperateScope, type ContextMenuSource, type EnvironmentId, type EnvironmentMachineKind, type ScopedThreadRef, } from "@t3tools/contracts"; import type { TimestampFormat } from "@t3tools/contracts/settings"; import { AlarmClockIcon, AlarmClockOffIcon, ArrowRightLeftIcon, CheckIcon, CircleAlertIcon, CircleCheckIcon, CircleDashedIcon, CircleDotDashedIcon, ClockIcon, GitBranchIcon, MessageCircleQuestionIcon, PinIcon, PinOffIcon, ShieldQuestionIcon, SquarePenIcon, TerminalIcon, Undo2Icon, UserRoundIcon, XIcon, } from "lucide-react"; import { memo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent, type PointerEvent as ReactPointerEvent, type ReactNode, } from "react"; import { msg, T, useGT, useMessages, Var } from "gt-react"; import type { MessageResolver } from "../../i18n/messages"; import { useRightPanelStore } from "../../rightPanelStore"; import { useOpenPrLink } from "../../lib/openPullRequestLink"; import { useUiStateStore } from "../../uiStateStore"; import { useThreadSelectionStore } from "../../threadSelectionStore"; import { useNowMinute } from "../../hooks/useNowMinute"; import { useNowSecond } from "../../hooks/useNowSecond"; import { vcsEnvironment, vcsBranchRevalidation } from "../../state/vcs"; import { useLinkedIssueDetail } from "../../state/issues"; import { useEnvironmentQuery } from "../../state/query"; import { readEnvironmentScope, useEnvironmentScope } from "../../state/session"; import { formatRelativeTime, parseTimestampDate } from "../../timestampFormat"; import type { SidebarThreadSummary } from "../../types"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; import { cn } from "~/lib/utils"; import { textDirection } from "~/textDirection"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { animateSidebarLayoutChanges, hasUnseenCompletion, resolveSidebarRowAccessibility, type SidebarDropVerb, resolveSidebarRowStatus, resolveThreadLastVisitedAt, shouldRecedeSidebarThread, resolveWorkingStartedAt, useRetainedValue, withoutRemovedCheckout, useSidebarRowSubscriptionLease, setFileDragActive, } from "../Sidebar.logic"; import { resolveLocalCheckoutBranchMismatch } from "../BranchToolbar.logic"; import { ThreadPullRequestBadgeControl, ThreadPullRequestsMiniList, ThreadWorktreeIndicator, prStatusIndicator, resolveThreadPullRequestBadge, terminalStatusFromRunningIds, type TerminalStatusIndicator, useLinkedThreadPullRequest, ThreadSearchPullRequestNumber, } from "../ThreadStatusIndicators"; import { pickSnoozePreset, resolveSnoozePresets, type SnoozePreset } from "../Sidebar.snooze"; import { useThreadShell } from "../../state/entities"; import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; import { ThreadSearchMatchExcerpt } from "../ThreadSearchMatch"; import { makeWorkspaceFileDropHandlers } from "../chat/workspaceFileDrop"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { getTriggerDisplayModelName } from "../chat/providerIconUtils"; import { shouldShowInstanceBadge, type ProviderInstanceEntry } from "../../providerInstances"; import { useThreadRunningTerminalIds } from "../../state/terminalSessions"; import { InlineButton } from "../ui/button"; import { Kbd } from "../ui/kbd"; import { Menu, MenuItem, MenuItemDetail, MenuPopup, MenuSeparator, MenuTrigger } from "../ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { MiddleTruncate } from "../ui/middle-truncate"; import { ActivityShimmerOverlay } from "../chat/TimelineRowParts"; import { observeVisibleAnimation } from "~/lib/visibleAnimation"; import { useThreadHasUnsentDraft } from "../../composerDraftStore"; import { ThreadDetailsIssueRows } from "../chat/ThreadDetailsIssueRows"; import { IssueGlyph, issueStatePresentation } from "../issue/issuePresentation"; // The fields thread rows show. Provider status pushes refresh `checkedAt`, // status and auth on every provider; leaving those out keeps each // environment's map, and every memoized row, stable across them. export type SidebarProviderEntry = Pick< ProviderInstanceEntry, | "instanceId" | "driverKind" | "enabled" | "displayName" | "accentColor" | "acpRegistryAgentId" | "acpRegistryIconUrl" | "models" >; function compactSidebarTimeLabel(timestamp: string, nowMs: number, resolve: MessageResolver) { const parts = formatRelativeTime(timestamp, nowMs, resolve); if (parts === null) return ""; return parts.suffix === null ? resolve(msg("now", { $context: "relative time" })) : parts.value; } // Subscribes to the minute tick itself, so only the label re-renders each // minute. The minute is passed as the clock so it is the formatter's input. function RelativeTimeLabel(props: { timestamp: string | null }) { const nowMinute = useNowMinute(); const m = useMessages(); return props.timestamp === null ? null : compactSidebarTimeLabel(props.timestamp, Date.parse(`${nowMinute}:00.000Z`), m); } function JumpHintBadge(props: { label: string }) { return ( {props.label} ); } const JUMP_HINT_SLOT_CLASS_NAME = "[&>:not([data-jump-hint])]:invisible [&>:not([data-jump-hint])]:absolute"; function WorkingDuration(props: { environmentId: EnvironmentId; startedAt: string | null }) { const startedMs = props.startedAt !== null ? Date.parse(props.startedAt) : Number.NaN; if (Number.isNaN(startedMs)) return null; return ; } // Self-ticking so only this span re-renders each second, not the whole row; // the shared tick lands every working row's update in the same frame. function WorkingDurationLabel(props: { environmentId: EnvironmentId; startedMs: number }) { const nowMs = useNowSecond(); const messages = useMessages(); return ( {formatWorkingDurationLabel( toServerClock(props.environmentId, nowMs) - props.startedMs, messages, )} ); } function terminalProcessLabel(count: number, resolve: MessageResolver): string { return resolve( msg( "{count, plural, one {{count} terminal process running} other {{count} terminal processes running}}", { count }, ), ); } function SidebarProviderStack(props: { thread: SidebarThreadSummary; providerEntryByInstanceId: ReadonlyMap; }) { const stack = resolveThreadProviderStack(props.thread); const currentInstanceId = stack[stack.length - 1]!; const currentEntry = props.providerEntryByInstanceId.get(currentInstanceId) ?? null; if (currentEntry === null) return null; const showInstanceBadge = shouldShowInstanceBadge( currentEntry, props.providerEntryByInstanceId.values(), ); const current = ( ); if (stack.length === 1) { return {current}; } return ( {stack.slice(0, -1).map((instanceId) => { const entry = props.providerEntryByInstanceId.get(instanceId); if (entry === undefined) return null; return ( ); })} {current} ); } function SidebarThreadTooltip({ thread, project, projectDisplayName, environmentLabel, environmentMachine, providerEntry, providerEntryByInstanceId, showInstanceBadge, modelInstanceId, modelLabel, branchMismatch, terminalStatus, terminalProcessCount, }: { thread: SidebarThreadSummary; project: ProjectFaviconProject | null; projectDisplayName: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; providerEntry: SidebarProviderEntry | null; providerEntryByInstanceId: ReadonlyMap; showInstanceBadge: boolean; modelInstanceId: string; modelLabel: string; branchMismatch: { threadBranch: string; currentBranch: string; } | null; terminalStatus: TerminalStatusIndicator | null; terminalProcessCount: number; }) { const driverKind = providerEntry?.driverKind ?? null; const previousProviderNames = thread.providerInstanceHistory .filter((instanceId) => instanceId !== modelInstanceId) .map((instanceId) => providerEntryByInstanceId.get(instanceId)?.displayName ?? instanceId); const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId); const gt = useGT(); const m = useMessages(); return ( 0 ? (
) : null } > {projectDisplayName ? (
{project ? : null}
{projectDisplayName}
) : null} {environmentLabel ? (
{environmentLabel}
) : null} {thread.branch ? (
) : null} {branchMismatch ? (
You're currently checked out on another branch.
) : null} {driverKind ? (
{showInstanceBadge && providerEntry ? `${modelLabel} · ${providerEntry.displayName}` : modelLabel}
) : null} {previousProviderNames.length > 0 ? (
Handed off from {previousProviderNames.join(", ")}
) : null} {terminalStatus ? (
{terminalProcessLabel(terminalProcessCount, m)}
) : null} {thread.runtime?.lastError ? (
{thread.runtime.lastErrorClass === "usage_limit" ? gt("Usage limit reached") : gt("Error occurred")}
) : null}
); } function SnoozeMenuButton(props: { open: boolean; onOpenChange: (open: boolean) => void; onSnooze: (preset: Pick) => void; timestampFormat: TimestampFormat; environmentId: EnvironmentId; }) { const { open, onOpenChange, onSnooze, timestampFormat, environmentId } = props; const gt = useGT(); const messages = useMessages(); const presets = open ? // oxlint-disable-next-line react/purity -- Presets are resolved only while the menu is open, so each opening reads a fresh time. resolveSnoozePresets(new Date(), timestampFormat, environmentId, messages) : []; return ( event.stopPropagation()} onDoubleClick={(event) => event.stopPropagation()} className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" /> } /> } > Snooze thread {presets.map((preset) => ( { event.stopPropagation(); const picked = pickSnoozePreset(presets, preset.id, timestampFormat, environmentId); if (picked) onSnooze(picked); }} > {preset.label} {preset.whenLabel} ))} {presets.length > 0 ? : null} { event.stopPropagation(); const choice = await requestCustomSnooze(); if (choice) onSnooze(choice); }} > Custom… ); } type SortableThreadRowBag = Pick< ReturnType, "listeners" | "setNodeRef" | "transform" | "transition" | "isDragging" >; export const draftSurfaceClassName = "bg-warning/4 hover:bg-warning/8"; export const draftPenClassName = "size-3 shrink-0 text-warning-foreground"; // useSortable memoizes on its `disabled` object, so a fresh one per render // re-renders every row and marker on each sidebar update. export const SIDEBAR_SORTABLE_DRAG_DISABLED = { draggable: true } as const; const SIDEBAR_SORTABLE_DRAG_ENABLED = { draggable: false } as const; // Takes the row's props rather than a render function: a closure from the // sidebar body is new on every sidebar render, which rebuilt the bag and // re-rendered every memoized row with it. export function SortableThreadRow( props: Omit & { sortableId: string; sortableDisabled: boolean; contextDrag: boolean; }, ) { const { sortableId, sortableDisabled, contextDrag, ...rowProps } = props; const canOperateThread = useEnvironmentScope( rowProps.thread.environmentId, AuthOrchestrationOperateScope, ); const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: sortableId, disabled: sortableDisabled || !canOperateThread ? SIDEBAR_SORTABLE_DRAG_DISABLED : SIDEBAR_SORTABLE_DRAG_ENABLED, animateLayoutChanges: animateSidebarLayoutChanges, }); // dnd-kit memoizes each field but not the bag, so the memoized row would // rerender on every shell update without this. const bag = { listeners, setNodeRef, transform: contextDrag ? null : transform, transition: contextDrag && isDragging ? "transform 150ms ease-out" : transition, isDragging: isDragging && !contextDrag, }; // The sidebar arranges rows from quiet shells, which hold still while a // thread streams; reading the live shell here re-renders only this row. const liveThread = useThreadShell( scopeThreadRef(rowProps.thread.environmentId, rowProps.thread.id), ); // A runtime on the arranged copy but not the run-less live shell is the list's launch overlay. const thread = liveThread === null ? rowProps.thread : rowProps.thread.runtime !== null ? asLaunchingThread(liveThread) : liveThread; // Keyed by variant so a card/slim switch remounts the row. return ; } export type SidebarSweepAction = "settle" | "unsettle" | "unsnooze"; const dropVerbBadge: Record = { pin: ( <> Pin ), unpin: ( <> Unpin ), settle: ( <> Settle ), unsettle: ( <> Un-settle ), wake: ( <> Wake ), }; const TOP_STATUS_ICONS = { working: CircleDashedIcon, waiting: CircleDotDashedIcon, input: MessageCircleQuestionIcon, request: UserRoundIcon, approval: ShieldQuestionIcon, failed: CircleAlertIcon, done: CircleCheckIcon, woke: AlarmClockIcon, } as const; function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: string }) { const Icon = TOP_STATUS_ICONS[props.icon]; return ; } type SidebarThreadRowProps = { thread: SidebarThreadSummary; // "folder" is a one-line row inside a boring sidebar project folder; // "folder-multiline" adds the card's branch and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; settlementSupported: boolean; snoozeSupported: boolean; pinningSupported: boolean; isPinned: boolean; sortable?: SortableThreadRowBag | undefined; dropVerb: SidebarDropVerb | null; dragOverPinned: boolean; sweepAction: SidebarSweepAction | null; snoozeWakeLabelText: string | null; wokeAt: string | null; isActive: boolean; // Set on the active row only; scrolls it into view when a reveal is owed. revealRef?: ((row: HTMLElement, threadKey: string) => (() => void) | undefined) | undefined; // Unlike isActive, never true for the ancestor standing in for an open // subagent: drafts and PR clicks care about which composer is on screen. isRouteThread: boolean; // Read at click time; a prop would re-render every row on entering or leaving a thread route. readOpensPullRequestsInRightPanel: () => boolean; jumpLabel: string | null; currentEnvironmentId: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; scratchMachineLabel: string | null; project: EnvironmentProject | null; projectDisplayName: string | null; providerEntryByInstanceId: ReadonlyMap; timestampFormat: TimestampFormat; onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void; onThreadActivate: (threadRef: ScopedThreadRef) => void; onStartRename: (threadRef: ScopedThreadRef, title: string) => void; onRenameTitleChange: (title: string) => void; onCommitRename: (threadRef: ScopedThreadRef, title: string) => void; onCancelRename: () => void; isRenaming: boolean; renamingTitle: string; onContextMenu: ( threadRef: ScopedThreadRef, position: { x: number; y: number }, source: ContextMenuSource, ) => void; onSettle: (threadRef: ScopedThreadRef) => void; onActionSweepStart: ( threadRef: ScopedThreadRef, action: SidebarSweepAction, event: PointerEvent, ) => void; onUnsettle: (threadRef: ScopedThreadRef) => void; onSnooze: (threadRef: ScopedThreadRef, preset: Pick) => void; onUnsnooze: (threadRef: ScopedThreadRef) => void; onUnpin: (threadRef: ScopedThreadRef) => void; onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void; onFileDropThreads?: ((threadRef: ScopedThreadRef, files: File[]) => void) | undefined; }; // Mounted only while renaming, so each rename starts uncommitted. function ThreadRenameInput(props: { title: string; onTitleChange: (title: string) => void; onCommit: () => void; onCancel: () => void; }) { // Enter and Escape blur the input as it unmounts; that blur must not commit again. const settledRef = useRef(false); const gt = useGT(); const handleKeyDown = (event: ReactKeyboardEvent) => { event.stopPropagation(); if (event.nativeEvent.isComposing || event.keyCode === 229) return; if (event.key === "Enter") { event.preventDefault(); settledRef.current = true; props.onCommit(); } else if (event.key === "Escape") { event.preventDefault(); settledRef.current = true; props.onCancel(); } }; return ( props.onTitleChange(event.target.value)} onFocus={(event) => event.currentTarget.select()} onKeyDown={handleKeyDown} onBlur={() => { if (!settledRef.current) props.onCommit(); }} onClick={(event) => event.stopPropagation()} onDoubleClick={(event) => event.stopPropagation()} className="-mx-1 min-w-0 flex-1 rounded-sm bg-card px-1 text-sm font-medium text-card-foreground outline-none ring-1 ring-inset ring-input focus:ring-foreground" /> ); } const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowProps) { const gt = useGT(); const messages = useMessages(); const { isRenaming, onCancelRename, onCommitRename, onContextMenu, onAcknowledgeWoke, onFileDropThreads, onRenameTitleChange, onSettle, onActionSweepStart, onSnooze, onStartRename, onThreadActivate, onThreadClick, onUnsettle, onUnsnooze, onUnpin, readOpensPullRequestsInRightPanel, renamingTitle, thread, variant, variantAction, } = props; const threadRef = scopeThreadRef(thread.environmentId, thread.id); const threadKey = scopedThreadKey(threadRef); const canOperateThread = useEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope); const { leaseLiveStatus, rowRef: leaseRowRef } = useSidebarRowSubscriptionLease(props.isActive); const { revealRef } = props; const rowRef = (row: HTMLElement | null) => { const stopReveal = row === null ? undefined : revealRef?.(row, threadKey); const releaseLease = leaseRowRef(row); if (!stopReveal) return releaseLease; return () => { stopReveal(); releaseLease?.(); }; }; const isRegeneratingTitle = thread.titleRegeneration != null; const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt); const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey)); const openPrLink = useOpenPrLink(); const runningTerminalIds = useThreadRunningTerminalIds({ environmentId: thread.environmentId, threadId: thread.id, }); const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds, messages); const terminalProcessCount = runningTerminalIds.length; const hasUnsentDraft = useThreadHasUnsentDraft(threadRef) && !props.isRouteThread; const handleDiscardDraftClick = (event: ReactMouseEvent) => { event.preventDefault(); event.stopPropagation(); discardComposerDraft(threadRef); }; const gitCwd = thread.worktreePath ?? props.project?.workspaceRoot ?? null; const linkedPullRequestStatus = useLinkedThreadPullRequest( thread.environmentId, thread.linkedPullRequest, leaseLiveStatus, thread.pullRequests, thread.branchPullRequest, ); const branchTarget = leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null ? { environmentId: thread.environmentId, cwd: gitCwd } : null; const gitStatus = useEnvironmentQuery( branchTarget === null ? null : vcsEnvironment.branch({ environmentId: branchTarget.environmentId, input: { cwd: branchTarget.cwd }, }), ); useAtomMount(vcsBranchRevalidation(branchTarget)); const visibleGitStatus = useRetainedValue( JSON.stringify([thread.environmentId, gitCwd]), gitStatus.data, ); const checkoutThread = withoutRemovedCheckout(thread, visibleGitStatus); const pr = linkedPullRequestStatus?.pr ?? null; const supportsMultiplePullRequests = useSupportsMultiplePullRequests(thread.environmentId); const currentLinkedPr = supportsMultiplePullRequests ? resolveThreadCurrentPullRequestLink(thread.pullRequests) : null; const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt }); const status = resolveSidebarRowStatus({ ...thread, lastVisitedAt }); const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt); const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt); const isWoke = wokeAtDate !== null && (lastVisitedDate === null || lastVisitedDate < wokeAtDate) && thread.settledOverride !== "settled"; const shouldRecede = shouldRecedeSidebarThread({ status, isUnread, isWoke, isActive: props.isActive, isSelected, }); const topStatus = status === "preparing" || status === "working" ? { label: status === "preparing" ? gt("Setting up") : thread.goal?.status === "active" ? gt("Goal", { $context: "thread status: working on a goal" }) : gt("Working", { $context: "thread status" }), icon: "working" as const, className: "text-info-foreground", } : status === "waiting" ? { label: gt("Waiting", { $context: "thread status" }), icon: "waiting" as const, className: "text-muted-foreground", } : status === "approval" ? { label: gt("Approval", { $context: "thread status: needs approval" }), icon: "approval" as const, className: "text-warning-foreground", } : status === "input" ? { label: gt("Input", { $context: "thread status: needs user input" }), icon: "input" as const, className: "text-indigo-600 dark:text-indigo-300", } : status === "request" ? { label: gt("Request", { $context: "thread status: guest request" }), icon: "request" as const, className: "text-guest-foreground", } : status === "limited" ? { label: gt("Limited", { $context: "thread status: usage limited" }), icon: "failed" as const, className: "text-warning-foreground", } : status === "failed" ? { label: gt("Failed", { $context: "thread status" }), icon: "failed" as const, className: "text-error-foreground", } : isWoke ? { label: gt("Woke", { $context: "thread status: woke from snooze" }), icon: "woke" as const, className: "text-warning-foreground", } : isUnread ? { label: gt("Done", { $context: "thread status" }), icon: "done" as const, className: "text-success-foreground", } : null; const isWokeStatus = topStatus?.icon === "woke"; const branchMismatch = resolveLocalCheckoutBranchMismatch({ effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree", activeWorktreePath: thread.worktreePath, activeThreadBranch: thread.branch, currentGitBranch: visibleGitStatus?.refName ?? null, }); const prStatus = prStatusIndicator(pr, linkedPullRequestStatus?.sourceControlProvider, messages); const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; const showInstanceBadge = providerEntry !== null && shouldShowInstanceBadge(providerEntry, props.providerEntryByInstanceId.values()); const selectedModel = providerEntry?.models.find( (model) => model.slug === thread.modelSelection.model, ); const modelLabel = selectedModel ? getTriggerDisplayModelName(selectedModel, providerEntry?.driverKind) : thread.modelSelection.model; const isRemote = thread.environmentId !== props.currentEnvironmentId; const showsScratchMachine = !checkoutThread.branch && props.scratchMachineLabel !== null; const detailsTooltip = ( ); const handleClick = (event: ReactMouseEvent) => { onThreadClick(event, threadRef); }; const handleAcknowledgeWokeClick = (event: ReactMouseEvent) => { event.preventDefault(); event.stopPropagation(); if (props.wokeAt === null) return; onAcknowledgeWoke(threadRef, props.wokeAt); }; const handleContextMenu = (event: ReactMouseEvent) => { event.preventDefault(); onContextMenu(threadRef, { x: event.clientX, y: event.clientY }, contextMenuSourceOf(event)); }; const handleKeyDown = (event: ReactKeyboardEvent) => { if (event.target !== event.currentTarget) return; if ( event.key === "F2" && !isRenaming && readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) ) { event.preventDefault(); onStartRename(threadRef, thread.title); return; } if (event.key !== "Enter" && event.key !== " ") return; event.preventDefault(); onThreadActivate(threadRef); }; const handleDoubleClick = (event: ReactMouseEvent) => { if ( !readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope) || isRenaming || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey ) { return; } if ((event.target as HTMLElement).closest("button, a, input")) return; event.preventDefault(); onStartRename(threadRef, thread.title); }; const [isFileDragOver, setIsFileDragOver] = useState(false); const fileDropHandlers = onFileDropThreads ? makeWorkspaceFileDropHandlers({ setDragActive: (active) => setFileDragActive(setIsFileDragOver, active), addFiles: (files) => { onFileDropThreads(threadRef, files); }, addFolders: () => {}, }) : null; const handleSettleClick = (event: ReactMouseEvent) => { event.preventDefault(); event.stopPropagation(); onSettle(threadRef); }; const handleActionPointerDown = (event: ReactPointerEvent) => { if (!event.isPrimary || event.button !== 0) return; event.stopPropagation(); onActionSweepStart(threadRef, variantAction, event.nativeEvent); }; const handleUnsettleClick = (event: ReactMouseEvent) => { event.preventDefault(); event.stopPropagation(); onUnsettle(threadRef); }; const handleUnsnoozeClick = (event: ReactMouseEvent) => { event.preventDefault(); event.stopPropagation(); onUnsnooze(threadRef); }; const handleUnpinClick = (event: ReactMouseEvent) => { event.preventDefault(); event.stopPropagation(); onUnpin(threadRef); }; const handleSnoozePreset = (preset: Pick) => { onSnooze(threadRef, preset); }; const [snoozeMenuOpenRaw, setSnoozeMenuOpen] = useState(false); // The React Compiler caches render results on their inputs, so a clock read // here would stay frozen until `thread` changes and a queued-turn gate would // never reopen. The gate's clock is state, reset with the thread. const [snoozeGateClock, setSnoozeGateClock] = useState(() => ({ thread, now: new Date().toISOString(), })); if (snoozeGateClock.thread !== thread) { // oxlint-disable-next-line react/purity -- Reseeds the snooze gate clock only in the render-phase adjustment that runs when the thread changes. setSnoozeGateClock({ thread, now: new Date().toISOString() }); } const snoozeGateNow = snoozeGateClock.now; const snoozeGateExpiryMs = hasQueuedTurnStart(thread, { now: snoozeGateNow }) ? Date.parse(thread.latestUserMessageAt ?? "") + QUEUED_TURN_START_GRACE_MS : Number.NaN; // A gate still closed past its expiry is held by runtime status, not time, // so no clock tick can open it. const snoozeGateOpensAt = Number.isFinite(snoozeGateExpiryMs) && snoozeGateExpiryMs > Date.parse(snoozeGateNow) ? snoozeGateExpiryMs + 50 : null; const snoozeGateOpened = useDeadlinePassed(snoozeGateOpensAt); if (snoozeGateOpened && snoozeGateOpensAt !== null) { setSnoozeGateClock({ thread, now: new Date(snoozeGateOpensAt).toISOString() }); } const showSnoozeButton = canOperateThread && props.snoozeSupported && canSnooze(thread, { now: snoozeGateNow }); // Closing here, not just masking, keeps the menu from reopening when the button returns. if (snoozeMenuOpenRaw && !showSnoozeButton) setSnoozeMenuOpen(false); const snoozeMenuOpen = snoozeMenuOpenRaw && showSnoozeButton; const jumpHintLabel = snoozeMenuOpen ? null : props.jumpLabel; const handlePrClick = (event: ReactMouseEvent, targetUrl?: string) => { const url = targetUrl ?? pr?.url ?? currentLinkedPr?.url; if (!url) return; const showInRightPanel = targetUrl !== undefined || readOpensPullRequestsInRightPanel(); const openedInRightPanel = openPrLink(event, url, showInRightPanel ? threadRef : undefined); if (openedInRightPanel && showInRightPanel && !props.isRouteThread) { onThreadActivate(threadRef); } }; const rowSurfaceClassName = cn( "group/sidebar-row relative w-full cursor-pointer overflow-hidden rounded-md text-left outline-none select-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring", variantAction === "unsettle" && !props.isActive && "[&:not(:hover):not(:focus-within)_*:not(.live-activity-focus_*)]:text-secondary-label", props.isActive ? "bg-sidebar-row-active text-sidebar-foreground light:ring-1 light:ring-inset light:ring-sidebar-border/70" : isSelected || props.sweepAction !== null ? "bg-sidebar-row-selected text-sidebar-foreground light:ring-1 light:ring-inset light:ring-sidebar-border/70" : hasUnsentDraft ? cn(draftSurfaceClassName, "text-sidebar-foreground") : shouldRecede ? "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground" : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover", shouldRecede && (status === "preparing" || status === "working") && "opacity-70 transition-opacity hover:opacity-100 focus-within:opacity-100 motion-reduce:transition-none", isFileDragOver && "ring-1 ring-inset ring-primary/70", isFileDragOver && !props.isActive && !isSelected && "bg-sidebar-row-hover", props.sortable?.isDragging && "bg-sidebar bg-linear-to-b from-sidebar-row-active to-sidebar-row-active text-sidebar-foreground opacity-100 shadow-lg", ); const sortable = props.sortable; const sortableRootProps = sortable ? { ref: sortable.setNodeRef, style: { transform: CSS.Translate.toString(sortable.transform), transition: sortable.transition, // A zero-height boundary also makes dnd-kit scale the source to // zero. Only projected peers use scaleY as a visibility sentinel. visibility: !sortable.isDragging && sortable.transform?.scaleY === 0 ? ("hidden" as const) : undefined, }, ...sortable.listeners, } : {}; const destinationVerb = sortable?.isDragging ? props.dropVerb : props.sweepAction === "unsnooze" ? "wake" : props.sweepAction; const dragDestination = destinationVerb !== null ? ( {dropVerbBadge[destinationVerb]} ) : null; const accessibility = resolveSidebarRowAccessibility({ title: thread.title, statusLabel: topStatus?.label ?? null, projectDisplayName: props.projectDisplayName, isActive: props.isActive, }); const title = isRenaming ? ( onCommitRename(threadRef, renamingTitle)} onCancel={onCancelRename} /> ) : ( {thread.title} {isRegeneratingTitle ? ( {thread.title} ) : null} ); const prBadgeShape = supportsMultiplePullRequests ? resolveThreadPullRequestBadge(thread.pullRequests) : null; const openLinkedItems = () => { useRightPanelStore.getState().open(threadRef, "pull-requests"); if (!props.isRouteThread) onThreadActivate(threadRef); }; const prBadge = prBadgeShape?.kind === "stack" || pr || currentLinkedPr ? ( } badge={prBadgeShape} pullRequests={thread.pullRequests} number={pr?.number ?? currentLinkedPr?.number} url={pr?.url ?? currentLinkedPr?.url} status={prStatus} onOpenList={openLinkedItems} onOpenPullRequest={handlePrClick} /> ) : null; const firstIssue = thread.issues?.[0]; const issueCount = thread.issues?.length ?? 0; const issueDetail = useLinkedIssueDetail( thread.environmentId, leaseLiveStatus && issueCount === 1 ? firstIssue : undefined, "sidebar", ); const issueStatus = issueDetail === null ? null : issueStatePresentation(issueDetail.state); const IssueIcon = issueStatus?.Icon ?? IssueGlyph.issue; const issueLabel = issueCount === 1 && firstIssue ? issueStatus ? gt("Issue {key}: {title}, {state}", { key: firstIssue.displayKey, title: firstIssue.title, state: issueStatus.label, }) : gt("Issue {key}: {title}", { key: firstIssue.displayKey, title: firstIssue.title }) : gt("{count, plural, one {{count} linked issue} other {{count} linked issues}}", { count: issueCount, }); const issueBadge = firstIssue ? ( event.stopPropagation()} onClick={(event) => { event.stopPropagation(); openLinkedItems(); }} /> } > {issueCount === 1 ? firstIssue.displayKey : issueCount} event.stopPropagation()} >
{ if (!props.isRouteThread) onThreadActivate(threadRef); }} />
) : null; const terminalStatusIcon = ( ); const draftIndicator = hasUnsentDraft ? ( } > Unsent draft ) : null; const showPin = props.isPinned && (!sortable?.isDragging || (props.dragOverPinned && props.dropVerb === null)); const pinIndicator = showPin ? ( props.pinningSupported && canOperateThread && !sortable?.isDragging ? ( } > Unpin thread ) : ( ) ) : null; const remoteMachineIcon = isRemote && !showsScratchMachine ? ( ) : null; const diff = latestRunDiff(thread); // Only the trailing icons would remain, so the row moves them to the title line instead. const metaLineEmpty = !checkoutThread.branch && !showsScratchMachine && prBadge === null && issueBadge === null && diff === null && runningTerminalIds.length === 0; const metaLine = metaLineEmpty ? null : (
{checkoutThread.branch ? ( <> ) : showsScratchMachine ? ( <> {props.scratchMachineLabel} ) : ( )} {terminalStatusIcon} {prBadge} {issueBadge} {diff ? ( +{formatDiffCount(diff.insertions)}{" "} −{formatDiffCount(diff.deletions)} ) : null} {remoteMachineIcon}
); const titleLineIcons = metaLineEmpty ? ( {remoteMachineIcon} ) : null; if (variant !== "card") { const multiline = variant === "folder-multiline"; const inFolder = variant === "folder" || multiline; return (
  • } > {/* `contents` keeps one-line rows a single flex row. */}
    {inFolder ? null : ( {props.project ? ( ) : null} )} {draftIndicator} {title} {multiline ? titleLineIcons : null} {pinIndicator} {multiline ? null : terminalStatusIcon} {multiline ? null : issueBadge} {isRegeneratingTitle ? ( Regenerating title ) : null} {sortable?.isDragging ? ( dragDestination ) : ( {variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? ( {/* The clock tells a wake time from an age at a glance. */} {props.snoozeWakeLabelText} ) : (inFolder ? isWokeStatus : isWoke) ? ( Woke } /> Dismiss Woke notification ) : inFolder && topStatus ? ( // Folder rows have no status line, so the status takes the time slot. {topStatus.label} ) : ( )} {variantAction === "unsnooze" ? ( !props.snoozeSupported ? null : ( ) ) : !props.settlementSupported ? null : variantAction === "unsettle" ? ( } > Un-settle thread ) : ( } > Settle thread )} {jumpHintLabel ? : null} )} {props.sweepAction !== null ? dragDestination : null}
    {multiline ? metaLine : null}
    {detailsTooltip}
  • ); } return (
  • } >
    {draftIndicator} {props.project ? ( ) : null} {/* Left of the status slot, the pin would slide when hover swaps the label for the wider row controls. */} {pinIndicator} {props.projectDisplayName ? ( {props.projectDisplayName} ) : ( )} {sortable?.isDragging ? ( dragDestination ) : ( {topStatus ? ( isWokeStatus ? ( {topStatus.label} } /> Dismiss Woke notification ) : ( {/* Not a live region: a collapsed sidebar is inert, so BackgroundThreadAnnouncer and the open thread's timeline speak status changes instead. */} {topStatus.label} {status === "preparing" || status === "working" ? ( ) : status === "waiting" ? ( ) : null} ) ) : ( )} {props.settlementSupported || showSnoozeButton || hasUnsentDraft ? ( {hasUnsentDraft ? ( } > Discard draft ) : null} {showSnoozeButton ? ( ) : null} {props.settlementSupported ? ( } > Settle Settle thread ) : null} ) : null} {jumpHintLabel ? : null} )} {props.sweepAction !== null ? dragDestination : null}
    {title} {isRegeneratingTitle ? ( Regenerating title ) : null} {titleLineIcons}
    {metaLine}
    {detailsTooltip}
  • ); }); function latestRunDiff( thread: SidebarThreadSummary, ): { insertions: number; deletions: number } | null { void thread; return null; } // Attached only to the highlighted result, so React calls it each time the // highlight lands on a different row: a new query, late rows replacing the first // result, or arrow keys moving past the scrolled edge. const scrollHighlightedResultIntoView = (node: HTMLLIElement | null) => { node?.scrollIntoView({ block: "nearest" }); }; export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: { isSettled: boolean; thread: SidebarThreadSummary; project: EnvironmentProject | null; projectDisplayName: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; providerEntryByInstanceId: ReadonlyMap; isHighlighted: boolean; isRouteActive: boolean; resultId: string; searchMatch: EnvironmentThreadSearchMatch | null; searchQuery: string; /** The query `searchMatch` was found for, which lags `searchQuery` while a search runs. */ searchMatchQuery?: string; onHighlight: () => void; onSelect: () => void; onFileDropThreads: (threadRef: ScopedThreadRef, files: File[]) => void; }) { const messages = useMessages(); const thread = useThreadShell(scopeThreadRef(props.thread.environmentId, props.thread.id)) ?? props.thread; const accessibility = resolveSidebarRowAccessibility({ title: thread.title, statusLabel: null, projectDisplayName: props.projectDisplayName, isActive: props.isRouteActive, }); const threadRef = scopeThreadRef(thread.environmentId, thread.id); // Results only drag out as chat context; the row keeps its own listbox attributes. const { listeners: dragListeners, setNodeRef: setDragNodeRef } = useDraggable({ id: scopedThreadKey(threadRef), }); const { leaseLiveStatus, rowRef: leaseRowRef } = useSidebarRowSubscriptionLease( props.isHighlighted || props.isRouteActive, ); const isRegeneratingTitle = thread.titleRegeneration != null; const rowRef = (row: HTMLElement | null) => { setDragNodeRef(row); return leaseRowRef(row); }; const gitCwd = thread.worktreePath ?? props.project?.workspaceRoot ?? null; const branchTarget = leaseLiveStatus && (thread.branch != null || thread.worktreePath !== null) && gitCwd !== null ? { environmentId: thread.environmentId, cwd: gitCwd } : null; const gitStatus = useEnvironmentQuery( branchTarget === null ? null : vcsEnvironment.branch({ environmentId: branchTarget.environmentId, input: { cwd: branchTarget.cwd }, }), ); useAtomMount(vcsBranchRevalidation(branchTarget)); const visibleGitStatus = useRetainedValue( JSON.stringify([thread.environmentId, gitCwd]), gitStatus.data, ); const checkoutThread = withoutRemovedCheckout(thread, visibleGitStatus); const branchMismatch = resolveLocalCheckoutBranchMismatch({ effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree", activeWorktreePath: thread.worktreePath, activeThreadBranch: thread.branch, currentGitBranch: visibleGitStatus?.refName ?? null, }); const modelInstanceId = thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId; const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; const showInstanceBadge = providerEntry !== null && shouldShowInstanceBadge(providerEntry, props.providerEntryByInstanceId.values()); const selectedModel = providerEntry?.models.find( (model) => model.slug === thread.modelSelection.model, ); const modelLabel = selectedModel ? getTriggerDisplayModelName(selectedModel, providerEntry?.driverKind) : thread.modelSelection.model; const runningTerminalIds = useThreadRunningTerminalIds({ environmentId: thread.environmentId, threadId: thread.id, }); const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds, messages); const [isFileDragOver, setIsFileDragOver] = useState(false); const onFileDropThreads = props.onFileDropThreads; const fileDropHandlers = makeWorkspaceFileDropHandlers({ setDragActive: (active) => setFileDragActive(setIsFileDragOver, active), addFiles: (files) => { onFileDropThreads(threadRef, files); }, addFolders: () => {}, }); return (
  • { dragListeners?.onPointerDown?.(event); event.preventDefault(); }} onClick={props.onSelect} className={cn( "group/sidebar-row group/v2-row flex min-h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 py-1 text-left text-sm outline-none", props.isHighlighted || props.isRouteActive ? "bg-sidebar-row-active text-sidebar-foreground" : "text-sidebar-muted-foreground/75 hover:bg-sidebar-row-hover hover:text-sidebar-foreground", isFileDragOver && "ring-1 ring-inset ring-primary/70", isFileDragOver && !props.isRouteActive && "bg-sidebar-row-hover", )} /> } > {props.project ? ( ) : null} {thread.title} {isRegeneratingTitle ? ( {thread.title} ) : null} {props.searchMatch ? ( ) : null}
  • ); });