import { DEFAULT_MODEL, defaultInstanceIdForDriver, type EnvironmentId, type MessageId, type ModelSelection, type OrchestrationV2ThreadProjection, type ProjectScript, type ProjectId, type ProviderApprovalDecision, type PreviewAnnotationPayload, ProviderInstanceId, type ServerProvider, type ResolvedKeybindingsConfig, type ScopedThreadRef, type ThreadId, type RunId, type RuntimeRequestId, type KeybindingCommand, ProviderInteractionMode, ProviderDriverKind, RuntimeMode, TerminalOpenInput, } from "@t3tools/contracts"; import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { deriveLatestThreadRun, deriveThreadRuntime, } from "@t3tools/client-runtime/state/thread-execution"; import { resolveThreadProviderSession } from "@t3tools/client-runtime/state/thread-workflows"; import { derivePendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; import { parseScopedThreadKey, scopedThreadKey, scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime/environment"; import { applyClaudePromptEffortPrefix, createModelSelection, resolvePromptInjectedEffort, } from "@t3tools/shared/model"; import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList"; import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts"; import { truncate } from "@t3tools/shared/String"; import { nextTerminalId, resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels"; import { Debouncer } from "@tanstack/react-pacer"; import { useAtomValue } from "@effect/atom-react"; import { lazy, memo, Suspense, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from "react"; import { flushSync } from "react-dom"; import { useNavigate } from "@tanstack/react-router"; import { useShallow } from "zustand/react/shallow"; import { isAtomCommandInterrupted, mapAtomCommandResult, settlePromise, squashAtomCommandFailure, type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/unstable/reactivity"; import { isElectron } from "../env"; import { readLocalApi } from "../localApi"; import { useDiffPanelStore } from "../diffPanelStore"; import { collapseExpandedComposerCursor, parseStandaloneComposerSlashCommand, } from "../composer-logic"; import { derivePendingApprovals, derivePendingUserInputs, derivePhase, deriveTimelineEntriesFromVisibleTurnItems, deriveRevertTurnCountByUserMessageId, deriveActiveWorkStartedAt, deriveActivePlanState, deriveTurnPlans, findLatestProposedPlan, hasActionableProposedPlan, isLatestRunSettled, } from "../session-logic"; import { type LegendListRef } from "@legendapp/list/react"; import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring"; import { buildPendingUserInputAnswers, derivePendingUserInputProgress, setPendingUserInputCustomAnswer, togglePendingUserInputOptionSelection, type PendingUserInputDraftAnswer, } from "../pendingUserInput"; import { useUiStateStore } from "../uiStateStore"; import { buildPlanImplementationThreadTitle, buildPlanImplementationPrompt, resolvePlanFollowUpSubmission, } from "../proposedPlan"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, DEFAULT_THREAD_TERMINAL_ID, MAX_TERMINALS_PER_GROUP, type ChatMessage, type SessionPhase, type Thread, type TurnDiffSummary, } from "../types"; import { useTheme } from "../hooks/useTheme"; import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; import { isCommandPaletteOpen } from "../commandPaletteBus"; import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git"; import { useMediaQuery } from "../hooks/useMediaQuery"; import { useElementWidth } from "../hooks/useElementWidth"; import { usePreviewPanelInlineSize } from "../hooks/usePreviewPanelInlineSize"; import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY, resolveThreadPanelPresentation, } from "../rightPanelLayout"; import { selectActiveRightPanel, selectActiveRightPanelSurface, selectThreadPanelOpen, selectThreadRightPanelState, type RightPanelSurface, useRightPanelStore, } from "../rightPanelStore"; import { isPreviewSupportedInRuntime, setActivePreviewTab, useThreadPreviewState, } from "../previewStateStore"; import { addBrowserSurface } from "./preview/addBrowserSurface"; import { closePreviewSession } from "./preview/closePreviewSession"; import { ThreadPreviewMiniPlayer } from "./preview/ThreadPreviewMiniPlayer"; import { subscribePreviewAction } from "./preview/previewActionBus"; import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic"; import { selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore, } from "../previewMiniPlayerStore"; import { RightPanelTabs } from "./RightPanelTabs"; import { AgentsPanel } from "./AgentsPanel"; import { deriveAgentPanelModel, foldSubagentActivities, } from "@t3tools/client-runtime/state/subagentRuntime"; import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; import { ChevronDownIcon } from "lucide-react"; import { cn, randomHex } from "~/lib/utils"; import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar"; import { stackedThreadToast, toastManager } from "./ui/toast"; import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings"; import { type NewProjectScriptInput } from "./ProjectScriptsControl"; import { buildProjectScript, commandForProjectScript, nextProjectScriptId, projectScriptIdFromCommand, } from "~/projectScripts"; import { newDraftId, newMessageId, newThreadId } from "~/lib/utils"; import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels"; import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances"; import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings"; import { useNowMinute } from "../hooks/useNowMinute"; import { useNewThreadHandler } from "../hooks/useHandleNewThread"; import { resolveAppModelSelectionForInstance } from "../modelSelection"; import { getTerminalFocusOwner } from "../lib/terminalFocus"; import { preventRepeatedTerminalCloseShortcut } from "../lib/terminalCloseShortcut"; import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions"; import { deriveLogicalProjectKeyFromSettings, selectProjectGroupingSettings, } from "../logicalProject"; import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../threadRoutes"; import { type ComposerImageAttachment, type DraftThreadEnvMode, useComposerDraftStore, type DraftId, } from "../composerDraftStore"; import { appendTerminalContextsToPrompt, formatTerminalContextLabel, type TerminalContextDraft, type TerminalContextSelection, } from "../lib/terminalContext"; import { appendElementContextsToPrompt, type ElementContextDraft, formatElementContextLabel, } from "../lib/elementContext"; import { appendPreviewAnnotationPrompt } from "../lib/previewAnnotation"; import { appendReviewCommentsToPrompt, type ReviewCommentContext } from "../reviewCommentContext"; import { environmentCatalog } from "../connection/catalog"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions"; import { projectEnvironment } from "../state/projects"; import { useEnvironmentQuery } from "../state/query"; import { primaryServerAvailableEditorsAtom, primaryServerKeybindingsAtom, primaryServerSettingsAtom, serverEnvironment, } from "../state/server"; import { terminalEnvironment } from "../state/terminal"; import { threadEnvironment, useEnvironmentThread } from "../state/threads"; import { requestOlderThreadTurns, threadHasOlderTurns, } from "@t3tools/client-runtime/state/threads"; import { vcsEnvironment } from "../state/vcs"; import { useEnvironments, usePrimaryEnvironment } from "../state/environments"; import { useProject, useProjects, useThreadProjection, useThreadShell, useThreadRefs, useThreadVisibleTurnItems, waitForThreadShell, } from "../state/entities"; import { environmentShell } from "../state/shell"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; import { DraftHeroHeadline } from "./chat/DraftHeroHeadline"; import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; import { MessagesTimeline } from "./chat/MessagesTimeline"; import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic"; import { ChatHeader } from "./chat/ChatHeader"; import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic"; import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut"; import { PanelLayoutControls, type PanelLayoutControlsProps, RightPanelMaximizeControl, } from "./chat/PanelLayoutControls"; import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { ThreadDetailsPanel, type ThreadDetailsPanelProps } from "./chat/ThreadDetailsPanel"; import { NoActiveThreadState } from "./NoActiveThreadState"; import { resolveEffectiveEnvMode, resolveLocalCheckoutBranchMismatch, shouldShowComposerContextStrip, shouldShowEnvironmentIndicator, } from "./BranchToolbar.logic"; import { getProviderStatusBannerKey, ProviderStatusBanner, shouldShowProviderStatusBanner, } from "./chat/ProviderStatusBanner"; import { dismissThreadErrorBannerForSession, getThreadErrorBannerKey, isThreadErrorBannerDismissedForSession, shouldShowThreadErrorBanner, ThreadErrorBanner, } from "./chat/ThreadErrorBanner"; import { resolveThreadPr } from "./ThreadStatusIndicators"; import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; import { QueuedRunsControl } from "./chat/QueuedRunsControl"; import type { ComposerDispatchMode } from "./chat/composerDispatch"; import { MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, branchMismatchKey, buildExpiredTerminalContextToastCopy, buildLocalDraftThread, buildLoadingThreadFromShell, buildThreadTurnInterruptInput, collectUserMessageBlobPreviewUrls, createLocalDispatchSnapshot, deriveCommittedServerUserMessageIds, deriveComposerSendState, dismissBranchMismatchForSession, hasServerAcknowledgedLocalDispatch, isBranchMismatchDismissedForSession, shouldShowBranchMismatchBanner, getStartedThreadModelChangeBlockReason, LAST_INVOKED_SCRIPT_BY_PROJECT_KEY, LastInvokedScriptByProjectSchema, type LocalDispatchSnapshot, PullRequestDialogState, cloneComposerImageForRetry, deriveLockedProvider, readFileAsDataUrl, reconcileMountedTerminalThreadIds, resolveThreadMetadataUpdateForNextTurn, resolveSendEnvMode, revokeBlobPreviewUrl, revokeUserMessagePreviewUrls, shouldShowComposerContextStrip, waitForStartedServerThread, } from "./ChatView.logic"; import type { ThreadSyncPhase } from "../threadSync"; import { useLocalStorage } from "~/hooks/useLocalStorage"; import { useComposerHandleContext } from "../composerHandleContext"; import { sanitizeThreadErrorMessage } from "~/rpc/transportError"; import { RightPanelSheet } from "./RightPanelSheet"; import { previewEnvironment } from "../state/preview"; import { useAtomCommand } from "../state/use-atom-command"; import { AlertDialog, AlertDialogClose, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogPopup, AlertDialogTitle, } from "./ui/alert-dialog"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ServerUpdateAction, ServerUpdateProgress } from "./ServerUpdateAction"; import { buildVersionMismatchDismissalKey, dismissVersionMismatch, isVersionMismatchDismissed, resolveServerConfigVersionMismatch, resolveServerSelfUpdateCapability, serverUpdateGuidance, } from "../versionSkew"; import { useAssetUrls } from "../assets/assetUrls"; const IMAGE_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]"; const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; const EMPTY_ATTACHMENT_IDS: string[] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; function useDraftHeroLayoutTransition(isDraftHeroState: boolean) { const transitionGroupRef = useRef(null); const composerAnchorRef = useRef(null); const previousStateRef = useRef(isDraftHeroState); const previousComposerRectRef = useRef(null); const animationRef = useRef(null); const attachTransitionGroupRef = (element: HTMLDivElement | null) => { transitionGroupRef.current = element; }; const attachComposerAnchorRef = (element: HTMLDivElement | null) => { composerAnchorRef.current = element; }; const captureComposerRect = () => { previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null; }; useLayoutEffect(() => { const transitionGroup = transitionGroupRef.current; const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null; const stateChanged = previousStateRef.current !== isDraftHeroState; const prefersReducedMotion = typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches; const mobileComposerTransitionActive = typeof document !== "undefined" && document.documentElement.dataset.mobileComposerRouteTransition === "true"; animationRef.current?.cancel(); animationRef.current = null; const previousComposerRect = previousComposerRectRef.current; if ( stateChanged && !prefersReducedMotion && !mobileComposerTransitionActive && transitionGroup && previousComposerRect && nextComposerRect && typeof transitionGroup.animate === "function" ) { const translateX = previousComposerRect.left - nextComposerRect.left; const translateY = previousComposerRect.top - nextComposerRect.top; if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) { const animation = transitionGroup.animate( [ { transform: `translate3d(${translateX}px, ${translateY}px, 0)` }, { transform: "translate3d(0, 0, 0)" }, ], { duration: DRAFT_HERO_TRANSITION_DURATION_MS, easing: DRAFT_HERO_TRANSITION_EASING, }, ); animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID; animationRef.current = animation; void animation.finished .catch(() => undefined) .then(() => { if (animationRef.current !== animation) { return; } animationRef.current = null; }); } } previousStateRef.current = isDraftHeroState; previousComposerRectRef.current = nextComposerRect; }, [isDraftHeroState]); return [attachTransitionGroupRef, attachComposerAnchorRef, captureComposerRect] as const; } const PreviewPanel = lazy(() => import("./preview/PreviewPanel").then((module) => ({ default: module.PreviewPanel })), ); const DiffPanel = lazy(() => import("./DiffPanel")); const FilePreviewPanel = lazy(() => import("./files/FilePreviewPanel")); const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet = new Set(); const TYPE_TO_FOCUS_EDITABLE_SELECTOR = [ "input", "textarea", "select", '[contenteditable="true"]', '[contenteditable="plaintext-only"]', '[role="textbox"]', ].join(","); const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [ "button", "a[href]", "summary", '[role="button"]', '[role="checkbox"]', '[role="menuitem"]', '[role="option"]', '[role="radio"]', '[role="switch"]', '[role="tab"]', ].join(","); const TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR = [ '[data-slot="dialog"]', '[data-slot="menu-popup"]', '[data-slot="select-popup"]', '[data-slot="popover-popup"]', '[data-slot="combobox-popup"]', '[data-slot="autocomplete-popup"]', ].join(","); type EnvironmentUnavailableState = { readonly environmentId: EnvironmentId; readonly label: string; readonly connection: EnvironmentConnectionPresentation; }; type ThreadPlanCatalogEntry = { readonly id: ThreadId; readonly projection: OrchestrationV2ThreadProjection; }; function eventPathContainsSelector(event: Event, selector: string): boolean { const path = event.composedPath(); if (path.length === 0 && event.target) { path.push(event.target); } return path.some((target) => target instanceof Element && target.closest(selector)); } function shouldTypeToFocusComposer(event: KeyboardEvent): boolean { if (event.defaultPrevented || event.isComposing) return false; if (event.metaKey || event.ctrlKey || event.altKey) return false; if (event.key.length !== 1) return false; if (eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR)) return false; if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false; if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false; return true; } function formatOutgoingPrompt(params: { provider: ProviderDriverKind; model: string | null; models: ReadonlyArray; effort: string | null; text: string; }): string { const caps = getProviderModelCapabilities(params.models, params.model, params.provider); const promptEffort = resolvePromptInjectedEffort(caps, params.effort); return applyClaudePromptEffortPrefix(params.text, promptEffort); } const SCRIPT_TERMINAL_COLS = 120; const SCRIPT_TERMINAL_ROWS = 30; type ChatViewProps = | { environmentId: EnvironmentId; threadId: ThreadId; onDiffPanelOpen?: () => void; reserveTitleBarControlInset?: boolean; forceExpandedMobileComposer?: boolean; threadSyncPhase?: ThreadSyncPhase | null; routeKind: "server"; draftId?: never; } | { environmentId: EnvironmentId; threadId: ThreadId; onDiffPanelOpen?: () => void; reserveTitleBarControlInset?: boolean; forceExpandedMobileComposer?: boolean; threadSyncPhase?: never; routeKind: "draft"; draftId: DraftId; }; interface TerminalLaunchContext { threadId: ThreadId; cwd: string; worktreePath: string | null; } type PersistentTerminalLaunchContext = Pick; function useLocalDispatchState(input: { activeThread: Thread | undefined; activeLatestRun: Thread["latestRun"] | null; phase: SessionPhase; activePendingApproval: RuntimeRequestId | null; activePendingUserInput: RuntimeRequestId | null; threadError: string | null | undefined; }) { const [localDispatch, setLocalDispatch] = useState(null); const latestUserMessageId = input.activeThread?.messages.findLast((message) => message.role === "user")?.id ?? null; const resetLocalDispatch = useCallback(() => { setLocalDispatch(null); }, []); const serverAcknowledgedLocalDispatch = useMemo( () => hasServerAcknowledgedLocalDispatch({ localDispatch, phase: input.phase, latestRun: input.activeLatestRun, runtime: input.activeThread?.runtime ?? null, hasPendingApproval: input.activePendingApproval !== null, hasPendingUserInput: input.activePendingUserInput !== null, threadError: input.threadError, }), [ input.activeLatestRun, input.activePendingApproval, input.activePendingUserInput, input.activeThread?.runtime, input.phase, input.threadError, latestUserMessageId, localDispatch, ], ); const activeLocalDispatch = serverAcknowledgedLocalDispatch ? null : localDispatch; const beginLocalDispatch = useCallback( (options?: { preparingWorktree?: boolean }) => { const preparingWorktree = Boolean(options?.preparingWorktree); setLocalDispatch((current) => { const active = serverAcknowledgedLocalDispatch ? null : current; if (active) { return active.preparingWorktree === preparingWorktree ? active : { ...active, preparingWorktree }; } return createLocalDispatchSnapshot(input.activeThread, options); }); }, [input.activeThread, serverAcknowledgedLocalDispatch], ); return { beginLocalDispatch, resetLocalDispatch, localDispatchStartedAt: activeLocalDispatch?.startedAt ?? null, isPreparingWorktree: activeLocalDispatch?.preparingWorktree ?? false, isSendBusy: activeLocalDispatch !== null, }; } /** Same terminal ids (order ignored) — avoids reconcile when only server session ordering differs. */ function terminalIdListsEqual(left: readonly string[], right: readonly string[]): boolean { if (left.length !== right.length) { return false; } if (left.length === 0) { return true; } const sortedLeft = left.toSorted((a, b) => a.localeCompare(b)); const sortedRight = right.toSorted((a, b) => a.localeCompare(b)); for (let index = 0; index < sortedLeft.length; index += 1) { if (sortedLeft[index] !== sortedRight[index]) { return false; } } return true; } /** * Server knows about fewer sessions than the client, but every server id still exists locally. * Typical right after `terminal.open`: known-session list lags; reconciling would drop the new id * and later re-add it as a separate group (no split layout). */ function serverTerminalIdsStrictSubsetOfClient( serverIds: readonly string[], clientIds: readonly string[], ): boolean { if (serverIds.length >= clientIds.length || clientIds.length === 0) { return false; } const clientSet = new Set(clientIds); for (const id of serverIds) { if (!clientSet.has(id)) { return false; } } return true; } interface PersistentThreadTerminalDrawerProps { threadRef: { environmentId: EnvironmentId; threadId: ThreadId }; threadId: ThreadId; visible: boolean; launchContext: PersistentTerminalLaunchContext | null; focusRequestId: number; splitShortcutLabel: string | undefined; splitVerticalShortcutLabel: string | undefined; newShortcutLabel: string | undefined; closeShortcutLabel: string | undefined; keybindings: ResolvedKeybindingsConfig; onAddTerminalContext: (selection: TerminalContextSelection) => void; } const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDrawer({ threadRef, threadId, visible, launchContext, focusRequestId, splitShortcutLabel, splitVerticalShortcutLabel, newShortcutLabel, closeShortcutLabel, keybindings, onAddTerminalContext, }: PersistentThreadTerminalDrawerProps) { const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open"); const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close"); const serverThread = useThreadShell(threadRef); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); const serverThread = useThread(threadRef, { waitForShell: draftThread !== null }); const projectRef = serverThread ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) : draftThread ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) : null; const project = useProject(projectRef); const terminalUiState = useTerminalUiStateStore((state) => selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef), ); const knownTerminalSessions = useKnownTerminalSessions({ environmentId: threadRef.environmentId, threadId, }); const panelSurfaces = useRightPanelStore( (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces, ); const panelTerminalIds = useMemo( () => new Set( panelSurfaces.flatMap((surface) => surface.kind === "terminal" ? surface.terminalIds : [], ), ), [panelSurfaces], ); const drawerTerminalSessions = useMemo( () => knownTerminalSessions.filter((session) => !panelTerminalIds.has(session.target.terminalId)), [knownTerminalSessions, panelTerminalIds], ); const terminalLabelsById = useMemo(() => { const next = new Map(); for (const session of drawerTerminalSessions) { next.set( session.target.terminalId, resolveTerminalSessionLabel(session.target.terminalId, session.state.summary), ); } return next; }, [drawerTerminalSessions]); const terminalLaunchLocationsById = useMemo(() => { const next = new Map< string, { readonly cwd: string; readonly worktreePath: string | null; readonly runtimeEnv: Record; } >(); if (!project) { return next; } for (const session of drawerTerminalSessions) { const summary = session.state.summary; if (!summary) { continue; } const worktreePathForLaunch = launchContext !== null ? launchContext.worktreePath : summary.worktreePath; next.set(session.target.terminalId, { cwd: launchContext?.cwd ?? summary.cwd, worktreePath: worktreePathForLaunch, runtimeEnv: projectScriptRuntimeEnv({ project: { cwd: project.workspaceRoot }, worktreePath: worktreePathForLaunch, }), }); } return next; }, [drawerTerminalSessions, launchContext, project]); const serverOrderedTerminalIds = useMemo( () => drawerTerminalSessions.map((session) => session.target.terminalId), [drawerTerminalSessions], ); // Every client-side id source participates in allocation: the server list // lags fresh opens, and panel terminals are filtered out of the drawer's // sessions — an id collision attaches two viewports to one PTY session. const allocatableTerminalIds = useMemo( () => [ ...new Set([ ...serverOrderedTerminalIds, ...terminalUiState.terminalIds, ...panelTerminalIds, ]), ], [panelTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds], ); const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight); const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal); const storeSplitTerminalVertical = useTerminalUiStateStore( (state) => state.splitTerminalVertical, ); const storeNewTerminal = useTerminalUiStateStore((state) => state.newTerminal); const storeSetActiveTerminal = useTerminalUiStateStore((state) => state.setActiveTerminal); const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal); const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds); useEffect(() => { if (terminalIdListsEqual(serverOrderedTerminalIds, terminalUiState.terminalIds)) { return; } if ( serverTerminalIdsStrictSubsetOfClient(serverOrderedTerminalIds, terminalUiState.terminalIds) ) { return; } reconcileTerminalIds(threadRef, serverOrderedTerminalIds); }, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]); const [localFocusRequestId, setLocalFocusRequestId] = useState(0); const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; const effectiveWorktreePath = useMemo(() => { if (launchContext !== null) { return launchContext.worktreePath; } return worktreePath; }, [launchContext, worktreePath]); const cwd = useMemo( () => launchContext?.cwd ?? (project ? projectScriptCwd({ project: { cwd: project.workspaceRoot }, worktreePath: effectiveWorktreePath, }) : null), [effectiveWorktreePath, launchContext?.cwd, project], ); const runtimeEnv = useMemo( () => project ? projectScriptRuntimeEnv({ project: { cwd: project.workspaceRoot }, worktreePath: effectiveWorktreePath, }) : {}, [effectiveWorktreePath, project], ); const bumpFocusRequestId = useCallback(() => { if (!visible) { return; } setLocalFocusRequestId((value) => value + 1); }, [visible]); const setTerminalHeight = useCallback( (height: number) => { storeSetTerminalHeight(threadRef, height); }, [storeSetTerminalHeight, threadRef], ); const splitTerminal = useCallback(() => { if (!cwd) { return; } const terminalId = nextTerminalId(allocatableTerminalIds); storeSplitTerminal(threadRef, terminalId); bumpFocusRequestId(); void openTerminal({ environmentId: threadRef.environmentId, input: { threadId, terminalId, cwd, ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}), env: runtimeEnv, }, }); }, [ allocatableTerminalIds, bumpFocusRequestId, cwd, effectiveWorktreePath, runtimeEnv, storeSplitTerminal, threadId, threadRef, openTerminal, ]); const splitTerminalVertical = useCallback(() => { if (!cwd) { return; } const terminalId = nextTerminalId(allocatableTerminalIds); storeSplitTerminalVertical(threadRef, terminalId); bumpFocusRequestId(); void openTerminal({ environmentId: threadRef.environmentId, input: { threadId, terminalId, cwd, ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}), env: runtimeEnv, }, }); }, [ allocatableTerminalIds, bumpFocusRequestId, cwd, effectiveWorktreePath, openTerminal, runtimeEnv, storeSplitTerminalVertical, threadId, threadRef, ]); const createNewTerminal = useCallback(() => { if (!cwd) { return; } const terminalId = nextTerminalId(allocatableTerminalIds); storeNewTerminal(threadRef, terminalId); bumpFocusRequestId(); void openTerminal({ environmentId: threadRef.environmentId, input: { threadId, terminalId, cwd, ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}), env: runtimeEnv, }, }); }, [ bumpFocusRequestId, cwd, effectiveWorktreePath, allocatableTerminalIds, runtimeEnv, storeNewTerminal, threadId, threadRef, openTerminal, ]); const activateTerminal = useCallback( (terminalId: string) => { storeSetActiveTerminal(threadRef, terminalId); bumpFocusRequestId(); }, [bumpFocusRequestId, storeSetActiveTerminal, threadRef], ); const closeTerminal = useCallback( (terminalId: string) => { const fallbackExitWrite = () => writeTerminal({ environmentId: threadRef.environmentId, input: { threadId, terminalId, data: "exit\n" }, }); void (async () => { const closeResult = await closeTerminalMutation({ environmentId: threadRef.environmentId, input: { threadId, terminalId, deleteHistory: true, }, }); if (closeResult._tag === "Failure" && !isAtomCommandInterrupted(closeResult)) { await fallbackExitWrite(); } })(); storeCloseTerminal(threadRef, terminalId); bumpFocusRequestId(); }, [ bumpFocusRequestId, storeCloseTerminal, threadId, threadRef, closeTerminalMutation, writeTerminal, ], ); const handleAddTerminalContext = useCallback( (selection: TerminalContextSelection) => { if (!visible) { return; } onAddTerminalContext(selection); }, [onAddTerminalContext, visible], ); if (!project || !terminalUiState.terminalOpen || !cwd) { return null; } return (
); }); interface PersistentThreadTerminalPanelProps { threadRef: ScopedThreadRef; surface: Extract; launchContext: PersistentTerminalLaunchContext | null; focusRequestId: number; keybindings: ResolvedKeybindingsConfig; onAddTerminalContext: (selection: TerminalContextSelection) => void; onSplitTerminal: () => void; onSplitTerminalVertical: () => void; onNewTerminal: () => void; onActiveTerminalChange: (terminalId: string) => void; onCloseTerminal: (terminalId: string) => void; splitShortcutLabel?: string | undefined; splitVerticalShortcutLabel?: string | undefined; newShortcutLabel?: string | undefined; closeShortcutLabel?: string | undefined; } const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPanel({ threadRef, surface, launchContext, focusRequestId, keybindings, onAddTerminalContext, onSplitTerminal, onSplitTerminalVertical, onNewTerminal, onActiveTerminalChange, onCloseTerminal, splitShortcutLabel, splitVerticalShortcutLabel, newShortcutLabel, closeShortcutLabel, }: PersistentThreadTerminalPanelProps) { const serverThread = useThreadShell(threadRef); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); const serverThread = useThread(threadRef, { waitForShell: draftThread !== null }); const projectRef = serverThread ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) : draftThread ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) : null; const project = useProject(projectRef); const knownTerminalSessions = useKnownTerminalSessions({ environmentId: threadRef.environmentId, threadId: threadRef.threadId, }); const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; const activeSummary = knownTerminalSessions.find((session) => session.target.terminalId === surface.activeTerminalId) ?.state.summary ?? null; const worktreePath = launchContext?.worktreePath ?? activeSummary?.worktreePath ?? threadWorktreePath; const cwd = useMemo( () => launchContext?.cwd ?? activeSummary?.cwd ?? (project ? projectScriptCwd({ project: { cwd: project.workspaceRoot }, worktreePath, }) : null), [activeSummary?.cwd, launchContext?.cwd, project, worktreePath], ); const runtimeEnv = useMemo( () => project ? projectScriptRuntimeEnv({ project: { cwd: project.workspaceRoot }, worktreePath, }) : {}, [project, worktreePath], ); const terminalLabelsById = useMemo(() => { const labels = new Map(); for (const terminalId of surface.terminalIds) { const summary = knownTerminalSessions.find((session) => session.target.terminalId === terminalId)?.state .summary ?? null; labels.set(terminalId, resolveTerminalSessionLabel(terminalId, summary)); } return labels; }, [knownTerminalSessions, surface.terminalIds]); const terminalLaunchLocationsById = useMemo(() => { const locations = new Map< string, { readonly cwd: string; readonly worktreePath: string | null; readonly runtimeEnv: Record; } >(); for (const terminalId of surface.terminalIds) { const summary = knownTerminalSessions.find((session) => session.target.terminalId === terminalId)?.state .summary ?? null; const terminalWorktreePath = launchContext?.worktreePath ?? summary?.worktreePath ?? threadWorktreePath; const terminalCwd = launchContext?.cwd ?? summary?.cwd ?? (project ? projectScriptCwd({ project: { cwd: project.workspaceRoot }, worktreePath: terminalWorktreePath, }) : null); if (!terminalCwd || !project) continue; locations.set(terminalId, { cwd: terminalCwd, worktreePath: terminalWorktreePath, runtimeEnv: projectScriptRuntimeEnv({ project: { cwd: project.workspaceRoot }, worktreePath: terminalWorktreePath, }), }); } return locations; }, [ knownTerminalSessions, launchContext?.cwd, launchContext?.worktreePath, project, surface.terminalIds, threadWorktreePath, ]); if (!project || !cwd) return null; return ( undefined} onAddTerminalContext={onAddTerminalContext} terminalLabelsById={terminalLabelsById} terminalLaunchLocationsById={terminalLaunchLocationsById} keybindings={keybindings} /> ); }); // Errors surface through two maps (draft-keyed and thread-keyed) whose entries // can race around promotion, so each write carries its time to let the latest // one win when they collide. type LocalThreadErrorEntry = { readonly message: string | null; readonly at: number; }; function chatActionErrorMessage(error: unknown): string { return error instanceof Error ? error.message : "An error occurred."; } function ChatViewContent(props: ChatViewProps) { const { environmentId, threadId, routeKind, onDiffPanelOpen, reserveTitleBarControlInset = true, forceExpandedMobileComposer = false, } = props; const draftId = routeKind === "draft" ? props.draftId : null; const threadSyncPhase = routeKind === "server" ? (props.threadSyncPhase ?? null) : null; const threadDetailLoading = threadSyncPhase === "loading"; const handleNewThread = useNewThreadHandler(); const routeThreadRef = useMemo( () => scopeThreadRef(environmentId, threadId), [environmentId, threadId], ); const routeThreadKey = useMemo(() => scopedThreadKey(routeThreadRef), [routeThreadRef]); const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false }); const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, { reportFailure: false, }); const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open"); const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write"); const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close"); const createThread = useAtomCommand(threadEnvironment.create, { reportFailure: false }); const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false }); const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { reportFailure: false, }); const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false }); const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, { reportFailure: false, }); const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, { reportFailure: false, }); const startThreadTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false }); const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, { reportFailure: false, }); const respondToThreadApproval = useAtomCommand(threadEnvironment.respondToApproval, { reportFailure: false, }); const respondToThreadUserInput = useAtomCommand(threadEnvironment.respondToUserInput, { reportFailure: false, }); const revertThreadCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, { reportFailure: false, }); const forkThreadFromRun = useAtomCommand(threadEnvironment.forkFromRun, { reportFailure: false, }); const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false }); const closePreview = useAtomCommand(previewEnvironment.close, "preview close"); const { environments } = useEnvironments(); const primaryEnvironment = usePrimaryEnvironment(); const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false }); const environmentById = useMemo( () => new Map(environments.map((environment) => [environment.environmentId, environment])), [environments], ); const composerDraftTarget: ScopedThreadRef | DraftId = routeKind === "server" ? routeThreadRef : props.draftId; const serverThread = useThreadShell(routeKind === "server" ? routeThreadRef : null); const serverThreadProjection = useThreadProjection( routeKind === "server" ? routeThreadRef : null, ); const serverProjection = serverThreadProjection?.projection ?? null; const serverVisibleTurnItems = useThreadVisibleTurnItems( routeKind === "server" ? routeThreadRef : null, ); const committedServerMessageIds = useMemo( () => deriveCommittedServerUserMessageIds(serverVisibleTurnItems), [serverVisibleTurnItems], ); const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); const activeThreadLastVisitedAt = useUiStateStore( (store) => store.threadLastVisitedAtById[routeThreadKey], ); const loadEarlierTurns = useMemo(() => { if (routeKind !== "server" || !threadHasOlderTurns(routeThreadState)) { return null; } return { loading: routeThreadState.page._tag === "Some" && routeThreadState.page.value.loadingOlder, onLoadEarlier: () => { requestOlderThreadTurns(routeThreadRef.environmentId, routeThreadRef.threadId); }, }; }, [routeKind, routeThreadRef, routeThreadState]); const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); const settings = useEnvironmentSettings(environmentId); // New-thread defaults live in the primary environment's settings.json (the // settings UI never writes to remote environments), so read them from the // primary server rather than the thread's environment. const primaryServerSettings = useAtomValue(primaryServerSettingsAtom); const setStickyComposerModelSelection = useComposerDraftStore( (store) => store.setStickyModelSelection, ); const timestampFormat = settings.timestampFormat; const navigate = useNavigate(); const { resolvedTheme } = useTheme(); // Granular store selectors — avoid subscribing to prompt changes. const composerRuntimeMode = useComposerDraftStore( (store) => store.getComposerDraft(composerDraftTarget)?.runtimeMode ?? null, ); const composerInteractionMode = useComposerDraftStore( (store) => store.getComposerDraft(composerDraftTarget)?.interactionMode ?? null, ); const composerActiveProvider = useComposerDraftStore( (store) => store.getComposerDraft(composerDraftTarget)?.activeProvider ?? null, ); const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); const setComposerDraftTerminalContexts = useComposerDraftStore( (store) => store.setTerminalContexts, ); const setComposerDraftElementContexts = useComposerDraftStore( (store) => store.setElementContexts, ); const setComposerDraftPreviewAnnotations = useComposerDraftStore( (store) => store.setPreviewAnnotations, ); const setComposerDraftReviewComments = useComposerDraftStore((store) => store.setReviewComments); const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection); const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode); const setComposerDraftInteractionMode = useComposerDraftStore( (store) => store.setInteractionMode, ); const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent); const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const getDraftSessionByLogicalProjectKey = useComposerDraftStore( (store) => store.getDraftSessionByLogicalProjectKey, ); const getDraftSession = useComposerDraftStore((store) => store.getDraftSession); const setLogicalProjectDraftThreadId = useComposerDraftStore( (store) => store.setLogicalProjectDraftThreadId, ); const promptRef = useRef(""); const composerImagesRef = useRef([]); const composerTerminalContextsRef = useRef([]); const composerElementContextsRef = useRef([]); const localComposerRef = useRef(null); const composerRef = useComposerHandleContext() ?? localComposerRef; const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [expandedImage, setExpandedImage] = useState(null); const [optimisticUserMessages, setOptimisticUserMessages] = useState([]); const optimisticUserMessagesRef = useRef(optimisticUserMessages); optimisticUserMessagesRef.current = optimisticUserMessages; const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState< Record >({}); const [localServerErrorsByThreadKey, setLocalServerErrorsByThreadKey] = useState< Record >({}); const [isConnecting, _setIsConnecting] = useState(false); const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false); const [maximizedRightPanelThreadKey, setMaximizedRightPanelThreadKey] = useState( null, ); const [respondingRequestIds, setRespondingRequestIds] = useState([]); const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState< RuntimeRequestId[] >([]); const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState< Record> >({}); const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] = useState>({}); const shouldUsePlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY); const [workspaceLayoutRef, workspaceLayoutWidth] = useElementWidth(); const previewPanelInlineSize = usePreviewPanelInlineSize(); const threadPanelPopoverAnchorRef = useRef(null); // Tracks whether the user explicitly dismissed the sidebar for the active turn. const planSidebarDismissedForTurnRef = useRef(null); // When set, the thread-change reset effect will open the sidebar instead of closing it. // Used by "Implement in a new thread" to carry the sidebar-open intent across navigation. const planSidebarOpenOnNextThreadRef = useRef(false); const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0); const [pullRequestDialogState, setPullRequestDialogState] = useState(null); const [terminalUiLaunchContext, setTerminalUiLaunchContext] = useState(null); const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState< Record >({}); const [pendingServerThreadEnvMode, setPendingServerThreadEnvMode] = useState(null); const [pendingServerThreadBranch, setPendingServerThreadBranch] = useState(); const [ pendingServerThreadStartFromOriginByThreadId, setPendingServerThreadStartFromOriginByThreadId, ] = useState>({}); const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage( LAST_INVOKED_SCRIPT_BY_PROJECT_KEY, {}, LastInvokedScriptByProjectSchema, ); const legendListRef = useRef(null); const [composerOverlayElement, setComposerOverlayElement] = useState(null); const [composerOverlayHeight, setComposerOverlayHeight] = useState(0); const isAtEndRef = useRef(true); const attachmentPreviewHandoffByMessageIdRef = useRef>({}); const attachmentPreviewPromotionInFlightByMessageIdRef = useRef>({}); const sendInFlightRef = useRef(false); const terminalUiOpenByThreadRef = useRef>({}); useLayoutEffect(() => { if (!composerOverlayElement) return; const updateHeight = () => { const nextHeight = Math.ceil(composerOverlayElement.getBoundingClientRect().height); if (nextHeight <= 0) return; setComposerOverlayHeight((currentHeight) => currentHeight === nextHeight ? currentHeight : nextHeight, ); }; updateHeight(); if (typeof ResizeObserver === "undefined") return; const observer = new ResizeObserver(updateHeight); observer.observe(composerOverlayElement); return () => observer.disconnect(); }, [composerOverlayElement]); const terminalUiState = useTerminalUiStateStore((state) => selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef), ); const openTerminalThreadKeys = useTerminalUiStateStore( useShallow((state) => Object.entries(state.terminalUiStateByThreadKey).flatMap( ([nextThreadKey, nextTerminalUiState]) => nextTerminalUiState.terminalOpen ? [nextThreadKey] : [], ), ), ); const storeSetTerminalOpen = useTerminalUiStateStore((s) => s.setTerminalOpen); const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal); const storeSplitTerminal = useTerminalUiStateStore((s) => s.splitTerminal); const storeSplitTerminalVertical = useTerminalUiStateStore((s) => s.splitTerminalVertical); const storeNewTerminal = useTerminalUiStateStore((s) => s.newTerminal); const storeSetActiveTerminal = useTerminalUiStateStore((s) => s.setActiveTerminal); const storeCloseTerminal = useTerminalUiStateStore((s) => s.closeTerminal); const serverThreadRefs = useThreadRefs(); const serverThreadKeys = useMemo(() => serverThreadRefs.map(scopedThreadKey), [serverThreadRefs]); const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey); const draftThreadKeys = useMemo( () => Object.values(draftThreadsByThreadKey).map((draftThread) => scopedThreadKey(scopeThreadRef(draftThread.environmentId, draftThread.threadId)), ), [draftThreadsByThreadKey], ); const [mountedTerminalThreadKeys, setMountedTerminalThreadKeys] = useState([]); const mountedTerminalThreadRefs = useMemo( () => mountedTerminalThreadKeys.flatMap((mountedThreadKey) => { const mountedThreadRef = parseScopedThreadKey(mountedThreadKey); return mountedThreadRef ? [{ key: mountedThreadKey, threadRef: mountedThreadRef }] : []; }), [mountedTerminalThreadKeys], ); const fallbackDraftProjectRef = draftThread ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) : null; const fallbackDraftProject = useProject(fallbackDraftProjectRef); const localDraftError = activeServerThread ? null : ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null); const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null; // Draft errors are keyed by draftId while server errors are keyed by thread // key, so a pending draft entry must migrate when the server thread loads or // a failed send would silently disappear on promotion. When both keys hold // an entry, the most recent write wins. useEffect(() => { if (!activeServerThread || !draftId) { return; } const pendingDraftEntry = localDraftErrorsByDraftId[draftId]; if (pendingDraftEntry === undefined) { return; } setLocalDraftErrorsByDraftId((existing) => { if (existing[draftId] === undefined) { return existing; } const next = { ...existing }; delete next[draftId]; return next; }); setLocalServerErrorsByThreadKey((existing) => { const currentEntry = existing[routeThreadKey]; if ( currentEntry !== undefined && (currentEntry.at > pendingDraftEntry.at || currentEntry.message === pendingDraftEntry.message) ) { return existing; } return { ...existing, [routeThreadKey]: pendingDraftEntry, }; }); }, [activeServerThread, draftId, localDraftErrorsByDraftId, routeThreadKey]); const localDraftThread = useMemo( () => draftThread ? buildLocalDraftThread( threadId, draftThread, fallbackDraftProject?.defaultModelSelection ?? NO_PROVIDER_MODEL_SELECTION, ) : undefined, [draftThread, fallbackDraftProject?.defaultModelSelection, threadId], ); const isServerThread = routeKind === "server" && serverThread !== null; const activeThread = isServerThread ? serverThread : localDraftThread; const serverLatestRun = useMemo( () => (serverProjection === null ? null : deriveLatestThreadRun(serverProjection)), [serverProjection], ); const serverRuntime = useMemo( () => (serverProjection === null ? null : deriveThreadRuntime(serverProjection)), [serverProjection], ); const activeProviderSession = useMemo( () => (serverProjection === null ? null : resolveThreadProviderSession(serverProjection)), [serverProjection], ); const supportsProviderSwitchingViaHandoff = activeProviderSession?.capabilities.sessions.supportsProviderSwitchingViaHandoff === true; const activeLatestRun = isServerThread ? serverLatestRun : (activeThread?.latestRun ?? null); const activeRuntime = isServerThread ? serverRuntime : (activeThread?.runtime ?? null); const parentSubagentThreadId = activeThread?.lineage.relationshipToParent === "subagent" ? activeThread.lineage.parentThreadId : null; const parentSubagentEnvironmentId = activeThread?.environmentId ?? null; const parentSubagentThreadRef = useMemo(() => { if (parentSubagentEnvironmentId === null || parentSubagentThreadId === null) { return null; } return scopeThreadRef(parentSubagentEnvironmentId, parentSubagentThreadId); }, [parentSubagentEnvironmentId, parentSubagentThreadId]); const parentSubagentThread = useThreadShell(parentSubagentThreadRef); const parentThreadLink = useMemo( () => parentSubagentThreadRef === null ? null : { threadId: parentSubagentThreadRef.threadId, title: parentSubagentThread?.title ?? "Parent thread", }, [parentSubagentThread?.title, parentSubagentThreadRef], ); const threadError = isServerThread ? (localServerError ?? serverRuntime?.lastError ?? null) : localDraftError; // Dismissals can only mask the shown error, never clear it: a server thread // keeps its error in session.lastError, so clearing the local shadow would // just fall through to the persisted one. Mask the current error until a // different error arrives, mirroring the provider status banner. const threadErrorBannerKey = getThreadErrorBannerKey(routeThreadKey, threadError); const visibleThreadError = shouldShowThreadErrorBanner( routeThreadKey, threadError, isThreadErrorBannerDismissedForSession(threadErrorBannerKey), ) ? threadError : null; // Dismissing only mutates the session-scoped mask set, which does not // trigger a render on its own; setThreadError(null) can also bail when the // local shadow is already empty and the banner is driven purely by // session.lastError. Bump a tick so the banner hides immediately. Mirrors // the branch mismatch banner. const [, setThreadErrorBannerDismissTick] = useState(0); const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE; // Plan mode is legacy (Settings → Beta). With the flag off the effective // mode is forced to "default" — even for threads with a stored plan mode — // so nobody is trapped in plan mode while its toggle is hidden. The next // send persists "default" back to the thread. const interactionMode = settings.planModeEnabled ? (composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE) : DEFAULT_INTERACTION_MODE; const isLocalDraftThread = !isServerThread && localDraftThread !== undefined; const canCheckoutPullRequestIntoThread = isLocalDraftThread; const activeThreadId = activeThread?.id ?? null; // Prefer the larger of turn-item-committed ids and projection messages so // env lock does not unlock while turn items lag projection hydration. const activeMessageCount = isServerThread ? Math.max(committedServerMessageIds.size, serverProjection?.messages.length ?? 0) : 0; const runningTerminalIds = useThreadRunningTerminalIds({ environmentId: activeThread?.environmentId ?? null, threadId: activeThreadId, }); const activeThreadKnownSessionsRaw = useKnownTerminalSessions({ environmentId: activeThread?.environmentId ?? null, threadId: activeThreadId, }); const activeThreadKnownSessions = useMemo(() => { if (activeThreadId === null) { return []; } return activeThreadKnownSessionsRaw.filter( (session) => session.target.threadId === activeThreadId, ); }, [activeThreadId, activeThreadKnownSessionsRaw]); const activeServerOrderedTerminalIds = useMemo( () => activeThreadKnownSessions.map((session) => session.target.terminalId), [activeThreadKnownSessions], ); const activeKnownTerminalIds = useMemo( () => [...new Set([...activeServerOrderedTerminalIds, ...terminalUiState.terminalIds])], [activeServerOrderedTerminalIds, terminalUiState.terminalIds], ); const activeTerminalLabelsById = useMemo(() => { const labels = new Map(); for (const session of activeThreadKnownSessions) { labels.set( session.target.terminalId, resolveTerminalSessionLabel(session.target.terminalId, session.state.summary), ); } return labels; }, [activeThreadKnownSessions]); const activeThreadRef = useMemo( () => (activeThread ? scopeThreadRef(activeThread.environmentId, activeThread.id) : null), [activeThread], ); const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null; const [timelineAnchor, setTimelineAnchor] = useState<{ readonly threadKey: string | null; readonly messageId: MessageId | null; }>({ threadKey: activeThreadKey, messageId: null }); if (timelineAnchor.threadKey !== activeThreadKey) { setTimelineAnchor({ threadKey: activeThreadKey, messageId: null }); } const timelineAnchorMessageId = timelineAnchor.messageId; const activeRightPanelKind = useRightPanelStore((state) => selectActiveRightPanel(state.byThreadKey, activeThreadRef), ); const diffOpen = activeRightPanelKind === "diff"; const rightPanelState = useRightPanelStore((state) => selectThreadRightPanelState(state.byThreadKey, activeThreadRef), ); const activeRightPanelSurface = useRightPanelStore((state) => selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef), ); const activeFileSurface = activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null; const activePreviewState = useThreadPreviewState(activeThreadRef); const activePreviewMiniPlayer = usePreviewMiniPlayerStore((state) => selectThreadPreviewMiniPlayer(state.byThreadKey, activeThreadRef), ); const panelTerminalIds = useMemo( () => new Set( rightPanelState.surfaces.flatMap((surface) => surface.kind === "terminal" ? surface.terminalIds : [], ), ), [rightPanelState.surfaces], ); const allocatableActiveTerminalIds = useMemo( () => [...new Set([...activeKnownTerminalIds, ...panelTerminalIds])], [activeKnownTerminalIds, panelTerminalIds], ); const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime(); const rightPanelOpen = rightPanelState.isOpen; const canMaximizeRightPanel = rightPanelOpen && !shouldUseRightPanelSheet; const rightPanelMaximized = canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey; const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet; const threadPanelPresentation = resolveThreadPanelPresentation( workspaceLayoutWidth, inlineRightPanelOwnsTitleBar ? previewPanelInlineSize.width : 0, rightPanelMaximized, ); const threadPanelOpen = useRightPanelStore((state) => selectThreadPanelOpen( state.threadPanelVisibilityByThreadKey, activeThreadRef, threadPanelPresentation, ), ); const inlineThreadPanelOpen = threadPanelOpen && threadPanelPresentation === "inline"; useEffect(() => { if (!activeThreadRef) return; useRightPanelStore .getState() .reconcileBrowserSurfaces(activeThreadRef, Object.keys(activePreviewState.sessions)); }, [activePreviewState.sessions, activeThreadRef]); useEffect(() => { if (!activeThreadRef || !activePreviewMiniPlayer) return; const miniTabStillExists = Boolean(activePreviewState.sessions[activePreviewMiniPlayer.tabId]); const sameTabOpenInPanel = previewPanelOpen && activeRightPanelSurface?.kind === "preview" && activeRightPanelSurface.resourceId === activePreviewMiniPlayer.tabId; if (!miniTabStillExists || sameTabOpenInPanel) { usePreviewMiniPlayerStore.getState().close(activeThreadRef); } }, [ activePreviewMiniPlayer, activePreviewState.sessions, activeRightPanelSurface, activeThreadRef, previewPanelOpen, ]); const existingOpenTerminalThreadKeys = useMemo(() => { const existingThreadKeys = new Set([...serverThreadKeys, ...draftThreadKeys]); return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey)); }, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]); const sourcePlanThreadRef = useMemo(() => { const sourceThreadId = activeLatestRun?.sourcePlanRef?.threadId; if (!activeThread || !sourceThreadId || sourceThreadId === activeThread.id) { return null; } return scopeThreadRef(activeThread.environmentId, sourceThreadId); }, [activeLatestRun?.sourcePlanRef?.threadId, activeThread]); const sourceThreadProjection = useThreadProjection(sourcePlanThreadRef); const threadPlanCatalog = useMemo(() => { if (!activeThread || serverProjection === null) { return []; } const entries: ThreadPlanCatalogEntry[] = [ { id: activeThread.id, projection: serverProjection }, ]; if (sourcePlanThreadRef && sourceThreadProjection !== null) { entries.push({ id: sourcePlanThreadRef.threadId, projection: sourceThreadProjection.projection, }); } return entries; }, [activeThread, serverProjection, sourcePlanThreadRef, sourceThreadProjection]); useEffect(() => { setMountedTerminalThreadKeys((currentThreadIds) => { const nextThreadIds = reconcileMountedTerminalThreadIds({ currentThreadIds, openThreadIds: existingOpenTerminalThreadKeys, activeThreadId: activeThreadKey, activeThreadTerminalOpen: Boolean(activeThreadKey && terminalUiState.terminalOpen), maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, }); return currentThreadIds.length === nextThreadIds.length && currentThreadIds.every((nextThreadId, index) => nextThreadId === nextThreadIds[index]) ? currentThreadIds : nextThreadIds; }); }, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]); const latestRunSettled = isLatestRunSettled(activeLatestRun, activeRuntime); const activeProjectRef = activeThread ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) : null; const activeProject = useProject(activeProjectRef); const handleNewThreadInActiveProject = useCallback(() => { startNewThreadForProject(activeProjectRef, handleNewThread); }, [activeProjectRef, handleNewThread]); const activeEnvironmentShell = useEnvironmentQuery( activeThread ? environmentShell.stateAtom(activeThread.environmentId) : null, ); const activeEnvironmentBootstrapComplete = activeEnvironmentShell.data?.snapshot._tag === "Some"; const activeProjectKey = activeProject ? `${activeProject.environmentId}:${activeProject.workspaceRoot}` : null; const [pendingFileSurfaceIdsByProject, setPendingFileSurfaceIdsByProject] = useState< ReadonlyMap> >(() => new Map()); const pendingFileSurfaceIds = activeProjectKey ? (pendingFileSurfaceIdsByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS) : EMPTY_PENDING_FILE_SURFACE_IDS; const handleFilePendingChange = useCallback( (relativePath: string, pending: boolean) => { if (!activeProjectKey) return; setPendingFileSurfaceIdsByProject((currentByProject) => { const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS; const surfaceId = `file:${relativePath}`; if (current.has(surfaceId) === pending) return currentByProject; const next = new Set(current); if (pending) next.add(surfaceId); else next.delete(surfaceId); const nextByProject = new Map(currentByProject); if (next.size === 0) nextByProject.delete(activeProjectKey); else nextByProject.set(activeProjectKey, next); return nextByProject; }); }, [activeProjectKey], ); const configuredPreviewUrls = useMemo( () => getConfiguredPreviewUrls(activeProject?.scripts), [activeProject?.scripts], ); useEffect(() => { if (!activeThreadRef || !activeEnvironmentBootstrapComplete) return; useRightPanelStore.getState().reconcileFileSurfaces(activeThreadRef, activeProject !== null); }, [activeEnvironmentBootstrapComplete, activeProject, activeThreadRef]); // Compute the list of environments this logical project spans, used to // drive the environment picker in BranchToolbar. const allProjects = useProjects(); const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null; const activeEnvironment = activeThread == null ? null : (environmentById.get(activeThread.environmentId) ?? null); const activeEnvironmentConnectionPhase = activeEnvironment?.connection.phase ?? "available"; const activeEnvironmentUnavailable = activeEnvironment !== null && activeEnvironmentConnectionPhase !== "connected"; const activeEnvironmentUnavailableLabel = activeEnvironment?.label ?? null; const activeEnvironmentUnavailableState = useMemo(() => { if (!activeEnvironmentUnavailable || !activeEnvironmentUnavailableLabel || !activeEnvironment) { return null; } return { environmentId: activeEnvironment.environmentId, label: activeEnvironmentUnavailableLabel, connection: activeEnvironment.connection, }; }, [activeEnvironment, activeEnvironmentUnavailable, activeEnvironmentUnavailableLabel]); const handleReconnectActiveEnvironment = useCallback( async (environmentId: EnvironmentId) => { const result = await retryEnvironment(environmentId); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); toastManager.add( stackedThreadToast({ type: "error", title: "Could not reconnect environment", description: error instanceof Error ? error.message : "Failed to reconnect.", }), ); } }, [retryEnvironment], ); const projectGroupingSettings = selectProjectGroupingSettings(settings); const logicalProjectEnvironments = useMemo(() => { if (!activeProject) return []; const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings); const memberProjects = allProjects.filter( (p) => deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) === logicalKey, ); const seen = new Set(); const envs: Array<{ environmentId: EnvironmentId; projectId: ProjectId; label: string; isPrimary: boolean; }> = []; for (const p of memberProjects) { if (seen.has(p.environmentId)) continue; seen.add(p.environmentId); const isPrimary = p.environmentId === primaryEnvironmentId; const label = environmentById.get(p.environmentId)?.label ?? p.environmentId; envs.push({ environmentId: p.environmentId, projectId: p.id, label, isPrimary, }); } // Sort: primary first, then alphabetical envs.sort((a, b) => { if (a.isPrimary !== b.isPrimary) return a.isPrimary ? -1 : 1; return a.label.localeCompare(b.label); }); return envs; }, [activeProject, allProjects, projectGroupingSettings, primaryEnvironmentId, environmentById]); const openPullRequestDialog = useCallback( (reference?: string) => { if (!canCheckoutPullRequestIntoThread) { return; } setPullRequestDialogState({ initialReference: reference ?? null, key: Date.now(), }); }, [canCheckoutPullRequestIntoThread], ); const closePullRequestDialog = useCallback(() => { setPullRequestDialogState(null); }, []); const openOrReuseProjectDraftThread = useCallback( async (input: { branch: string; worktreePath: string | null; envMode: DraftThreadEnvMode }) => { if (!activeProject) { throw new Error("No active project is available for this pull request."); } const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id); const logicalProjectKey = deriveLogicalProjectKeyFromSettings( activeProject, projectGroupingSettings, ); const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey); if (storedDraftSession) { setDraftThreadContext(storedDraftSession.draftId, input); setLogicalProjectDraftThreadId( logicalProjectKey, activeProjectRef, storedDraftSession.draftId, { threadId: storedDraftSession.threadId, ...input, }, ); if (routeKind !== "draft" || draftId !== storedDraftSession.draftId) { await navigate({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(storedDraftSession.draftId), }); } return storedDraftSession.threadId; } const activeDraftSession = routeKind === "draft" && draftId ? getDraftSession(draftId) : null; if ( !isServerThread && activeDraftSession?.logicalProjectKey === logicalProjectKey && draftId ) { setDraftThreadContext(draftId, input); setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, draftId, { threadId: activeDraftSession.threadId, createdAt: activeDraftSession.createdAt, runtimeMode: activeDraftSession.runtimeMode, interactionMode: activeDraftSession.interactionMode, ...input, }); return activeDraftSession.threadId; } const nextDraftId = newDraftId(); const nextThreadId = newThreadId(); setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, nextDraftId, { threadId: nextThreadId, createdAt: new Date().toISOString(), runtimeMode: DEFAULT_RUNTIME_MODE, interactionMode: DEFAULT_INTERACTION_MODE, ...input, }); await navigate({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(nextDraftId), }); return nextThreadId; }, [ activeProject, draftId, getDraftSession, getDraftSessionByLogicalProjectKey, isServerThread, navigate, projectGroupingSettings, routeKind, setDraftThreadContext, setLogicalProjectDraftThreadId, ], ); const handlePreparedPullRequestThread = useCallback( async (input: { branch: string; worktreePath: string | null }) => { await openOrReuseProjectDraftThread({ branch: input.branch, worktreePath: input.worktreePath, envMode: input.worktreePath ? "worktree" : "local", }); }, [openOrReuseProjectDraftThread], ); const selectedProviderByThreadId = composerActiveProvider ?? null; const threadProvider = activeThread?.modelSelection.instanceId ?? activeProject?.defaultModelSelection?.instanceId ?? null; const lockedProvider = deriveLockedProvider({ thread: activeThread, selectedProvider: selectedProviderByThreadId, threadProvider, }); const modelPickerLockedProvider = supportsProviderSwitchingViaHandoff ? null : lockedProvider; // Once a thread selects an environment, never substitute the primary // environment's config while the selected environment is still loading. const serverConfig = activeThread ? (activeEnvironment?.serverConfig ?? null) : (primaryEnvironment?.serverConfig ?? null); const versionMismatch = resolveServerConfigVersionMismatch(serverConfig); const versionMismatchDismissKey = versionMismatch && activeThread ? buildVersionMismatchDismissalKey(activeThread.environmentId, versionMismatch) : null; const [dismissedVersionMismatchKey, setDismissedVersionMismatchKey] = useState( null, ); const versionMismatchDismissed = versionMismatchDismissKey === dismissedVersionMismatchKey || isVersionMismatchDismissed(versionMismatchDismissKey); const showVersionMismatchBanner = versionMismatch !== null && versionMismatchDismissKey !== null && !versionMismatchDismissed; const hasMultipleRegisteredEnvironments = environments.length > 1; const versionMismatchServerLabel = hasMultipleRegisteredEnvironments && activeThread ? `${environmentById.get(activeThread.environmentId)?.label ?? serverConfig?.environment.label ?? activeThread.environmentId} server` : "server"; const reconnectActiveEnvironment = useCallback(() => { if (!activeEnvironmentUnavailableState) return; void handleReconnectActiveEnvironment(activeEnvironmentUnavailableState.environmentId); }, [activeEnvironmentUnavailableState, handleReconnectActiveEnvironment]); const openConnectionSettings = useCallback(() => { void navigate({ to: "/settings/connections" }); }, [navigate]); const handleDismissVersionMismatch = useCallback(() => { if (!versionMismatchDismissKey) return; dismissVersionMismatch(versionMismatchDismissKey); setDismissedVersionMismatchKey(versionMismatchDismissKey); }, [setDismissedVersionMismatchKey, versionMismatchDismissKey]); const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; const unlockedSelectedProvider = resolveSelectableProvider( providerStatuses, selectedProviderByThreadId ?? threadProvider, ); const selectedProvider: ProviderDriverKind = modelPickerLockedProvider ?? unlockedSelectedProvider; const phase = derivePhase(activeRuntime); const pendingRequests = useMemo( () => serverProjection === null ? { approvals: [], userInputs: [] } : derivePendingThreadRequests(serverProjection), [serverProjection], ); const pendingApprovals = useMemo( () => derivePendingApprovals(pendingRequests.approvals), [pendingRequests.approvals], ); const pendingUserInputs = useMemo( () => derivePendingUserInputs(pendingRequests.userInputs), [pendingRequests.userInputs], ); const activePendingUserInput = pendingUserInputs[0] ?? null; const activePendingDraftAnswers = useMemo( () => activePendingUserInput ? (pendingUserInputAnswersByRequestId[activePendingUserInput.requestId] ?? EMPTY_PENDING_USER_INPUT_ANSWERS) : EMPTY_PENDING_USER_INPUT_ANSWERS, [activePendingUserInput, pendingUserInputAnswersByRequestId], ); const activePendingQuestionIndex = activePendingUserInput ? (pendingUserInputQuestionIndexByRequestId[activePendingUserInput.requestId] ?? 0) : 0; const activePendingProgress = useMemo( () => activePendingUserInput ? derivePendingUserInputProgress( activePendingUserInput.questions, activePendingDraftAnswers, activePendingQuestionIndex, ) : null, [activePendingDraftAnswers, activePendingQuestionIndex, activePendingUserInput], ); const activePendingResolvedAnswers = useMemo( () => activePendingUserInput ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers) : null, [activePendingDraftAnswers, activePendingUserInput], ); const activePendingIsResponding = activePendingUserInput ? activePendingUserInput.responseCapability !== "live" || respondingUserInputRequestIds.includes(activePendingUserInput.requestId) : false; const activeProposedPlan = useMemo(() => { if (!latestRunSettled) { return null; } return findLatestProposedPlan(serverProjection, activeLatestRun?.runId ?? null); }, [activeLatestRun?.runId, latestRunSettled, serverProjection]); const sidebarProposedPlan = useMemo( () => findSidebarProposedPlan({ threads: threadPlanCatalog, latestRun: activeLatestRun, latestRunSettled, threadId: activeThread?.id ?? null, }), [activeLatestRun, activeThread?.id, latestRunSettled, threadPlanCatalog], ); const activePlan = useMemo( () => deriveActivePlanState(serverProjection, activeLatestRun?.runId ?? undefined), [activeLatestRun?.runId, serverProjection], ); // Current step for the in-chat working row: only for the running turn's own // plan (deriveActivePlanState falls back to older turns' plans, which must // not label fresh work). Falls back to the first pending step so an // all-pending freshly written plan labels the row, matching the chip and // the server's planProgress. const workingStepLabel = useMemo(() => { if (!activePlan || activePlan.turnId !== (activeLatestTurn?.turnId ?? null)) { return null; } return ( activePlan.steps.find((step) => step.status === "inProgress")?.step ?? activePlan.steps.find((step) => step.status === "pending")?.step ?? null ); }, [activeLatestTurn?.turnId, activePlan]); const showPlanFollowUpPrompt = pendingUserInputs.length === 0 && interactionMode === "plan" && latestRunSettled && hasActionableProposedPlan(activeProposedPlan); const activePendingApproval = pendingApprovals[0] ?? null; const { beginLocalDispatch, resetLocalDispatch, localDispatchStartedAt, isPreparingWorktree, isSendBusy, } = useLocalDispatchState({ activeThread, activeLatestRun, phase, activePendingApproval: activePendingApproval?.requestId ?? null, activePendingUserInput: activePendingUserInput?.requestId ?? null, threadError, }); const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; const activeWorkStartedAt = deriveActiveWorkStartedAt( activeLatestRun, activeRuntime, localDispatchStartedAt, ); useEffect(() => { attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId; }, [attachmentPreviewHandoffByMessageId]); const clearAttachmentPreviewHandoff = useCallback( (messageId: MessageId, previewUrls?: ReadonlyArray) => { delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; const currentPreviewUrls = previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? []; setAttachmentPreviewHandoffByMessageId((existing) => { if (!(messageId in existing)) { return existing; } const next = { ...existing }; delete next[messageId]; attachmentPreviewHandoffByMessageIdRef.current = next; return next; }); for (const previewUrl of currentPreviewUrls) { revokeBlobPreviewUrl(previewUrl); } }, [], ); const clearAttachmentPreviewHandoffs = useCallback(() => { attachmentPreviewPromotionInFlightByMessageIdRef.current = {}; for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) { for (const previewUrl of previewUrls) { revokeBlobPreviewUrl(previewUrl); } } attachmentPreviewHandoffByMessageIdRef.current = {}; setAttachmentPreviewHandoffByMessageId({}); }, []); useEffect(() => { return () => { clearAttachmentPreviewHandoffs(); for (const message of optimisticUserMessagesRef.current) { revokeUserMessagePreviewUrls(message); } }; }, [clearAttachmentPreviewHandoffs]); const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => { if (previewUrls.length === 0) return; const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? []; const nextPreviewUrlSet = new Set(previewUrls); for (const previewUrl of previousPreviewUrls) { if (!nextPreviewUrlSet.has(previewUrl)) { revokeBlobPreviewUrl(previewUrl); } } setAttachmentPreviewHandoffByMessageId((existing) => { const next = { ...existing, [messageId]: previewUrls, }; attachmentPreviewHandoffByMessageIdRef.current = next; return next; }); }, []); const committedServerAttachmentIds = useMemo(() => { const attachmentIds = new Set(); for (const row of serverVisibleTurnItems) { if (row.item.type !== "user_message") continue; for (const attachment of row.item.attachments) { attachmentIds.add(attachment.id); } } return [...attachmentIds]; }, [serverVisibleTurnItems]); const serverAttachmentIds = isServerThread ? committedServerAttachmentIds : EMPTY_ATTACHMENT_IDS; const serverAttachmentResources = useMemo( () => serverAttachmentIds.map((attachmentId) => ({ _tag: "attachment" as const, attachmentId, })), [serverAttachmentIds], ); const serverAttachmentUrls = useAssetUrls(environmentId, serverAttachmentResources); const serverAttachmentUrlById = useMemo( () => new Map( serverAttachmentIds.flatMap((attachmentId, index) => { const url = serverAttachmentUrls[index]; return url ? [[attachmentId, url] as const] : []; }), ), [serverAttachmentIds, serverAttachmentUrls], ); useEffect(() => { if (typeof Image === "undefined" || serverVisibleTurnItems.length === 0) { return; } const cleanups: Array<() => void> = []; const userMessagesById = new Map( serverVisibleTurnItems.flatMap((row) => row.item.type === "user_message" ? [[String(row.item.messageId), row.item] as const] : [], ), ); for (const [messageId, handoffPreviewUrls] of Object.entries( attachmentPreviewHandoffByMessageId, )) { if (attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]) { continue; } const serverMessage = userMessagesById.get(messageId); if (serverMessage === undefined || serverMessage.attachments.length === 0) { continue; } const serverPreviewUrls = serverMessage.attachments.flatMap((attachment) => attachment.type === "image" ? [serverAttachmentUrlById.get(attachment.id)].filter( (previewUrl): previewUrl is string => previewUrl !== undefined, ) : [], ); if ( serverPreviewUrls.length === 0 || serverPreviewUrls.length !== handoffPreviewUrls.length || serverPreviewUrls.some((previewUrl) => previewUrl.startsWith("blob:")) ) { continue; } attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId] = true; let cancelled = false; const imageInstances: HTMLImageElement[] = []; const preloadServerPreviews = Promise.all( serverPreviewUrls.map( (previewUrl) => new Promise((resolve, reject) => { const image = new Image(); imageInstances.push(image); const handleLoad = () => resolve(); const handleError = () => reject(new Error(`Failed to load server preview for ${messageId}.`)); image.addEventListener("load", handleLoad, { once: true }); image.addEventListener("error", handleError, { once: true }); image.src = previewUrl; }), ), ); void preloadServerPreviews .then(() => { if (cancelled) { return; } clearAttachmentPreviewHandoff(messageId as MessageId, handoffPreviewUrls); }) .catch(() => { if (!cancelled) { delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; } }); cleanups.push(() => { cancelled = true; delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; for (const image of imageInstances) { image.src = ""; } }); } return () => { for (const cleanup of cleanups) { cleanup(); } }; }, [ attachmentPreviewHandoffByMessageId, clearAttachmentPreviewHandoff, serverAttachmentUrlById, serverVisibleTurnItems, ]); const timelineAttachmentUrlById = useMemo(() => { const urls = new Map(serverAttachmentUrlById); for (const row of serverVisibleTurnItems) { if (row.item.type !== "user_message") continue; const handoffUrls = attachmentPreviewHandoffByMessageId[row.item.messageId]; if (handoffUrls === undefined) continue; let imageIndex = 0; for (const attachment of row.item.attachments) { if (attachment.type !== "image") continue; const handoffUrl = handoffUrls[imageIndex]; imageIndex += 1; if (handoffUrl !== undefined) urls.set(attachment.id, handoffUrl); } } return urls; }, [attachmentPreviewHandoffByMessageId, serverAttachmentUrlById, serverVisibleTurnItems]); const serverTimelineEntries = useMemo( () => deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems: serverVisibleTurnItems, optimisticMessages: optimisticUserMessages, attachmentUrlById: timelineAttachmentUrlById, ...(serverProjection === null ? {} : { attempts: serverProjection.attempts, nodes: serverProjection.nodes, }), }), [optimisticUserMessages, serverVisibleTurnItems, serverProjection, timelineAttachmentUrlById], ); const draftTimelineEntries = useMemo( () => optimisticUserMessages.map( (message) => ({ id: message.id, kind: "message", createdAt: message.createdAt, message, }) as const, ), [optimisticUserMessages], ); const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries; const { turnDiffSummaries } = useTurnDiffSummaries(serverProjection); const turnDiffSummaryByAssistantMessageId = useMemo(() => { const byMessageId = new Map(); for (const summary of turnDiffSummaries) { if (!summary.assistantMessageId) continue; byMessageId.set(summary.assistantMessageId, summary); } return byMessageId; }, [turnDiffSummaries]); const revertTurnCountByUserMessageId = useMemo( () => deriveRevertTurnCountByUserMessageId({ timelineEntries, checkpoints: turnDiffSummaries, }), [timelineEntries, turnDiffSummaries], ); const gitCwd = activeProject ? projectScriptCwd({ project: { cwd: activeProject.workspaceRoot }, worktreePath: activeThread?.worktreePath ?? null, }) : null; const gitStatusCwd = activeThread?.worktreePath ?? gitCwd; const gitStatusQuery = useEnvironmentQuery( gitStatusCwd === null ? null : vcsEnvironment.status({ environmentId, input: { cwd: gitStatusCwd }, }), ); const keybindings = useAtomValue(primaryServerKeybindingsAtom); const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom); const showOpenInPicker = shouldShowOpenInPicker({ activeProjectName: activeProject?.title, activeThreadEnvironmentId: activeThread?.environmentId ?? environmentId, primaryEnvironmentId, }); useOpenFavoriteEditorShortcut({ enabled: showOpenInPicker, environmentId: activeThread?.environmentId ?? environmentId, keybindings, availableEditors, openInCwd: gitCwd, }); // Prefer an instance-id match so a custom Codex instance (e.g. // `codex_personal`) surfaces its own status/message in the banner rather // than the default Codex's. Falls back to first-match-by-kind when no // saved instance id is available or the instance no longer exists. const selectedProviderInstanceId = providerStatuses.find((status) => status.instanceId === selectedProviderByThreadId) ?.instanceId ?? null; const activeProviderInstanceId = selectedProviderInstanceId ?? activeRuntime?.providerInstanceId ?? activeThread?.modelSelection.instanceId ?? activeProject?.defaultModelSelection?.instanceId ?? null; const activeProviderStatus = useMemo(() => { if (activeProviderInstanceId) { return ( providerStatuses.find((status) => status.instanceId === activeProviderInstanceId) ?? null ); } const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider); return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null; }, [activeProviderInstanceId, providerStatuses, selectedProvider]); const providerStatusBannerKey = getProviderStatusBannerKey(activeProviderStatus); const [dismissedProviderStatusBannerKey, setDismissedProviderStatusBannerKey] = useState< string | null >(null); useEffect(() => { if (providerStatusBannerKey === null && dismissedProviderStatusBannerKey !== null) { setDismissedProviderStatusBannerKey(null); } }, [dismissedProviderStatusBannerKey, providerStatusBannerKey]); const visibleProviderStatus = shouldShowProviderStatusBanner( activeProviderStatus, dismissedProviderStatusBannerKey, ) ? activeProviderStatus : null; const hasTimelineTopBanner = Boolean(visibleThreadError) || visibleProviderStatus !== null; const activeProjectCwd = activeProject?.workspaceRoot ?? null; const activeThreadWorktreePath = activeThread?.worktreePath ?? null; const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined; const activeTerminalLaunchContext = terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null; // Default true while loading to avoid toolbar flicker. const isGitRepo = gitStatusQuery.data?.isRepo ?? true; const showComposerContextStrip = shouldShowComposerContextStrip({ routeKind, isGitRepo, hasActiveProject: activeProject !== null, }); const initialDiffPanelGitScope = gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch"; const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending"; const terminalShortcutLabelOptions = useMemo( () => ({ context: { terminalFocus: true, terminalOpen: Boolean(terminalUiState.terminalOpen), }, }), [terminalUiState.terminalOpen], ); const splitTerminalShortcutLabel = useMemo( () => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions), [keybindings, terminalShortcutLabelOptions], ); const splitTerminalVerticalShortcutLabel = useMemo( () => shortcutLabelForCommand(keybindings, "terminal.splitVertical", terminalShortcutLabelOptions), [keybindings, terminalShortcutLabelOptions], ); const newTerminalShortcutLabel = useMemo( () => shortcutLabelForCommand(keybindings, "terminal.new", terminalShortcutLabelOptions), [keybindings, terminalShortcutLabelOptions], ); const closeTerminalShortcutLabel = useMemo( () => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions), [keybindings, terminalShortcutLabelOptions], ); const onToggleDiff = useCallback(() => { if (!isServerThread) { return; } if (!diffOpen) { onDiffPanelOpen?.(); } if (activeThreadRef) { useRightPanelStore.getState().toggle(activeThreadRef, "diff"); } }, [activeThreadRef, diffOpen, isServerThread, onDiffPanelOpen]); const envLocked = Boolean(activeThread && (activeMessageCount > 0 || activeRuntime !== null)); // Handle environment change for draft threads. When the user picks a // different environment we update the draft context to point at the physical // project in that environment while keeping the same logical project. const onEnvironmentChange = useCallback( (nextEnvironmentId: EnvironmentId) => { if (envLocked || !draftId) return; const target = logicalProjectEnvironments.find( (env) => env.environmentId === nextEnvironmentId, ); if (!target) return; setDraftThreadContext(draftId, { projectRef: scopeProjectRef(target.environmentId, target.projectId), }); }, [draftId, envLocked, logicalProjectEnvironments, setDraftThreadContext], ); const activeTerminalGroup = terminalUiState.terminalGroups.find( (group) => group.id === terminalUiState.activeTerminalGroupId, ) ?? terminalUiState.terminalGroups.find((group) => group.terminalIds.includes(terminalUiState.activeTerminalId), ) ?? null; const hasReachedSplitLimit = (activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP; const setThreadError = useCallback( (targetThreadId: ThreadId | null, error: string | null) => { if (!targetThreadId) return; const nextError = sanitizeThreadErrorMessage(error); const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() }; if ( shouldWriteThreadErrorToCurrentServerThread({ activeServerThread, routeThreadRef, targetThreadId, }) ) { setLocalServerErrorsByThreadKey((existing) => { if ((existing[routeThreadKey]?.message ?? null) === nextError) { return existing; } return { ...existing, [routeThreadKey]: nextEntry, }; }); return; } const localDraftErrorKey = draftId ?? targetThreadId; setLocalDraftErrorsByDraftId((existing) => { if ((existing[localDraftErrorKey]?.message ?? null) === nextError) { return existing; } return { ...existing, [localDraftErrorKey]: nextEntry, }; }); }, [activeServerThread, draftId, routeThreadKey, routeThreadRef], ); const focusComposer = useCallback(() => { composerRef.current?.focusAtEnd(); }, [composerRef]); const scheduleComposerFocus = useCallback(() => { window.requestAnimationFrame(() => { focusComposer(); }); }, [focusComposer]); const addTerminalContextToDraft = useCallback( (selection: TerminalContextSelection) => { composerRef.current?.addTerminalContext(selection); }, [composerRef], ); const setTerminalOpen = useCallback( (open: boolean) => { if (!activeThreadRef) return; storeSetTerminalOpen(activeThreadRef, open); }, [activeThreadRef, storeSetTerminalOpen], ); const toggleTerminalVisibility = useCallback(() => { if (!activeThreadRef) return; const nextOpen = !terminalUiState.terminalOpen; if (nextOpen && terminalUiState.terminalIds.length === 0) { if (!activeThreadId || !activeProject) { return; } const cwdForOpen = gitCwd ?? activeProject.workspaceRoot; if (!cwdForOpen) { return; } const terminalId = nextTerminalId(allocatableActiveTerminalIds); storeEnsureTerminal(activeThreadRef, terminalId, { open: true }); void openTerminal({ environmentId, input: { threadId: activeThreadId, terminalId, cwd: cwdForOpen, ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), env: projectScriptRuntimeEnv({ project: { cwd: activeProject.workspaceRoot }, worktreePath: activeThreadWorktreePath, }), }, }); return; } setTerminalOpen(nextOpen); }, [ activeProject, activeThreadId, activeThreadRef, activeThreadWorktreePath, allocatableActiveTerminalIds, environmentId, gitCwd, openTerminal, setTerminalOpen, storeEnsureTerminal, terminalUiState.terminalIds.length, terminalUiState.terminalOpen, ]); const splitTerminal = useCallback( (direction: "horizontal" | "vertical" = "horizontal") => { if (!activeThreadRef || hasReachedSplitLimit || !activeThreadId || !activeProject) { return; } const cwdForOpen = gitCwd ?? activeProject.workspaceRoot; if (!cwdForOpen) { return; } const terminalId = nextTerminalId(allocatableActiveTerminalIds); if (direction === "vertical") { storeSplitTerminalVertical(activeThreadRef, terminalId); } else { storeSplitTerminal(activeThreadRef, terminalId); } setTerminalFocusRequestId((value) => value + 1); void openTerminal({ environmentId, input: { threadId: activeThreadId, terminalId, cwd: cwdForOpen, ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), env: projectScriptRuntimeEnv({ project: { cwd: activeProject.workspaceRoot }, worktreePath: activeThreadWorktreePath, }), }, }); }, [ activeProject, activeThreadId, allocatableActiveTerminalIds, activeThreadRef, openTerminal, activeThreadWorktreePath, environmentId, gitCwd, hasReachedSplitLimit, storeSplitTerminal, storeSplitTerminalVertical, ], ); const createNewTerminal = useCallback(() => { if (!activeThreadRef || !activeThreadId || !activeProject) { return; } const cwdForOpen = gitCwd ?? activeProject.workspaceRoot; if (!cwdForOpen) { return; } const terminalId = nextTerminalId(allocatableActiveTerminalIds); storeNewTerminal(activeThreadRef, terminalId); setTerminalFocusRequestId((value) => value + 1); void openTerminal({ environmentId, input: { threadId: activeThreadId, terminalId, cwd: cwdForOpen, ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), env: projectScriptRuntimeEnv({ project: { cwd: activeProject.workspaceRoot }, worktreePath: activeThreadWorktreePath, }), }, }); }, [ activeProject, activeThreadId, allocatableActiveTerminalIds, activeThreadRef, openTerminal, activeThreadWorktreePath, environmentId, gitCwd, storeNewTerminal, ]); const closeTerminal = useCallback( (terminalId: string) => { if (!activeThreadId || !activeThreadRef) return; const fallbackExitWrite = () => writeTerminal({ environmentId, input: { threadId: activeThreadId, terminalId, data: "exit\n" }, }); void (async () => { const closeResult = await closeTerminalMutation({ environmentId, input: { threadId: activeThreadId, terminalId, deleteHistory: true, }, }); if (closeResult._tag === "Failure" && !isAtomCommandInterrupted(closeResult)) { await fallbackExitWrite(); } })(); storeCloseTerminal(activeThreadRef, terminalId); setTerminalFocusRequestId((value) => value + 1); }, [ activeThreadId, activeThreadRef, closeTerminalMutation, environmentId, storeCloseTerminal, writeTerminal, ], ); const runProjectScript = useCallback( async ( script: ProjectScript, options?: { cwd?: string; env?: Record; worktreePath?: string | null; preferNewTerminal?: boolean; rememberAsLastInvoked?: boolean; }, ) => { if (!activeThreadId || !activeProject || !activeThread) return; if (options?.rememberAsLastInvoked !== false) { setLastInvokedScriptByProjectId((current) => { if (current[activeProject.id] === script.id) return current; return { ...current, [activeProject.id]: script.id }; }); } const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot; const baseTerminalId = terminalUiState.activeTerminalId || activeKnownTerminalIds[0] || DEFAULT_THREAD_TERMINAL_ID; const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId); const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy; const shouldCreateNewTerminal = wantsNewTerminal; const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null; setTerminalUiLaunchContext({ threadId: activeThreadId, cwd: targetCwd, worktreePath: targetWorktreePath, }); setTerminalOpen(true); if (!activeThreadRef) { return; } setTerminalFocusRequestId((value) => value + 1); const runtimeEnv = projectScriptRuntimeEnv({ project: { cwd: activeProject.workspaceRoot, }, worktreePath: targetWorktreePath, ...(options?.env ? { extraEnv: options.env } : {}), }); const targetTerminalId = shouldCreateNewTerminal ? nextTerminalId(allocatableActiveTerminalIds) : baseTerminalId; const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal ? { threadId: activeThreadId, terminalId: targetTerminalId, cwd: targetCwd, ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), env: runtimeEnv, cols: SCRIPT_TERMINAL_COLS, rows: SCRIPT_TERMINAL_ROWS, } : { threadId: activeThreadId, terminalId: targetTerminalId, cwd: targetCwd, ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}), env: runtimeEnv, }; if (shouldCreateNewTerminal) { storeNewTerminal(activeThreadRef, targetTerminalId); } else { storeSetActiveTerminal(activeThreadRef, targetTerminalId); } const openResult = await openTerminal({ environmentId, input: openTerminalInput }); if (openResult._tag === "Failure") { if (!isAtomCommandInterrupted(openResult)) { const error = squashAtomCommandFailure(openResult); setThreadError( activeThreadId, error instanceof Error ? error.message : `Failed to run script "${script.name}".`, ); } return; } const writeResult = await writeTerminal({ environmentId, input: { threadId: activeThreadId, terminalId: targetTerminalId, data: `${script.command}\r`, }, }); if (writeResult._tag === "Failure" && !isAtomCommandInterrupted(writeResult)) { const error = squashAtomCommandFailure(writeResult); setThreadError( activeThreadId, error instanceof Error ? error.message : `Failed to run script "${script.name}".`, ); } }, [ activeProject, activeThread, activeThreadId, activeThreadRef, gitCwd, setTerminalOpen, setThreadError, storeNewTerminal, storeSetActiveTerminal, setLastInvokedScriptByProjectId, environmentId, openTerminal, activeKnownTerminalIds, allocatableActiveTerminalIds, runningTerminalIds, terminalUiState.activeTerminalId, writeTerminal, ], ); const persistProjectScripts = useCallback( async (input: { projectId: ProjectId; projectCwd: string; previousScripts: ReadonlyArray; nextScripts: ReadonlyArray; keybinding?: string | null; keybindingCommand: KeybindingCommand; }): Promise> => { const updateResult = mapAtomCommandResult( await updateProject({ environmentId, input: { projectId: input.projectId, scripts: input.nextScripts, }, }), () => undefined, ); if (updateResult._tag === "Failure") { return updateResult; } const keybindingRule = decodeProjectScriptKeybindingRule({ keybinding: input.keybinding, command: input.keybindingCommand, }); if (isElectron && keybindingRule) { return mapAtomCommandResult( await upsertKeybinding({ environmentId, input: keybindingRule, }), () => undefined, ); } return updateResult; }, [environmentId, updateProject, upsertKeybinding], ); const saveProjectScript = useCallback( async (input: NewProjectScriptInput): Promise> => { if (!activeProject) { return AsyncResult.success(undefined); } const nextId = nextProjectScriptId( input.name, activeProject.scripts.map((script) => script.id), ); const nextScript = buildProjectScript(nextId, input); const nextScripts = input.runOnWorktreeCreate ? [ ...activeProject.scripts.map((script) => script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script, ), nextScript, ] : [...activeProject.scripts, nextScript]; return persistProjectScripts({ projectId: activeProject.id, projectCwd: activeProject.workspaceRoot, previousScripts: activeProject.scripts, nextScripts, keybinding: input.keybinding, keybindingCommand: commandForProjectScript(nextId), }); }, [activeProject, persistProjectScripts], ); const updateProjectScript = useCallback( async ( scriptId: string, input: NewProjectScriptInput, ): Promise> => { if (!activeProject) { return AsyncResult.success(undefined); } const existingScript = activeProject.scripts.find((script) => script.id === scriptId); if (!existingScript) { return AsyncResult.failure(Cause.fail(new Error("Script not found."))); } const updatedScript = buildProjectScript(existingScript.id, input); const nextScripts = activeProject.scripts.map((script) => script.id === scriptId ? updatedScript : input.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script, ); return persistProjectScripts({ projectId: activeProject.id, projectCwd: activeProject.workspaceRoot, previousScripts: activeProject.scripts, nextScripts, keybinding: input.keybinding, keybindingCommand: commandForProjectScript(scriptId), }); }, [activeProject, persistProjectScripts], ); const deleteProjectScript = useCallback( async (scriptId: string): Promise> => { if (!activeProject) { return AsyncResult.success(undefined); } const nextScripts = activeProject.scripts.filter((script) => script.id !== scriptId); const deletedName = activeProject.scripts.find((s) => s.id === scriptId)?.name; const result = await persistProjectScripts({ projectId: activeProject.id, projectCwd: activeProject.workspaceRoot, previousScripts: activeProject.scripts, nextScripts, keybinding: null, keybindingCommand: commandForProjectScript(scriptId), }); if (result._tag === "Success") { toastManager.add({ type: "success", title: `Deleted action "${deletedName ?? "Unknown"}"`, }); } else if (!isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); toastManager.add( stackedThreadToast({ type: "error", title: "Could not delete action", description: error instanceof Error ? error.message : "An unexpected error occurred.", }), ); } return result; }, [activeProject, persistProjectScripts], ); const handleRuntimeModeChange = useCallback( (mode: RuntimeMode) => { if (mode === runtimeMode) return; setComposerDraftRuntimeMode(composerDraftTarget, mode); if (isLocalDraftThread) { setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); } scheduleComposerFocus(); }, [ isLocalDraftThread, runtimeMode, scheduleComposerFocus, composerDraftTarget, setComposerDraftRuntimeMode, setDraftThreadContext, ], ); const handleInteractionModeChange = useCallback( (mode: ProviderInteractionMode) => { if (mode === interactionMode) return; setComposerDraftInteractionMode(composerDraftTarget, mode); if (isLocalDraftThread) { setDraftThreadContext(composerDraftTarget, { interactionMode: mode }); } scheduleComposerFocus(); }, [ interactionMode, isLocalDraftThread, scheduleComposerFocus, composerDraftTarget, setComposerDraftInteractionMode, setDraftThreadContext, ], ); const toggleInteractionMode = useCallback(() => { handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan"); }, [handleInteractionModeChange, interactionMode]); const dismissPlanSidebarForCurrentTurn = useCallback(() => { planSidebarDismissedForTurnRef.current = activePlan?.runId ?? sidebarProposedPlan?.runId ?? "__dismissed__"; }, [activePlan?.runId, sidebarProposedPlan?.runId]); const togglePlanSidebar = useCallback(() => { if (!activeThreadRef) return; if (planSidebarOpen) { dismissPlanSidebarForCurrentTurn(); } else { planSidebarDismissedForTurnRef.current = null; } useRightPanelStore.getState().toggle(activeThreadRef, "plan"); }, [activeThreadRef, dismissPlanSidebarForCurrentTurn, planSidebarOpen]); const closePlanSidebar = useCallback(() => { if (!activeThreadRef) return; setMaximizedRightPanelThreadKey(null); useRightPanelStore.getState().close(activeThreadRef); dismissPlanSidebarForCurrentTurn(); }, [activeThreadRef, dismissPlanSidebarForCurrentTurn]); const createBrowserSurface = useCallback(() => { if (!activeThreadRef) return; void addBrowserSurface({ threadRef: activeThreadRef, openPreview }); }, [activeThreadRef, openPreview]); const addDiffSurface = useCallback(() => { if (!activeThreadRef || !isServerThread || !isGitRepo) return; useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); }, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]); const openChangesFromThreadPanel = useCallback(() => { addDiffSurface(); }, [addDiffSurface]); const addFilesSurface = useCallback(() => { if (!activeThreadRef || !activeProject) return; useRightPanelStore.getState().open(activeThreadRef, "files"); }, [activeProject, activeThreadRef]); const addAgentsSurface = useCallback(() => { if (!activeThreadRef) return; useRightPanelStore.getState().open(activeThreadRef, "agents"); }, [activeThreadRef]); const openFileSurface = useCallback( (relativePath: string) => { if (!activeThreadRef || !activeProject) return; useRightPanelStore.getState().openFile(activeThreadRef, relativePath); }, [activeProject, activeThreadRef], ); const togglePreviewPanel = useCallback(() => { if (!activeThreadRef || !isPreviewSupportedInRuntime()) return; if (previewPanelOpen) { useRightPanelStore.getState().close(activeThreadRef); return; } const activeTabId = activePreviewState.activeTabId; if (activeTabId) { useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId); } else { createBrowserSurface(); } }, [activePreviewState.activeTabId, activeThreadRef, createBrowserSurface, previewPanelOpen]); const closePreviewPanel = useCallback(() => { if (activeThreadRef) { setMaximizedRightPanelThreadKey(null); useRightPanelStore.getState().close(activeThreadRef); } }, [activeThreadRef]); const addTerminalSurface = useCallback(() => { if (!activeThreadRef || !activeThreadId || !activeProject) return; const cwd = gitCwd ?? activeProject.workspaceRoot; const terminalId = nextTerminalId(allocatableActiveTerminalIds); useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId); setTerminalFocusRequestId((value) => value + 1); void openTerminal({ environmentId: activeThreadRef.environmentId, input: { threadId: activeThreadId, terminalId, cwd, ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), env: projectScriptRuntimeEnv({ project: { cwd: activeProject.workspaceRoot }, worktreePath: activeThreadWorktreePath, }), }, }); }, [ activeProject, activeThreadId, activeThreadRef, activeThreadWorktreePath, allocatableActiveTerminalIds, gitCwd, openTerminal, ]); const splitPanelTerminal = useCallback( (direction: "horizontal" | "vertical" = "horizontal") => { if ( !activeThreadRef || !activeThreadId || !activeProject || activeRightPanelSurface?.kind !== "terminal" || activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP ) { return; } const terminalId = nextTerminalId(allocatableActiveTerminalIds); const cwd = gitCwd ?? activeProject.workspaceRoot; useRightPanelStore .getState() .splitTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId, direction); setTerminalFocusRequestId((value) => value + 1); void openTerminal({ environmentId: activeThreadRef.environmentId, input: { threadId: activeThreadId, terminalId, cwd, ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}), env: projectScriptRuntimeEnv({ project: { cwd: activeProject.workspaceRoot }, worktreePath: activeThreadWorktreePath, }), }, }); }, [ activeProject, activeRightPanelSurface, activeThreadId, activeThreadRef, activeThreadWorktreePath, allocatableActiveTerminalIds, gitCwd, openTerminal, ], ); const splitPanelTerminalVertical = useCallback(() => { splitPanelTerminal("vertical"); }, [splitPanelTerminal]); const activatePanelTerminal = useCallback( (terminalId: string) => { if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return; useRightPanelStore .getState() .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId); setTerminalFocusRequestId((value) => value + 1); }, [activeRightPanelSurface, activeThreadRef], ); const closePanelTerminal = useCallback( (terminalId: string) => { if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return; void closeTerminalMutation({ environmentId: activeThreadRef.environmentId, input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true }, }); storeCloseTerminal(activeThreadRef, terminalId); useRightPanelStore .getState() .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId); setTerminalFocusRequestId((value) => value + 1); }, [activeRightPanelSurface, activeThreadRef, closeTerminalMutation, storeCloseTerminal], ); const activateRightPanelSurface = useCallback( (surface: RightPanelSurface) => { if (!activeThreadRef) return; useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id); if (surface.kind === "preview" && surface.resourceId) { setActivePreviewTab(activeThreadRef, surface.resourceId); } if (surface.kind === "terminal") { setTerminalFocusRequestId((value) => value + 1); } if (surface.kind === "diff" && !diffOpen) { onDiffPanelOpen?.(); } }, [activeThreadRef, diffOpen, onDiffPanelOpen], ); const toggleRightPanel = useCallback(() => { if (!activeThreadRef) return; if (rightPanelOpen) { closePreviewPanel(); return; } useRightPanelStore.getState().toggleVisibility(activeThreadRef); }, [activeThreadRef, closePlanSidebar, closePreviewPanel, planSidebarOpen, rightPanelOpen]); const toggleThreadPanel = useCallback(() => { if (!activeThreadRef) return; useRightPanelStore.getState().toggleThreadPanel(activeThreadRef, threadPanelPresentation); }, [activeThreadRef, threadPanelPresentation]); const closeThreadPanelPopover = useCallback(() => { if (!activeThreadRef) return; useRightPanelStore.getState().setThreadPanelOpen(activeThreadRef, "popover", false); }, [activeThreadRef]); const toggleRightPanelMaximized = useCallback(() => { if (!canMaximizeRightPanel) return; setMaximizedRightPanelThreadKey((threadKey) => threadKey === routeThreadKey ? null : routeThreadKey, ); }, [canMaximizeRightPanel, routeThreadKey]); const cleanupRightPanelSurfaces = useCallback( (surfaces: readonly RightPanelSurface[]) => { if (!activeThreadRef) return; for (const surface of surfaces) { if (surface.kind === "preview" && surface.resourceId) { void closePreviewSession({ closePreview, snapshot: activePreviewState.sessions[surface.resourceId] ?? null, tabId: surface.resourceId, threadRef: activeThreadRef, }); } if (surface.kind === "terminal") { for (const terminalId of surface.terminalIds) { storeCloseTerminal(activeThreadRef, terminalId); void closeTerminalMutation({ environmentId: activeThreadRef.environmentId, input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true }, }); } } } }, [ activeThreadRef, activePreviewState.sessions, closePreview, closeTerminalMutation, storeCloseTerminal, ], ); const syncActivePreviewSurface = useCallback(() => { if (!activeThreadRef) return; const nextActiveSurface = selectActiveRightPanelSurface( useRightPanelStore.getState().byThreadKey, activeThreadRef, ); if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) { setActivePreviewTab(activeThreadRef, nextActiveSurface.resourceId); } }, [activeThreadRef]); const closeRightPanelSurface = useCallback( (surface: RightPanelSurface) => { if (!activeThreadRef) return; cleanupRightPanelSurfaces([surface]); useRightPanelStore.getState().closeSurface(activeThreadRef, surface.id); syncActivePreviewSurface(); }, [activeThreadRef, cleanupRightPanelSurfaces, syncActivePreviewSurface], ); const closeOtherRightPanelSurfaces = useCallback( (surface: RightPanelSurface) => { if (!activeThreadRef) return; const surfaces = rightPanelState.surfaces.filter((entry) => entry.id !== surface.id); cleanupRightPanelSurfaces(surfaces); useRightPanelStore.getState().closeOtherSurfaces(activeThreadRef, surface.id); syncActivePreviewSurface(); }, [ activeThreadRef, cleanupRightPanelSurfaces, rightPanelState.surfaces, syncActivePreviewSurface, ], ); const closeRightPanelSurfacesToRight = useCallback( (surface: RightPanelSurface) => { if (!activeThreadRef) return; const surfaceIndex = rightPanelState.surfaces.findIndex((entry) => entry.id === surface.id); if (surfaceIndex < 0) return; const surfaces = rightPanelState.surfaces.slice(surfaceIndex + 1); cleanupRightPanelSurfaces(surfaces); useRightPanelStore.getState().closeSurfacesToRight(activeThreadRef, surface.id); syncActivePreviewSurface(); }, [ activeThreadRef, cleanupRightPanelSurfaces, rightPanelState.surfaces, syncActivePreviewSurface, ], ); const closeAllRightPanelSurfaces = useCallback(() => { if (!activeThreadRef) return; cleanupRightPanelSurfaces(rightPanelState.surfaces); useRightPanelStore.getState().closeAllSurfaces(activeThreadRef); }, [activeThreadRef, cleanupRightPanelSurfaces, rightPanelState.surfaces]); const copyRightPanelFilePath = useCallback((relativePath: string) => { if (typeof window === "undefined" || !navigator.clipboard?.writeText) { toastManager.add( stackedThreadToast({ type: "error", title: "Failed to copy path", description: "Clipboard API unavailable.", }), ); return; } void navigator.clipboard.writeText(relativePath).then( () => { toastManager.add({ type: "success", title: "Path copied", description: relativePath, }); }, (error) => { toastManager.add( stackedThreadToast({ type: "error", title: "Failed to copy path", description: error instanceof Error ? error.message : "An error occurred.", }), ); }, ); }, []); useEffect( () => subscribePreviewAction((action) => { if (action === "toggle-panel") togglePreviewPanel(); }), [togglePreviewPanel], ); const persistThreadSettingsForNextTurn = useCallback( async (input: { threadId: ThreadId; createdAt: string; modelSelection?: ModelSelection; branch?: string; runtimeMode: RuntimeMode; interactionMode: ProviderInteractionMode; }): Promise> => { if (!serverThread) { return AsyncResult.success(undefined); } let result: AtomCommandResult = AsyncResult.success(undefined); const metadataUpdate = resolveThreadMetadataUpdateForNextTurn({ currentModelSelection: serverThread.modelSelection, ...(input.modelSelection ? { nextModelSelection: input.modelSelection } : {}), currentBranch: serverThread.branch, ...(input.branch ? { nextBranch: input.branch } : {}), }); if (metadataUpdate) { result = mapAtomCommandResult( await updateThreadMetadata({ environmentId, input: { threadId: input.threadId, ...metadataUpdate, }, }), () => undefined, ); if (result._tag === "Failure") { return result; } } if (input.runtimeMode !== serverThread.runtimeMode) { result = mapAtomCommandResult( await setThreadRuntimeMode({ environmentId, input: { threadId: input.threadId, runtimeMode: input.runtimeMode, createdAt: input.createdAt, }, }), () => undefined, ); if (result._tag === "Failure") { return result; } } if (input.interactionMode !== serverThread.interactionMode) { result = mapAtomCommandResult( await setThreadInteractionMode({ environmentId, input: { threadId: input.threadId, interactionMode: input.interactionMode, createdAt: input.createdAt, }, }), () => undefined, ); } return result; }, [ environmentId, serverThread, setThreadInteractionMode, setThreadRuntimeMode, updateThreadMetadata, ], ); // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during // thread switches. LegendList fires scroll events with isAtEnd=false while // initialScrollAtEnd is settling; hiding is always immediate. const showScrollDebouncer = useRef( new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }), ); const timelineScrollModeRef = useRef("following-end"); // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd // re-pins on its own (independent of the refs), so the timeline needs a // render-visible flag to switch it off once the user scrolls away. const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true); const pendingTimelineAnchorRef = useRef(null); const positionedTimelineAnchorRef = useRef(null); const settledTimelineAnchorRef = useRef(null); const activeTimelineAnchorIndexRef = useRef(null); const anchorUserScrollGenerationRef = useRef(0); const liveFollowUserScrollGenerationRef = useRef(0); // Manual navigation stops live-follow without removing anchored end space. // Collapsing that space during a gesture clamps the viewport back to the end. const cancelTimelineLiveFollowForUserNavigation = useCallback(() => { anchorUserScrollGenerationRef.current += 1; timelineScrollModeRef.current = "free-scrolling"; liveFollowUserScrollGenerationRef.current = null; setTimelineLiveFollowEnabled(false); pendingTimelineAnchorRef.current = null; positionedTimelineAnchorRef.current = null; settledTimelineAnchorRef.current = null; activeTimelineAnchorIndexRef.current = null; }, []); const cancelTimelineLiveFollowForUserNavigationRef = useRef( cancelTimelineLiveFollowForUserNavigation, ); useEffect(() => { cancelTimelineLiveFollowForUserNavigationRef.current = cancelTimelineLiveFollowForUserNavigation; }, [cancelTimelineLiveFollowForUserNavigation]); const getActiveTimelineTurnMetrics = useCallback( (list?: LegendListRef | null) => { const resolvedList = list ?? legendListRef.current; const anchorIndex = activeTimelineAnchorIndexRef.current; const state = resolvedList?.getState(); if (!resolvedList || !state || anchorIndex === null) { return null; } return getAnchoredTurnMetrics({ state, anchorIndex, composerOverlayHeight, anchorOffset: CHAT_LIST_ANCHOR_OFFSET, }); }, [composerOverlayHeight], ); const timelineRealContentOverflowsViewport = useCallback( (list?: LegendListRef | null) => { const resolvedList = list ?? legendListRef.current; const state = resolvedList?.getState(); if (!resolvedList || !state || state.data.length === 0) { return false; } const lastRowIndex = state.data.length - 1; const lastRowTop = state.positionAtIndex(lastRowIndex); const lastRowHeight = state.sizeAtIndex(lastRowIndex); if ( typeof lastRowTop !== "number" || typeof lastRowHeight !== "number" || !Number.isFinite(lastRowTop) || !Number.isFinite(lastRowHeight) ) { return false; } const realContentBottom = lastRowTop + Math.max(1, lastRowHeight); const visibleScrollLength = Math.max( 0, (state.scrollLength ?? 0) - composerOverlayHeight - CHAT_LIST_ANCHOR_OFFSET, ); return realContentBottom > visibleScrollLength; }, [composerOverlayHeight], ); // Live-follow stays active after send/thread-open until an actual list scroll // gesture opts out. const scrollToEnd = useCallback((animated = false) => { isAtEndRef.current = true; timelineScrollModeRef.current = "following-end"; liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current; setTimelineLiveFollowEnabled(true); pendingTimelineAnchorRef.current = null; activeTimelineAnchorIndexRef.current = null; showScrollDebouncer.current.cancel(); setShowScrollToBottom(false); setTimelineAnchor((current) => current.messageId === null ? current : { ...current, messageId: null }, ); requestAnimationFrame(() => { void legendListRef.current?.scrollToEnd?.({ animated }); }); }, []); useEffect(() => { let removeListeners: (() => void) | null = null; let frame: number | null = null; const attach = (remainingAttempts: number) => { frame = requestAnimationFrame(() => { frame = null; const scrollNode = legendListRef.current?.getScrollableNode(); if (!scrollNode) { // The list may not have mounted on the first frame after a thread // switch — without a retry the opt-out listeners never attach and // live-follow becomes impossible to escape for the whole thread. if (remainingAttempts > 0) { attach(remainingAttempts - 1); } return; } const handleManualNavigation = () => { cancelTimelineLiveFollowForUserNavigationRef.current(); }; // The gestures below must only break follow when they can actually // move the viewport away from the live edge. Follow now gates // LegendList's maintainScrollAtEnd, so a spurious break while pinned // at the end produces no scroll event, never re-arms, and streaming // silently stops following. Underflowing content can't scroll at all, // so nothing there should break follow. const contentScrollsUp = () => timelineRealContentOverflowsViewport(); // The follow re-arm band, not the strict flag: streaming growth makes // isAtEnd flicker false for a frame before the follow scroll catches // up, and a gesture landing in that window while still pinned would // otherwise break follow with no scroll event left to re-arm it. const viewportIsAwayFromEnd = () => resolveTimelineIsAtEnd(legendListRef.current?.getState(), composerOverlayHeight) === false; // Only an upward wheel is a navigation intent; wheeling down while // following either does nothing (at the end) or moves toward it. const handleWheel = (event: WheelEvent) => { if (event.deltaY < 0 && contentScrollsUp()) { handleManualNavigation(); } }; // Touch direction isn't observable here (touchmove fires on any // finger motion, scrolling or not), so break only once the drag has // actually carried the viewport out of the end band — an upward flick // gets there within its first few events and later touchmoves break. const handleTouchMove = () => { if (viewportIsAwayFromEnd()) { handleManualNavigation(); } }; // Scrollbar drags produce no wheel/touch events; they are the only // pointerdowns whose target is the scroll node itself rather than a // message row. Content clicks break follow only away from the end // (reading or selecting up there must hold position); clicking near // the live edge keeps following. const handlePointerDown = (event: PointerEvent) => { if (event.target === scrollNode) { if (contentScrollsUp()) { handleManualNavigation(); } return; } if (viewportIsAwayFromEnd()) { handleManualNavigation(); } }; // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and // pointer events entirely; without this the timeline yanks back to // the end on the next stream chunk. const handleKeyDown = (event: KeyboardEvent) => { switch (event.key) { case "PageUp": case "Home": case "ArrowUp": if (contentScrollsUp()) { handleManualNavigation(); } break; default: break; } }; scrollNode.addEventListener("wheel", handleWheel, { passive: true, }); scrollNode.addEventListener("touchmove", handleTouchMove, { passive: true, }); scrollNode.addEventListener("pointerdown", handlePointerDown, { passive: true, }); scrollNode.addEventListener("keydown", handleKeyDown); removeListeners = () => { scrollNode.removeEventListener("wheel", handleWheel); scrollNode.removeEventListener("touchmove", handleTouchMove); scrollNode.removeEventListener("pointerdown", handlePointerDown); scrollNode.removeEventListener("keydown", handleKeyDown); }; }); }; attach(12); return () => { if (frame !== null) { cancelAnimationFrame(frame); } removeListeners?.(); }; }, [activeThread?.id, composerOverlayHeight, timelineRealContentOverflowsViewport]); const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => { // Anchored-end space can be remeasured when the turn completes. Once the // user has scrolled away (or returned to ordinary end-following), that // remeasurement must not restart the send-time anchor positioning. if (timelineScrollModeRef.current !== "anchoring-new-turn") { return; } if (pendingTimelineAnchorRef.current === messageId) { pendingTimelineAnchorRef.current = null; } activeTimelineAnchorIndexRef.current = anchorIndex; if (positionedTimelineAnchorRef.current === messageId) { return; } positionedTimelineAnchorRef.current = messageId; settledTimelineAnchorRef.current = null; const positionAnchor = (remainingAttempts: number) => { requestAnimationFrame(() => { if (positionedTimelineAnchorRef.current !== messageId) { return; } const list = legendListRef.current; if (!list) { if (remainingAttempts > 0) { positionAnchor(remainingAttempts - 1); } return; } void list .scrollToIndex({ index: anchorIndex, animated: true, viewPosition: 0, viewOffset: CHAT_LIST_ANCHOR_OFFSET, }) .then(() => { if (positionedTimelineAnchorRef.current !== messageId) { return; } settledTimelineAnchorRef.current = messageId; }); }); }; requestAnimationFrame(() => positionAnchor(12)); }, []); const onIsAtEndChange = useCallback((isAtEnd: boolean) => { if ( !isAtEnd && liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current ) { showScrollDebouncer.current.cancel(); setShowScrollToBottom(false); return; } if (isAtEndRef.current === isAtEnd) return; isAtEndRef.current = isAtEnd; if (isAtEnd) { timelineScrollModeRef.current = "following-end"; liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current; setTimelineLiveFollowEnabled(true); showScrollDebouncer.current.cancel(); setShowScrollToBottom(false); } else { timelineScrollModeRef.current = "free-scrolling"; liveFollowUserScrollGenerationRef.current = null; showScrollDebouncer.current.maybeExecute(); } }, []); // Anchored end space intentionally disables LegendList's normal end-follow so // the sent message can stay near the top. T3 only owns streaming adjustments // during that mode; LegendList owns ordinary end-follow everywhere else. useEffect(() => { if (!activeThread?.id) { return; } if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) { return; } if (timelineScrollModeRef.current !== "anchoring-new-turn") { return; } let secondFrame: number | null = null; const frame = requestAnimationFrame(() => { secondFrame = requestAnimationFrame(() => { if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) { return; } if (pendingTimelineAnchorRef.current !== null) { return; } if ( positionedTimelineAnchorRef.current !== null && settledTimelineAnchorRef.current !== positionedTimelineAnchorRef.current ) { return; } const list = legendListRef.current; if (!list) { return; } const metrics = getActiveTimelineTurnMetrics(list); if (!metrics || metrics.scrollDeltaToRevealEnd <= 1) { return; } const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd; void list.scrollToOffset({ offset: nextOffset, animated: false }); }); }); return () => { cancelAnimationFrame(frame); if (secondFrame !== null) { cancelAnimationFrame(secondFrame); } }; }, [activeThread?.id, timelineEntries, getActiveTimelineTurnMetrics]); useEffect(() => { setPullRequestDialogState(null); isAtEndRef.current = true; timelineScrollModeRef.current = "following-end"; liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current; setTimelineLiveFollowEnabled(true); pendingTimelineAnchorRef.current = null; positionedTimelineAnchorRef.current = null; settledTimelineAnchorRef.current = null; activeTimelineAnchorIndexRef.current = null; showScrollDebouncer.current.cancel(); setShowScrollToBottom(false); // activeThreadRef resets transitively with the active thread. }, [activeThread?.id]); // Auto-open the plan sidebar when plan/todo steps arrive for the current turn. // Don't auto-open for plans carried over from a previous turn (the user can open manually). useEffect(() => { if (!autoOpenPlanSidebar) return; if (!activePlan) return; if (planSidebarOpen) return; const latestRunId = activeLatestRun?.runId ?? null; if (latestRunId && activePlan.runId !== latestRunId) return; const turnKey = activePlan.runId ?? sidebarProposedPlan?.runId ?? "__dismissed__"; if (planSidebarDismissedForTurnRef.current === turnKey) return; if (activeThreadRef) { useRightPanelStore.getState().open(activeThreadRef, "plan"); } }, [ activePlan, activeLatestRun?.runId, activeThreadRef, autoOpenPlanSidebar, planSidebarOpen, sidebarProposedPlan?.runId, ]); useEffect(() => { setIsRevertingCheckpoint(false); }, [activeThread?.id]); useEffect(() => { if (!activeThread?.id || terminalUiState.terminalOpen) return; const frame = window.requestAnimationFrame(() => { focusComposer(); }); return () => { window.cancelAnimationFrame(frame); }; }, [activeThread?.id, focusComposer, terminalUiState.terminalOpen]); useEffect(() => { if (!activeThread?.id) return; if (activeMessageCount === 0) { return; } const removedMessages = optimisticUserMessages.filter((message) => committedServerMessageIds.has(message.id), ); if (removedMessages.length === 0) { return; } const timer = window.setTimeout(() => { setOptimisticUserMessages((existing) => existing.filter((message) => !committedServerMessageIds.has(message.id)), ); }, 0); for (const removedMessage of removedMessages) { const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage); if (previewUrls.length > 0) { handoffAttachmentPreviews(removedMessage.id, previewUrls); continue; } revokeUserMessagePreviewUrls(removedMessage); } return () => { window.clearTimeout(timer); }; }, [ activeMessageCount, activeThread?.id, committedServerMessageIds, handoffAttachmentPreviews, optimisticUserMessages, ]); useEffect(() => { setOptimisticUserMessages((existing) => { for (const message of existing) { revokeUserMessagePreviewUrls(message); } return []; }); resetLocalDispatch(); setExpandedImage(null); }, [draftId, resetLocalDispatch, threadId]); const closeExpandedImage = useCallback(() => { setExpandedImage(null); }, []); const activeWorktreePath = activeThread?.worktreePath ?? null; const derivedEnvMode: DraftThreadEnvMode = resolveEffectiveEnvMode({ activeWorktreePath, hasServerThread: isServerThread, draftThreadEnvMode: isLocalDraftThread ? draftThread?.envMode : undefined, }); const canOverrideServerThreadEnvMode = Boolean( isServerThread && activeThread && activeMessageCount === 0 && activeThread.worktreePath === null && !envLocked, ); const envMode: DraftThreadEnvMode = canOverrideServerThreadEnvMode ? (pendingServerThreadEnvMode ?? draftThread?.envMode ?? derivedEnvMode) : derivedEnvMode; const activeThreadBranch = canOverrideServerThreadEnvMode && pendingServerThreadBranch !== undefined ? pendingServerThreadBranch : (activeThread?.branch ?? null); const startFromOrigin = isLocalDraftThread ? (draftThread?.startFromOrigin ?? false) : canOverrideServerThreadEnvMode ? (pendingServerThreadStartFromOriginByThreadId[activeThread?.id ?? ""] ?? primaryServerSettings.newWorktreesStartFromOrigin) : false; const sendEnvMode = resolveSendEnvMode({ requestedEnvMode: envMode, isGitRepo, }); const localCheckoutBranchMismatch = useMemo( () => isServerThread ? resolveLocalCheckoutBranchMismatch({ effectiveEnvMode: envMode, activeWorktreePath, activeThreadBranch, currentGitBranch: gitStatusQuery.data?.refName ?? null, }) : null, [activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread], ); // Settled state of the open thread, resolved exactly like the sidebar // partition (same shell, same capability gate, same PR auto-settle input) // so the banner and the sidebar row never disagree. const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null); const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays); const activeThreadPr = resolveThreadPr({ threadBranch: activeThread?.branch ?? null, gitStatus: gitStatusQuery.data ?? null, }); const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true; const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true; const nowMinute = useNowMinute(); const snoozeNow = new Date().toISOString(); const activeThreadSnoozed = activeThreadShell !== null && supportsSnooze && effectiveSnoozed(activeThreadShell, { now: snoozeNow }); const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0); void snoozeWakeTick; const activeThreadWokeAt = activeThreadShell !== null && supportsSnooze ? threadWokeAt(activeThreadShell, { now: snoozeNow }) : null; useEffect(() => { if (!activeThreadSnoozed) return; const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? ""); if (!Number.isFinite(wakeAtMs)) return; const id = window.setTimeout( () => bumpSnoozeWakeTick((tick) => tick + 1), Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647), ); return () => window.clearTimeout(id); }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]); const acknowledgeActiveThreadWoke = useCallback(() => { if (activeThreadRef === null || activeThreadWokeAt === null) return; markThreadVisited(scopedThreadKey(activeThreadRef), activeThreadWokeAt); }, [activeThreadRef, activeThreadWokeAt, markThreadVisited]); // Mirror of the sidebar's Woke pill for the open thread: same visit // comparison, same merged/closed-PR suppression (finished work needs no // wake-up call). Drives the dismissible composer banner below. const activeThreadLastVisitedAt = useUiStateStore((store) => activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey], ); const activeThreadWokeVisible = useMemo(() => { if (activeThreadWokeAt === null) return false; if (activeThreadPr?.state === "merged" || activeThreadPr?.state === "closed") return false; const wokeAtMs = Date.parse(activeThreadWokeAt); if (Number.isNaN(wokeAtMs)) return false; // Having the thread open counts as a visit at completedAt (the effect // above stamps it); folding that floor in here keeps a completion- // triggered wake from flashing a banner for one frame before the stamp // lands. An unparseable stored visit counts as never-visited: corrupt // local data must not eat the wake signal. const storedVisitMs = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN; const completedAtMs = activeLatestTurn?.completedAt ? Date.parse(activeLatestTurn.completedAt) : NaN; const lastVisitedMs = Math.max( Number.isNaN(storedVisitMs) ? -Infinity : storedVisitMs, Number.isNaN(completedAtMs) ? -Infinity : completedAtMs, ); return lastVisitedMs < wokeAtMs; }, [ activeLatestTurn?.completedAt, activeThreadLastVisitedAt, activeThreadPr?.state, activeThreadWokeAt, ]); const activeThreadSettled = useMemo(() => { if (activeThreadShell === null || !supportsSettlement) return false; return effectiveSettled(activeThreadShell, { now: `${nowMinute}:00.000Z`, autoSettleAfterDays, changeRequestState: activeThreadPr?.state ?? null, }); }, [ activeThreadPr?.state, activeThreadShell, autoSettleAfterDays, nowMinute, supportsSettlement, ]); const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, { reportFailure: false, }); // Keyed by thread, not a boolean: the pending state must follow the thread // it belongs to across navigation, and a request resolving for thread A // must never clear (or re-enable) thread B's button. const [unsettlingThreadKey, setUnsettlingThreadKey] = useState(null); const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey; const handleUnsettleActiveThread = useCallback(async () => { if (!activeThreadRef) return; const threadKey = scopedThreadKey(activeThreadRef); setUnsettlingThreadKey(threadKey); try { const result = await unsettleThreadMutation({ environmentId: activeThreadRef.environmentId, input: { threadId: activeThreadRef.threadId, reason: "user" }, }); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); toastManager.add( stackedThreadToast({ type: "error", title: "Failed to un-settle thread", description: error instanceof Error ? error.message : "An error occurred.", }), ); } } finally { setUnsettlingThreadKey((current) => (current === threadKey ? null : current)); } }, [activeThreadRef, unsettleThreadMutation]); const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false, }); const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState(null); const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey; const handleUnsnoozeActiveThread = useCallback(async () => { if (!activeThreadRef) return; const threadKey = scopedThreadKey(activeThreadRef); setUnsnoozingThreadKey(threadKey); try { const result = await unsnoozeThreadMutation({ environmentId: activeThreadRef.environmentId, input: { threadId: activeThreadRef.threadId, reason: "user" }, }); if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); toastManager.add( stackedThreadToast({ type: "error", title: "Failed to wake thread", description: error instanceof Error ? error.message : "An error occurred.", }), ); } } finally { setUnsnoozingThreadKey((current) => (current === threadKey ? null : current)); } }, [activeThreadRef, unsnoozeThreadMutation]); const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false); const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false); // Once revealed for a given mismatch, the banner stays mounted until the // mismatch changes or resolves, so clearing the draft doesn't flicker it. const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState(null); // Dismissal lives in a module-level set (survives remounts); this tick just // forces a re-render so the banner leaves immediately. const [, setBranchMismatchDismissTick] = useState(0); const composerHasDraftContent = useComposerDraftStore((store) => { const draft = store.getComposerDraft(composerDraftTarget); return Boolean( draft && (draft.prompt.trim().length > 0 || draft.images.length > 0 || draft.terminalContexts.length > 0 || draft.elementContexts.length > 0 || draft.previewAnnotations.length > 0 || draft.reviewComments.length > 0), ); }); const activeBranchMismatchKey = branchMismatchKey( activeThread?.id ?? null, localCheckoutBranchMismatch, ); const showBranchMismatchBanner = shouldShowBranchMismatchBanner({ hasMismatch: localCheckoutBranchMismatch !== null, isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey), composerHasContent: composerHasDraftContent, wasShownForCurrentMismatch: revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey, }); useEffect(() => { setRevealedBranchMismatchKey((revealed) => { if (showBranchMismatchBanner) { return activeBranchMismatchKey; } // Hysteresis is scoped to an uninterrupted mismatch: reset when the // mismatch resolves or changes so a recurrence re-gates on intent. return revealed !== null && revealed !== activeBranchMismatchKey ? null : revealed; }); }, [activeBranchMismatchKey, showBranchMismatchBanner]); const handleSwitchCheckoutToThread = useCallback(async () => { if ( !activeProjectCwd || !activeThread || !localCheckoutBranchMismatch || isRestoringThreadBranch ) { return; } setIsRestoringThreadBranch(true); const checkoutResult = await switchGitRef({ environmentId, input: { cwd: activeProjectCwd, refName: localCheckoutBranchMismatch.threadBranch, }, }); if (checkoutResult._tag === "Failure") { setIsRestoringThreadBranch(false); if (!isAtomCommandInterrupted(checkoutResult)) { toastManager.add( stackedThreadToast({ type: "error", title: "Failed to switch checkout", description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)), }), ); } return; } const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch; if (nextBranch !== activeThread.branch) { const updateResult = await updateThreadMetadata({ environmentId, input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null }, }); if (updateResult._tag === "Failure") { setIsRestoringThreadBranch(false); if (!isAtomCommandInterrupted(updateResult)) { toastManager.add( stackedThreadToast({ type: "error", title: "Checkout switched, but the thread could not be updated", description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)), }), ); } gitStatusQuery.refresh(); return; } } gitStatusQuery.refresh(); setIsRestoringThreadBranch(false); scheduleComposerFocus(); }, [ activeProjectCwd, activeThread, environmentId, gitStatusQuery, isRestoringThreadBranch, localCheckoutBranchMismatch, scheduleComposerFocus, switchGitRef, updateThreadMetadata, ]); // Background work (subagent fleets, workflow runs, watch loops) can outlive // the turn; once it settles, the composer stop button is gone, so this // banner is the only visible stop affordance. Stop routes through the // stop-everything interrupt: it kills every live background task before // interrupting, and works by session, so no active turn is needed. const activeBackgroundLiveness = !isWorking && activeThread ? (activeThreadShell?.backgroundLiveness ?? null) : null; const [isStoppingBackgroundWork, setIsStoppingBackgroundWork] = useState(false); useEffect(() => { // "Stopping..." holds until the liveness clears; the interrupt command // returning only means the request was accepted. if (activeBackgroundLiveness === null) { setIsStoppingBackgroundWork(false); } }, [activeBackgroundLiveness]); useEffect(() => { // Per-thread state: switching threads while A's stop is pending must not // disable B's Stop button (review finding). setIsStoppingBackgroundWork(false); }, [activeThreadId]); const handleStopBackgroundWork = useCallback(async () => { if (!activeThread) return; setIsStoppingBackgroundWork(true); const result = await interruptThreadTurn({ environmentId, input: buildThreadTurnInterruptInput(activeThread), }); if (result._tag === "Failure") { // Every failure clears the pending state — an interrupted command // never reached the server, so liveness would hold "Stopping..." // forever. Only real failures toast. setIsStoppingBackgroundWork(false); if (!isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); setThreadError( activeThread.id, error instanceof Error ? error.message : "Failed to stop background work.", ); } } }, [activeThread, environmentId, interruptThreadTurn, setThreadError]); const backgroundLivenessBannerItem = useMemo(() => { if (activeBackgroundLiveness === null || !activeThread) { return null; } const working = activeBackgroundLiveness === "working"; const liveCount = agentPanelModel.liveCount; return { id: `background-liveness:${activeThread.id}`, variant: "default", icon: (