The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 4,186 lines 177 KB
Raw
1 import { m } from "../i18n/messages";
2 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3 import { useGT, useMessages } from "gt-react";
4 import { ChildThreadApprovals } from "./chat/ChildThreadApprovals";
5 import { workspaceAreaProps } from "../lib/workspaceFocus";
6 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
7 import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";
8 import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit";
9 import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays";
10 import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer";
11 import { useFocusComposerOnThreadOpen } from "./chat/useFocusComposerOnThreadOpen";
12 import { configuredHostedAppUrl } from "../hostedPairing";
13 import {
14 announcedRun,
15 isDetailBehindShell,
16 } from "@t3tools/client-runtime/state/thread-activity-announcement";
17 import {
18 deriveAvailableRevertTurnCounts,
19 deriveThreadPendingBackgroundTasks,
20 presentThreadShellFromProjection,
21 } from "./ChatView.logic";
22 import { usePullRequestDraftThread } from "./chat/usePullRequestDraftThread";
23 import { usePullRequestLinking } from "../hooks/usePullRequestLinking";
24 import { useComposerSelection } from "./chat/useComposerSelection";
25 import { useComposerFocus } from "./chat/useComposerFocus";
26 import { useProjectCloneBanner } from "./chat/useProjectCloneBanner";
27 import { useAttachmentPreviewHandoff } from "./chat/useAttachmentPreviewHandoff";
28 import {
29 applyOptimisticUserMessagesAction,
30 createOptimisticBlobPreviews,
31 emptyOptimisticUserMessages,
32 reconcileOptimisticUserMessages,
33 } from "./chat/optimisticUserMessages";
34 import { useTimelineRewind } from "./chat/useTimelineRewind";
35 import { useThreadLifecycle } from "./chat/useThreadLifecycle";
36 import { useRightPanelActions } from "./chat/useRightPanelActions";
37 import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useChatTerminalActions";
38 import { useComposerSend } from "./chat/useComposerSend";
39 import { useComposerResume } from "./chat/useComposerResume";
40 import { ThreadFind, ThreadFindCanvas } from "./chat/ThreadFindProvider";
41 import { closeThreadFind, openThreadFind, useThreadFindOpen } from "./chat/threadFindStore";
42 import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";
43 import { useUsageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";
44 import {
45 isThreadEnvironmentLocked,
46 resolveDraftHeroState,
47 threadErrorIsServerRuntime,
48 } from "./ChatView.logic";
49 import { useQueuedRunEdit } from "./chat/useQueuedRunEdit";
50 import { recallCheckoutIsRepo, rememberCheckoutIsRepo } from "./ChatView.logic";
51 import { useLogicalProjectEnvironments } from "../hooks/useLogicalProjectEnvironments";
52 import { useStableCallback } from "../hooks/useStableCallback";
53 import { useProjectScriptEditing } from "./chat/useProjectScriptEditing";
54 import { RightPanelSurfaceContent } from "./chat/RightPanelSurfaceContent";
55 import { usePendingThreadRequests } from "./chat/usePendingThreadRequests";
56 import { isScratchProject } from "@t3tools/client-runtime/state/projects";
57 import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests";
58 import type { UsageLimitSourceSnapshots } from "@t3tools/contracts";
59 import { feedbackBannerItem } from "./chat/ComposerFeedback";
60 import { freshSessionBannerItem } from "./chat/ComposerFreshSession";
61 import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms";
62 import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";
63 import { useWorktreeSetup } from "./chat/useWorktreeSetup";
64 import { useChatShortcuts } from "./chat/useChatShortcuts";
65 import { ChatBannerLane } from "./chat/ChatBannerLane";
66 import * as Schema from "effect/Schema";
67 import {
68 AuthOrchestrationOperateScope,
69 AuthSourceControlWriteScope,
70 AuthPreviewOperateScope,
71 AuthTerminalOperateScope,
72 type AssistantCitation,
73 type ResponseContextRecord,
74 type ChatFileAttachment,
75 type EnvironmentId,
76 type MessageId,
77 type ModelSelection,
78 type PreviewAnnotationPayload,
79 ProviderInstanceId,
80 type ServerProvider,
81 type ScopedThreadRef,
82 type ThreadId,
83 ProviderInteractionMode,
84 resolveIdleCompaction,
85 RuntimeMode,
86 } from "@t3tools/contracts";
87 import {
88 canResumeThread,
89 deriveProviderSubagentStatus,
90 deriveProviderExtensionStatuses,
91 deriveReportedModelSelection,
92 deriveResumableRunId,
93 formatModelSelectionEffort,
94 deriveRunlessWorkStartedAt,
95 deriveThreadActivityRun,
96 deriveLatestThreadRun,
97 deriveThreadStructureRuntime,
98 limitRecoveryOwnsSnooze,
99 } from "@t3tools/client-runtime/state/thread-execution";
100 import {
101 resolveWorkflowOpening,
102 workflowOpeningParentThreadId,
103 } from "@t3tools/client-runtime/state/subagentRuntime";
104 import {
105 getUserQueuedThreadRuns,
106 threadSteersDuringCompaction,
107 threadSupportsProviderHandoff,
108 } from "@t3tools/client-runtime/state/thread-workflows";
109 import { compactionBlocksSteering } from "@t3tools/client-runtime/state/composer-dispatch";
110 import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
111 import { HandoffRow } from "./chat/V2LifecycleRow";
112 import {
113 codexFeedbackMessage,
114 deriveWorkspaceMutationId,
115 isCompleteTurnItemRow,
116 shouldShowLoadEarlierControl,
117 type CodexFeedbackSubmission,
118 } from "@t3tools/client-runtime/state/threads";
119 import {
120 parseScopedThreadKey,
121 scopedThreadKey,
122 scopeProjectRef,
123 scopeThreadRef,
124 } from "@t3tools/client-runtime/environment";
125 import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
126 import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts";
127 import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
128 import { orchestrationV2WorktreePending } from "@t3tools/shared/orchestrationV2ThreadError";
129 import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
130 import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabelsCopy";
131 import { useAtomValue } from "@effect/atom-react";
132 import {
133 type MouseEvent as ReactMouseEvent,
134 type SetStateAction,
135 use,
136 useEffect,
137 useLayoutEffect,
138 useRef,
139 useState,
140 } from "react";
141 import { BackgroundThreadContext } from "./chat/backgroundThread";
142 import { WorkspaceMutationIdContext } from "./chat/ChatMarkdownMedia";
143 import { useLocation, useNavigate } from "@tanstack/react-router";
144 import {
145 assistantCitationFromLocation,
146 useSideChatCitationReveal,
147 } from "../lib/assistantCitationNavigation";
148 import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
149 import { useStore } from "zustand";
150 import { shallow } from "zustand/vanilla/shallow";
151 import { useShallow } from "zustand/react/shallow";
152 import {
153 isAtomCommandInterrupted,
154 mapAtomCommandResult,
155 squashAtomCommandFailure,
156 type AtomCommandResult,
157 } from "@t3tools/client-runtime/state/runtime";
158 import { AsyncResult } from "effect/reactivity";
159 import { isElectron } from "../env";
160 import { useActiveThreadRef } from "../hooks/useActiveThreadRef";
161 import { composerRequiresModifier } from "../composer-logic";
162 import {
163 derivePhase,
164 deriveActiveWorkStartedAt,
165 deriveCanInterruptRunningThread,
166 findRevertCheckpoint,
167 isLatestRunSettled,
168 } from "../session-logic";
169 import { type LegendListRef } from "@legendapp/list/react";
170 import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
171 import { DEFAULT_INTERACTION_MODE, type ChatMessage } from "../types";
172 import { buildThreadRouteParams } from "../threadRoutes";
173 import { useTheme } from "../hooks/useTheme";
174 import { copyThreadReference } from "../lib/copyThreadReference";
175 import { subscribeSnapShotComposerFocus } from "../lib/desktopSnapShot";
176 import { useMediaQuery } from "../hooks/useMediaQuery";
177 import { FileMetadataThreadProvider } from "../hooks/FileMetadataThreadProvider";
178 import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
179 import { PopoverCreateHandle } from "./ui/popover";
180 import {
181 selectActiveRightPanel,
182 selectActiveRightPanelSurface,
183 selectThreadPanelOpen,
184 selectThreadRightPanelState,
185 useRightPanelStore,
186 } from "../rightPanelStore";
187 import { isPreviewSupportedInRuntime, useThreadPreviewState } from "../previewStateStore";
188 import { previewRuntimeTabId } from "../browser/previewRuntimeTabId";
189 import {
190 ThreadPreviewMiniPlayer,
191 useThreadPreviewCanvasSource,
192 } from "./preview/ThreadPreviewMiniPlayer";
193 import { createChatCanvasStore, resolveChatCanvasModel } from "./chat/canvasStore";
194 import { usePreviewSession } from "./preview/usePreviewSession";
195 import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic";
196
197 import {
198 previewMiniPlayerSourceKey,
199 selectThreadPreviewMiniPlayer,
200 usePreviewMiniPlayerStore,
201 } from "../previewMiniPlayerStore";
202 import { threadPullRequestPanelTarget } from "./pullRequest/pullRequestDetail.logic";
203 import { LinkPullRequestDialogHost } from "./pullRequest/LinkPullRequestDialog";
204 import { GuestPendingMessages } from "./chat/GuestShareControls";
205 import { useDeviceState } from "~/state/device";
206 import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar";
207 import { ComposerContextPermissions } from "./ComposerContextPermissions";
208 import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";
209 import { isEditableFocused } from "../lib/editableFocus";
210 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
211 import { shortcutLabelForCommand } from "../keybindings";
212 import { cn } from "~/lib/utils";
213 import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
214 import { toastManager } from "./ui/toast";
215 import { projectScriptIdFromCommand } from "~/projectScripts";
216 import { newMessageId } from "~/lib/utils";
217 import {
218 isInSideChatPane,
219 resolveThreadOpenRoute,
220 type SideChatParentPanel,
221 } from "~/lib/sideChatPane";
222 import {
223 NO_PROVIDER_MODEL_SELECTION,
224 providerInstanceEntriesFor,
225 resolveProjectDefaultProviderModelSelection,
226 shouldShowInstanceBadge,
227 } from "../providerInstances";
228 import {
229 useClientSettings,
230 useClientSettingsHydrated,
231 useEnvironmentSettings,
232 } from "../hooks/useSettings";
233 import { useNowMinute } from "../hooks/useNowMinute";
234 import { usePanelAnimationSettings, usePanelPresence } from "../panelAnimations";
235 import { useNewThreadHandler } from "../hooks/useHandleNewThread";
236 import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
237 import { isPreviewFocused } from "../lib/previewFocus";
238 import { getTerminalFocusOwner } from "../lib/terminalFocus";
239 import { draftModelSelectionApplies, threadHasStarted } from "../lib/chatThreadActions";
240 import {
241 deriveLogicalProjectKeyFromSettings,
242 selectProjectGroupingSettings,
243 } from "@t3tools/client-runtime/state/project-grouping";
244 import {
245 isSameSidebarThreadRef,
246 useSidebarPendingFileDropStore,
247 } from "../sidebarPendingFileDropStore";
248 import {
249 composerDraftHasUserContent,
250 type ComposerFileAttachment,
251 type ComposerImageAttachment,
252 type DraftThreadEnvMode,
253 useComposerDraftStore,
254 DraftId,
255 } from "../composerDraftStore";
256 import { type TerminalContextDraft } from "../lib/terminalContext";
257 import { collectInlineContextIds } from "../lib/composerContextReferences";
258 import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
259 import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";
260 import { useEnvironmentQueryRefresh } from "../state/query";
261 import { useEnvironmentScope } from "~/state/session";
262 import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server";
263 import { hostEnvironmentIdAtom } from "../state/primaryEnvironment";
264 import { threadEnvironment } from "../state/threads";
265 import {
266 resolveProviderSkillsForCwd,
267 resolveProvidersForCwd,
268 } from "@t3tools/client-runtime/providerSkills";
269 import { chatGitStatusAtom, NO_CHAT_GIT_STATUS_ATOM, vcsEnvironment } from "../state/vcs";
270 import {
271 type EnvironmentPresentation,
272 useEnvironment,
273 useEnvironmentProviders,
274 useEnvironments,
275 usePrimaryEnvironment,
276 } from "../state/environments";
277 import {
278 resolveThreadDetailRef,
279 useEnvironmentSupportsServerBrowser,
280 useProject,
281 useQuietThreadProjection,
282 useThreadUpdatedAt,
283 useThreadLastVisitedAt,
284 useQuietThreadVisibleTurnItems,
285 useThreadStatus,
286 useThreadHistory,
287 useQuietThreadShell,
288 useThreadCheckpointSummaries,
289 } from "../state/entities";
290 import { useEnvironmentShellHasSnapshot } from "../state/shell";
291 import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
292 import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";
293 import { ExpandedImageDialogHost, openExpandedImagePreview } from "./chat/ExpandedImageDialog";
294 import {
295 BranchRestoreConfirmHost,
296 DeviceSetupDialogHost,
297 openBranchRestoreConfirm,
298 PullRequestThreadDialogHost,
299 RevertConfirmHost,
300 } from "./chat/ChatOverlayHosts";
301 import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
302 import { useCitedHistory } from "./chat/citationProcedure";
303 import type { MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
304 import { ThreadTimeline } from "./chat/ThreadTimeline";
305 import { NativeChildWorkDialog } from "./chat/NativeChildWorkDialog";
306 import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
307 import { getTriggerDisplayModelName } from "./chat/providerIconUtils";
308 import { resolveScrollToEndClearance } from "./composerFooterLayout";
309 import { ChatHeader } from "./chat/ChatHeader";
310 import { useSideChat } from "./chat/useSideChat";
311 import { sideThreadComposer, sideThreadKindOf } from "@t3tools/client-runtime/side-thread";
312 import { useOpenSurfaceInMainView } from "../hooks/useOpenSurfaceInMainView";
313 import { useRemoteOpenState } from "~/remoteOpen";
314 import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic";
315 import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut";
316 import {
317 PanelLayoutControls,
318 type PanelLayoutControlsProps,
319 RightPanelMaximizeControl,
320 ThreadPanelHeaderControl,
321 WorkspaceTitlebarControls,
322 } from "./chat/PanelLayoutControls";
323 import type { ExpandedImagePreview } from "./chat/ExpandedImagePreview";
324 import { ThreadDetailsPanel } from "./chat/ThreadDetailsPanel";
325 import { NoActiveThreadState } from "./NoActiveThreadState";
326 import {
327 resolveEffectiveEnvMode,
328 resolveLocalCheckoutBranchMismatch,
329 shouldShowComposerContextStrip,
330 shouldShowEnvironmentIndicator,
331 } from "./BranchToolbar.logic";
332 import {
333 getProviderStatusDismissalKey,
334 shouldShowProviderStatusBanner,
335 useProviderStatusBannerDismissed,
336 } from "./chat/ProviderStatusBanner";
337 import {
338 getThreadErrorBannerKey,
339 isThreadErrorBannerDismissedForSession,
340 shouldShowThreadErrorBanner,
341 } from "./chat/ThreadErrorBanner";
342 import { QueuedRunsControl, type QueuedRunsControlHandle } from "./chat/QueuedRunsControl";
343 import { useThreadLinkedPullRequest } from "./pullRequest/useThreadLinkedPullRequest";
344 import { useProactivePanels } from "../hooks/useProactivePanels";
345 import { useIncrementalTimelineEntries } from "../hooks/useIncrementalTimelineEntries";
346 import { useRightPanelSurfaceClose } from "../hooks/useRightPanelSurfaceClose";
347 import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
348 import { modelFallbackBannerItem } from "./chat/ComposerUsageLimits";
349 import { ComposerSurface } from "./chat/ComposerSurface";
350 import { resolveThreadSyncPhase } from "../threadSync";
351 import { hasAvailableCompactionProvider } from "./chat/compaction.logic";
352 import {
353 deriveLatestContextWindowSnapshot,
354 hasDismissedResumeCompaction,
355 latestProviderTurnTokenUsage,
356 shouldOfferResumeCompaction,
357 } from "@t3tools/client-runtime/state/context-window";
358 import {
359 MOBILE_COMPOSER_VIEW_TRANSITION_NAME,
360 MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
361 } from "./chat/draftHeroTransition";
362 import {
363 buildLocalDraftThread,
364 deriveCommittedServerUserMessageIds,
365 deriveTimelineWorking,
366 dismissBranchMismatchForSession,
367 shouldRenderPreviewMiniPlayer,
368 deriveLockedProvider,
369 resolveFileAttachmentUrl,
370 resolveComposerProviderSelection,
371 resolveThreadMetadataUpdateForNextTurn,
372 resolveSendEnvMode,
373 startNewThreadForProject,
374 codexArtifactTemplatePromptToAppend,
375 shouldRefocusComposerOnWindowFocus,
376 hasCompactableConversation,
377 } from "./ChatView.logic";
378 import { useLocalStorage } from "~/hooks/useLocalStorage";
379 import { useComposerHandleContext } from "../composerHandleContext";
380 import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
381 import { appAtomRegistry } from "../rpc/atomRegistry";
382 import { assetEnvironment } from "../state/assets";
383 import { readEnvironmentScope, readPreparedConnection } from "../state/session";
384 import { useAtomCommand } from "../state/use-atom-command";
385 import { useOrchestrationCommand } from "../state/use-orchestration-command";
386 import { useAtomQueryRunner } from "../state/use-atom-query-runner";
387 import { observeResize } from "~/lib/observeResize";
388 import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
389 import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers";
390 import { ChatRightPanel } from "./chat/ChatRightPanel";
391 import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting";
392 import { branchMismatchBannerItem, extensionStatusBannerItem } from "./chat/ThreadActivityBanners";
393 import { ThreadNow } from "./chat/ThreadNow";
394 import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
395 import { useDelayedStatus } from "../hooks/useDelayedStatus";
396 import { useTimelineFollow } from "./chat/useTimelineFollow";
397 import {
398 type EnvironmentUnavailableState,
399 useSystemComposerBanners,
400 } from "./chat/useSystemComposerBanners";
401 import { useDraftHeroLayoutTransition } from "./chat/useDraftHeroLayoutTransition";
402 import { useLocalDispatchState } from "./chat/useLocalDispatchState";
403 import { draftFanoutSelectionsAtom, draftSendState } from "./chat/chatViewSend";
404 import {
405 isCompactCommandMessage,
406 type LocalThreadErrorEntry,
407 makeThreadErrorSetter,
408 } from "./ChatView.logic";
409
410 const EMPTY_PROVIDERS: ServerProvider[] = [];
411 const EMPTY_PROVIDER_MODELS: ServerProvider["models"] = [];
412 const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = [];
413 import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
414
415 const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];
416 const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
417 const EMPTY_TURN_ITEMS: ThreadStructure["turnItems"] = [];
418 const EMPTY_RUNS: ThreadStructure["runs"] = [];
419 const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray<EnvironmentPresentation> = [];
420 const EMPTY_COMPOSER_BANNER_ITEMS: ReadonlyArray<ComposerBannerStackItem> = [];
421
422 const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet<string> = new Set();
423
424 type ChatViewProps =
425 | {
426 environmentId: EnvironmentId;
427 threadId: ThreadId;
428 onDiffPanelOpen?: () => void;
429 reserveTitleBarControlInset?: boolean;
430 forceExpandedMobileComposer?: boolean;
431 /** A side chat in its parent's right panel; the parent keeps the keyboard and workspace UI. */
432 embedded?: SideChatParentPanel;
433 routeKind: "server";
434 draftId?: never;
435 }
436 | {
437 environmentId: EnvironmentId;
438 threadId: ThreadId;
439 onDiffPanelOpen?: () => void;
440 reserveTitleBarControlInset?: boolean;
441 forceExpandedMobileComposer?: boolean;
442 embedded?: never;
443 routeKind: "draft";
444 draftId: DraftId;
445 };
446
447 const DismissedFallbackWindowSchema = Schema.NullOr(Schema.String);
448
449 const ignoreComposerFocus = () => {};
450
451 export default function ChatView(props: ChatViewProps) {
452 const gt = useGT();
453 const messages = useMessages();
454 const {
455 environmentId,
456 threadId,
457 routeKind,
458 onDiffPanelOpen,
459 reserveTitleBarControlInset = true,
460 forceExpandedMobileComposer = false,
461 embedded: parentPanel,
462 } = props;
463 const embedded = parentPanel !== undefined;
464 const panelHostShell = useQuietThreadShell(parentPanel?.hostRef ?? null);
465 const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
466 const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
467 const draftId = routeKind === "draft" ? props.draftId : null;
468 const handleNewThread = useNewThreadHandler();
469 const routeThreadRef = scopeThreadRef(environmentId, threadId);
470 const routeThreadKey = scopedThreadKey(routeThreadRef);
471 const currentRouteThreadKeyRef = useRef<string | null>(routeThreadKey);
472 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed route thread key to a ref that async handlers check before applying results
473 useLayoutEffect(() => {
474 currentRouteThreadKeyRef.current = routeThreadKey;
475 return () => {
476 currentRouteThreadKeyRef.current = null;
477 };
478 }, [routeThreadKey]);
479 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
480 reportFailure: false,
481 });
482 const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope);
483 const setThreadRuntimeMode = useOrchestrationCommand(threadEnvironment.setRuntimeMode, {
484 reportFailure: false,
485 });
486 const setThreadInteractionMode = useOrchestrationCommand(threadEnvironment.setInteractionMode, {
487 reportFailure: false,
488 });
489 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
490 reportFailure: false,
491 });
492 const createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
493 reportFailure: false,
494 refresh: true,
495 });
496 const interruptThreadTurn = useOrchestrationCommand(threadEnvironment.interruptTurn, {
497 reportFailure: false,
498 });
499 const loadEarlierThreadHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
500 label: "load earlier thread history",
501 reportFailure: false,
502 });
503 const { environments } = useEnvironments();
504 const providersByEnvironment = useEnvironmentProviders();
505 const primaryEnvironment = usePrimaryEnvironment();
506 const environmentById = new Map(
507 environments.map((environment) => [environment.environmentId, environment]),
508 );
509 const baseComposerDraftTarget: ScopedThreadRef | DraftId =
510 routeKind === "server" ? routeThreadRef : props.draftId;
511 const draftThread = useComposerDraftStore((store) =>
512 routeKind === "server"
513 ? store.getDraftSessionByRef(routeThreadRef)
514 : draftId
515 ? store.getDraftSession(draftId)
516 : null,
517 );
518 const serverThreadShell = useQuietThreadShell(routeThreadRef);
519 const routeThreadDetailRef = resolveThreadDetailRef(routeThreadRef, {
520 shellExists: serverThreadShell !== null,
521 waitForShell: draftThread !== null,
522 });
523 const serverThreadProjection = useQuietThreadProjection(routeThreadDetailRef);
524 const serverProjection = serverThreadProjection?.projection ?? null;
525 // Only the shell-less fallback needs these; with a shell, the shell carries them.
526 const fallbackDetailRef = serverThreadShell === null ? routeThreadDetailRef : null;
527 const fallbackUpdatedAt = useThreadUpdatedAt(fallbackDetailRef);
528 const fallbackLastVisitedAt = useThreadLastVisitedAt(fallbackDetailRef);
529 const serverThread =
530 serverThreadShell !== null || serverProjection === null || fallbackUpdatedAt === null
531 ? serverThreadShell
532 : presentThreadShellFromProjection(environmentId, threadId, serverProjection, {
533 updatedAt: fallbackUpdatedAt,
534 lastVisitedAt: fallbackLastVisitedAt,
535 });
536 const promptRef = useRef("");
537 const localComposerRef = useRef<ChatComposerHandle | null>(null);
538 const composerRef = useComposerHandleContext() ?? localComposerRef;
539 const queuedRunEdit = useQueuedRunEdit({
540 environmentId,
541 routeThreadRef,
542 threadDraftTarget: baseComposerDraftTarget,
543 activeThreadId: serverThread !== null || draftThread !== null ? threadId : null,
544 serverProjection,
545 promptRef,
546 composerRef,
547 });
548 const composerDraftTarget = queuedRunEdit.draftTarget;
549 const reportedModelSelection = serverProjection
550 ? deriveReportedModelSelection(serverProjection)
551 : null;
552 const threadStatus = useThreadStatus(routeThreadDetailRef);
553 const threadSyncPhase = resolveThreadSyncPhase({
554 detailExists: serverProjection !== null,
555 shellExists: serverThread !== null,
556 status: threadStatus,
557 });
558 const threadDetailLoading = threadSyncPhase === "loading";
559 // Held back briefly, so a quick sync does not flash a status line at the end of the timeline.
560 const delayedThreadSyncPhase = useDelayedStatus(routeThreadKey, threadSyncPhase);
561 const activeProviderThread = serverProjection?.providerThreads.find(
562 (thread) => thread.id === serverProjection.thread.activeProviderThreadId,
563 );
564 const activeThreadLiveTokenUsage = latestProviderTurnTokenUsage(
565 serverProjection?.providerTurns ?? [],
566 serverProjection,
567 activeProviderThread,
568 );
569 const serverVisibleTurnItems = useQuietThreadVisibleTurnItems(routeThreadDetailRef);
570 const serverThreadHistory = useThreadHistory(routeThreadDetailRef);
571 const threadHistoryControls = (() => {
572 if (routeThreadDetailRef === null || !shouldShowLoadEarlierControl(serverThreadHistory)) {
573 return undefined;
574 }
575 return {
576 hasMoreHistory: serverThreadHistory.hasMoreHistory,
577 loading: serverThreadHistory.loading,
578 error: serverThreadHistory.error,
579 onLoadEarlier: (throughEntryId) => {
580 void loadEarlierThreadHistory({
581 environmentId: routeThreadDetailRef.environmentId,
582 input: {
583 threadId: routeThreadDetailRef.threadId,
584 ...(throughEntryId === undefined ? {} : { throughEntryId }),
585 },
586 });
587 },
588 };
589 })() as MessagesTimelineHistoryControls | undefined;
590 const committedServerMessageIds = deriveCommittedServerUserMessageIds(serverVisibleTurnItems);
591 // Queued messages have no turn item until starting, so cancellation must retire their optimistic rows
592 // separately.
593 const serverAcknowledgedUserMessageIds = (() => {
594 const ids = new Set(committedServerMessageIds);
595 for (const message of serverProjection?.messages ?? []) {
596 if (message.role === "user") ids.add(message.id);
597 }
598 return ids;
599 })();
600 const settings = useEnvironmentSettings(environmentId);
601 const clientSettingsHydrated = useClientSettingsHydrated();
602 const timestampFormat = settings.timestampFormat;
603 const navigate = useNavigate();
604 // Selects primitives: an object here is new on every router store update, which
605 // re-renders ChatView on unrelated navigation state changes.
606 const citationHref = useLocation({ select: (location) => location.href });
607 const citationKey = useLocation({
608 select: (location) => location.state.assistantCitationActivation ?? location.state.__TSR_key,
609 });
610 const citationLocation = { href: citationHref, key: citationKey };
611 const locationCitation = assistantCitationFromLocation(citationLocation.href);
612 const citationActivation = citationLocation.key ?? citationLocation.href;
613 const citationRequest = (
614 locationCitation &&
615 locationCitation.environmentId === environmentId &&
616 locationCitation.threadId === threadId
617 ? { citation: locationCitation, key: citationActivation }
618 : null
619 ) as AssistantCitationRequest | null;
620 useSideChatCitationReveal(embedded ? null : routeThreadRef, locationCitation, citationActivation);
621 const citationHistory = useCitedHistory(citationRequest);
622 const { resolvedTheme } = useTheme();
623 const composerRuntimeMode = useComposerDraftStore(
624 (store) => store.getComposerDraft(composerDraftTarget)?.runtimeMode ?? null,
625 );
626 const composerActiveProvider = useComposerDraftStore(
627 (store) => store.getComposerDraft(composerDraftTarget)?.activeProvider ?? null,
628 );
629 const composerModelSelectionExplicit = useComposerDraftStore(
630 (store) => store.getComposerDraft(composerDraftTarget)?.modelSelectionExplicit === true,
631 );
632 const composerSelectedModelSelection = useComposerDraftStore((store) => {
633 const draft = store.getComposerDraft(composerDraftTarget);
634 return draft?.activeProvider
635 ? (draft.modelSelectionByProvider[draft.activeProvider] ?? null)
636 : null;
637 });
638 const composerHasAttachments = useComposerDraftStore((store) => {
639 const draft = store.getComposerDraft(composerDraftTarget);
640 return (draft?.images.length ?? 0) > 0 || (draft?.files.length ?? 0) > 0;
641 });
642 const referencedThreadContexts = useComposerDraftStore(
643 useShallow((store) => {
644 const draft = store.getComposerDraft(composerDraftTarget);
645 if (!draft?.threadContexts.length) return [];
646 // Linked prompts can replace text without pruning stored context records.
647 const referenced = new Set(collectInlineContextIds(draft.prompt));
648 return draft.threadContexts.filter((record) => referenced.has(record.contextId));
649 }),
650 );
651 const composerHasNonPromptContent = useComposerDraftStore((store) => {
652 const draft = store.getComposerDraft(composerDraftTarget);
653 return draft ? composerDraftHasUserContent({ ...draft, prompt: "" }) : false;
654 });
655 const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
656 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
657 const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
658 const composerFilesRef = useRef<ComposerFileAttachment[]>([]);
659 const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
660 const branchToolbarRef = useRef<BranchToolbarHandle>(null);
661 const citeAssistantText = (
662 citation: AssistantCitation,
663 sourceAnchor: AssistantCitationSourceAnchor,
664 ) => {
665 const inserted = composerRef.current?.citeAssistantText(citation, sourceAnchor) ?? false;
666 if (!inserted) {
667 toastManager.add({
668 type: "warning",
669 title: gt("The composer is not ready"),
670 description: gt(
671 "Try citing the selection after the connection or pending input is resolved.",
672 ),
673 });
674 }
675 return inserted;
676 };
677 const citeAssistantTextStable = useStableCallback(citeAssistantText);
678 const replyToResponseStable = useStableCallback((response: ResponseContextRecord) => {
679 const accepted = composerRef.current?.replyToResponse(response) ?? false;
680 if (!accepted) {
681 toastManager.add({
682 type: "warning",
683 title: gt("The composer is not ready"),
684 description: gt("Try replying after the connection or pending input is resolved."),
685 });
686 }
687 return accepted;
688 });
689 const [isWorkspaceFileDragActive, setIsWorkspaceFileDragActive] = useState(false);
690 const [optimisticBlobPreviews] = useState(createOptimisticBlobPreviews);
691 const [heldOptimisticUserMessages, setHeldOptimisticUserMessages] = useState(() =>
692 emptyOptimisticUserMessages(threadId),
693 );
694 // Acknowledged messages leave the timeline in the same render the server's copy enters it.
695 const optimisticState = reconcileOptimisticUserMessages(
696 heldOptimisticUserMessages,
697 threadId,
698 serverAcknowledgedUserMessageIds,
699 );
700 if (optimisticState !== heldOptimisticUserMessages) {
701 // Idempotent, and a discarded render only delays revocation to the thread's end.
702 optimisticBlobPreviews.handOff(optimisticState);
703 setHeldOptimisticUserMessages(optimisticState);
704 }
705 const optimisticUserMessages = optimisticState.messages;
706 const setOptimisticUserMessages = (action: SetStateAction<ChatMessage[]>) =>
707 setHeldOptimisticUserMessages((state) =>
708 applyOptimisticUserMessagesAction(state, threadId, action),
709 );
710 // Draft ids survive promotion and expire on navigation, keeping the pending resend scoped correctly.
711 const [workLocallyResendDraftId, setWorkLocallyResendDraftId] = useState<DraftId | null>(null);
712 const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
713 Record<string, ReadonlyArray<CodexFeedbackSubmission>>
714 >({});
715 const feedbackSubmissions =
716 feedbackSubmissionsByThreadKey[routeThreadKey] ?? EMPTY_FEEDBACK_SUBMISSIONS;
717 const feedbackUploading = feedbackSubmissions.some(
718 (submission) => submission.status === "uploading",
719 );
720 const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState<
721 Record<string, LocalThreadErrorEntry>
722 >({});
723 const [localServerErrorsByThreadKey, setLocalServerErrorsByThreadKey] = useState<
724 Record<string, LocalThreadErrorEntry>
725 >({});
726 const isRevertingCheckpoint = useComposerDraftStore((store) =>
727 store.rewindingThreadKeys.has(routeThreadKey),
728 );
729
730 const workspaceFileDragRouteKey = `${routeThreadKey}:${draftId ?? ""}`;
731 const [workspaceFileDragRoute, setWorkspaceFileDragRoute] = useState(workspaceFileDragRouteKey);
732 if (workspaceFileDragRoute !== workspaceFileDragRouteKey) {
733 setWorkspaceFileDragRoute(workspaceFileDragRouteKey);
734 setIsWorkspaceFileDragActive(false);
735 }
736
737 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window dragend listener that clears the workspace file drag state
738 useEffect(() => {
739 if (!isWorkspaceFileDragActive) return;
740 const clearWorkspaceFileDrag = () => setIsWorkspaceFileDragActive(false);
741 window.addEventListener("dragend", clearWorkspaceFileDrag);
742 return () => window.removeEventListener("dragend", clearWorkspaceFileDrag);
743 }, [isWorkspaceFileDragActive]);
744 const prefersPlanSidebarSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);
745 const isMobileViewport = useMediaQuery("max-sm");
746 // Focusing the composer without a tap raises the on-screen keyboard on touch devices.
747 const isCoarsePointer = useMediaQuery({ pointer: "coarse" });
748 const [workspaceLayoutElement, setWorkspaceLayoutElement] = useState<HTMLDivElement | null>(null);
749 const threadPanelPopoverAnchorRef = useRef<HTMLElement | null>(null);
750 const [terminalUiLaunchContext, setTerminalUiLaunchContext] =
751 useState<TerminalLaunchContext | null>(null);
752 // Overrides chosen before a server thread's first turn; they belong to that thread only.
753 const [pendingServerThreadEnvModeEntry, setPendingServerThreadEnvModeEntry] = useState<{
754 readonly threadId: ThreadId;
755 readonly mode: DraftThreadEnvMode;
756 } | null>(null);
757 const [pendingServerThreadBranchEntry, setPendingServerThreadBranchEntry] = useState<{
758 readonly threadId: ThreadId;
759 readonly branch: string | null;
760 } | null>(null);
761 const [
762 pendingServerThreadStartFromOriginByThreadId,
763 setPendingServerThreadStartFromOriginByThreadId,
764 ] = useState<Record<string, boolean>>({});
765 const legendListRef = useRef<LegendListRef | null>(null);
766 const conversationArea = workspaceAreaProps("conversation", 1, gt("Conversation"));
767 const [composerOverlayElement, setComposerOverlayElement] = useState<HTMLDivElement | null>(null);
768 const [composerTimelineInset, setComposerTimelineInset] = useState(0);
769 const composerTimelineInsetRef = useRef(0);
770 const [composerReservedHeight, setComposerReservedHeight] = useState(0);
771 const composerReservedHeightRef = useRef(0);
772 const composerExpandedHeightRef = useRef(0);
773 const [scrollToEndClearance, setScrollToEndClearance] = useState(0);
774 const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey);
775 const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
776 const multipleModelSelections = useAtomValue(fanoutSelectionsAtom);
777 const setMultipleModelSelections = (
778 selections: SetStateAction<ReadonlyArray<ModelSelection> | null>,
779 ) => {
780 appAtomRegistry.update(fanoutSelectionsAtom, (current) =>
781 typeof selections === "function" ? selections(current) : selections,
782 );
783 };
784 const setMultipleModelSelectionsStable = useStableCallback(setMultipleModelSelections);
785 const feedbackUploadsInFlightRef = useRef(new Set<string>());
786
787 const terminalUiState = useTerminalUiStateStore((state) =>
788 selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef),
789 );
790
791 const fallbackDraftProjectRef = draftThread
792 ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
793 : null;
794 const fallbackDraftProject = useProject(fallbackDraftProjectRef);
795 const localDraftError = serverThread
796 ? null
797 : ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null);
798 const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null;
799 const promotedDraftError =
800 serverThread && draftId ? localDraftErrorsByDraftId[draftId] : undefined;
801 if (promotedDraftError !== undefined && draftId) {
802 const remainingDraftErrors = { ...localDraftErrorsByDraftId };
803 delete remainingDraftErrors[draftId];
804 setLocalDraftErrorsByDraftId(remainingDraftErrors);
805 const currentEntry = localServerErrorsByThreadKey[routeThreadKey];
806 if (
807 currentEntry === undefined ||
808 (currentEntry.at <= promotedDraftError.at &&
809 currentEntry.message !== promotedDraftError.message)
810 ) {
811 setLocalServerErrorsByThreadKey({
812 ...localServerErrorsByThreadKey,
813 [routeThreadKey]: promotedDraftError,
814 });
815 }
816 }
817 const nowMinute = useNowMinute();
818 const draftDefaultModelSelection = draftThread
819 ? resolveProjectSettings(
820 settings,
821 fallbackDraftProject?.id ?? null,
822 fallbackDraftProject ?? undefined,
823 ).settings.defaultModelSelection
824 : null;
825 const draftModelResolution = draftThread
826 ? resolveNewThreadModelSelection({
827 defaultSelection:
828 draftDefaultModelSelection ??
829 resolveProjectDefaultProviderModelSelection(
830 providersByEnvironment.get(draftThread.environmentId) ?? [],
831 settings,
832 draftThread.projectId,
833 ),
834 fallbackSelection: settings.fallbackModelSelection,
835 providers: providersByEnvironment.get(draftThread.environmentId) ?? [],
836 settings,
837 projectId: draftThread.projectId,
838 now: Date.parse(`${nowMinute}:00Z`),
839 })
840 : null;
841 const draftFallback = draftModelResolution?.fallback ? draftModelResolution : null;
842 const localDraftThread = draftThread
843 ? buildLocalDraftThread(
844 threadId,
845 draftThread,
846 (draftFallback ? draftFallback.selection : draftDefaultModelSelection) ??
847 NO_PROVIDER_MODEL_SELECTION,
848 messages,
849 )
850 : undefined;
851 const isServerThread = serverThread !== null;
852 const activeThread = isServerThread ? serverThread : localDraftThread;
853 const serverLatestRun =
854 serverProjection === null ? null : deriveLatestThreadRun(serverProjection);
855 const serverActivityRun =
856 serverProjection === null ? null : deriveThreadActivityRun(serverProjection);
857 const serverRuntime =
858 serverProjection === null ? null : deriveThreadStructureRuntime(serverProjection);
859 const runlessWorkStartedAt =
860 serverProjection === null ? null : deriveRunlessWorkStartedAt(serverProjection);
861 const providerSubagentStatus =
862 serverProjection === null ? null : deriveProviderSubagentStatus(serverProjection);
863 const sideThreadKind = serverThread === null ? null : sideThreadKindOf(serverThread.source);
864 const isProviderSubagent =
865 sideThreadKind !== null && sideThreadComposer(sideThreadKind) === "read-only";
866 const supportsProviderSwitchingViaHandoff = threadSupportsProviderHandoff(serverProjection);
867 const activeLatestRun = isServerThread ? serverLatestRun : (activeThread?.latestRun ?? null);
868 const activeActivityRun = isServerThread ? serverActivityRun : (activeThread?.latestRun ?? null);
869 const activeRuntime = isServerThread ? serverRuntime : (activeThread?.runtime ?? null);
870 const hasHeldQueuedRuns =
871 isServerThread &&
872 serverProjection?.runs.some((run) => run.status === "queued" && run.queueHeld === true) ===
873 true;
874 const resumableRunId =
875 !isServerThread || serverProjection === null
876 ? null
877 : deriveResumableRunId(serverProjection, serverRuntime);
878 const canResume =
879 serverProjection !== null &&
880 canResumeThread(serverProjection, resumableRunId, hasHeldQueuedRuns);
881 const parentSubagentThreadId =
882 activeThread?.lineage.relationshipToParent === "subagent"
883 ? activeThread.lineage.parentThreadId
884 : null;
885 const parentSubagentEnvironmentId = activeThread?.environmentId ?? null;
886 const parentSubagentThreadRef = (() => {
887 if (parentSubagentEnvironmentId === null || parentSubagentThreadId === null) {
888 return null;
889 }
890 return scopeThreadRef(parentSubagentEnvironmentId, parentSubagentThreadId);
891 })();
892 const parentSubagentThread = useQuietThreadShell(parentSubagentThreadRef);
893 // Workflow threads open with a script; their replacement plan lives on the parent's coordinator row.
894 const workflowOpeningParentId =
895 serverProjection === null
896 ? null
897 : workflowOpeningParentThreadId({
898 thread: serverProjection.thread,
899 messages: serverProjection.messages,
900 });
901 const workflowOpeningParentProjection = useQuietThreadProjection(
902 workflowOpeningParentId === null || parentSubagentEnvironmentId === null
903 ? null
904 : scopeThreadRef(parentSubagentEnvironmentId, workflowOpeningParentId),
905 );
906 const workflowOpening =
907 serverProjection === null || workflowOpeningParentId === null
908 ? null
909 : resolveWorkflowOpening(
910 {
911 thread: serverProjection.thread,
912 messages: serverProjection.messages,
913 parentSubagents: workflowOpeningParentProjection?.projection.subagents ?? null,
914 },
915 messages,
916 );
917 // A linked environment's agent may have delegated this thread from there.
918 const delegatedFrom = activeThread?.delegatedFrom ?? null;
919 const delegatedFromEnvironment = useEnvironment(delegatedFrom?.environmentId ?? null);
920 const delegatedFromRef =
921 delegatedFrom === null
922 ? null
923 : scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
924 // The title it had at delegation, until this client sees the parent itself.
925 const delegatedFromThread = useQuietThreadShell(delegatedFromRef);
926 const sideChatParentRef =
927 activeThread?.lineage.sideChat === true && activeThread.lineage.parentThreadId !== null
928 ? scopeThreadRef(activeThread.environmentId, activeThread.lineage.parentThreadId)
929 : null;
930 const sideChatParent = useQuietThreadShell(sideChatParentRef);
931 const parentThreadLink = (() => {
932 if (sideChatParentRef !== null) {
933 const title = sideChatParent?.title ?? gt("Parent thread");
934 // Embedded, the parent is the view around it.
935 if (embedded) return { title, sideChat: true };
936 return {
937 title,
938 sideChat: true,
939 open: (): void => {
940 void navigate({
941 to: "/$environmentId/$threadId",
942 params: buildThreadRouteParams(sideChatParentRef),
943 });
944 },
945 };
946 }
947 if (parentSubagentThreadRef !== null) {
948 const title = parentSubagentThread?.title ?? gt("Parent thread");
949 // Embedded in its parent's panel, the parent is the view around it.
950 if (
951 parentPanel !== undefined &&
952 scopedThreadKey(parentPanel.hostRef) === scopedThreadKey(parentSubagentThreadRef)
953 ) {
954 return { title };
955 }
956 return {
957 title,
958 open: (): void => {
959 void navigate({
960 to: "/$environmentId/$threadId",
961 params: buildThreadRouteParams(
962 resolveThreadOpenRoute(parentSubagentThreadRef, parentSubagentThread),
963 ),
964 });
965 },
966 };
967 }
968 if (delegatedFrom === null || delegatedFromRef === null) return null;
969 const parentRef = delegatedFromRef;
970 return {
971 title: delegatedFromThread?.title ?? delegatedFrom.title,
972 environmentLabel: delegatedFromEnvironment?.label ?? activeThread?.linkOrigin?.label ?? "",
973 // Only an environment this client is connected to can open the parent.
974 ...(delegatedFromEnvironment === null
975 ? {}
976 : {
977 open: (): void => {
978 void navigate({
979 to: "/$environmentId/$threadId",
980 params: buildThreadRouteParams(parentRef),
981 });
982 },
983 }),
984 };
985 })();
986 // The header's breadcrumb opens a parent in this environment only.
987 const headerParentThreadLink =
988 parentSubagentThreadRef === null
989 ? null
990 : {
991 threadId: parentSubagentThreadRef.threadId,
992 title: parentSubagentThread?.title ?? gt("Parent thread"),
993 };
994 const threadError = isServerThread
995 ? (localServerError ?? serverRuntime?.lastError ?? null)
996 : localDraftError;
997 const threadErrorBannerKey = getThreadErrorBannerKey(
998 routeThreadKey,
999 threadError,
1000 threadErrorIsServerRuntime({
1001 isServerThread,
1002 localServerError,
1003 runtimeError: serverRuntime?.lastError ?? null,
1004 })
1005 ? (serverRuntime?.lastErrorSource ?? null)
1006 : null,
1007 );
1008 const visibleThreadError = shouldShowThreadErrorBanner(
1009 routeThreadKey,
1010 threadError,
1011 isThreadErrorBannerDismissedForSession(threadErrorBannerKey),
1012 )
1013 ? threadError
1014 : null;
1015 const [, setThreadErrorBannerDismissTick] = useState(0);
1016 const threadErrorIsServerRuntimeError =
1017 localServerError === null && visibleThreadError === serverRuntime?.lastError;
1018 const defaultRuntimeMode = resolveProjectSettings(settings, activeThread?.projectId ?? null)
1019 .settings.defaultRuntimeMode;
1020 const runtimeMode =
1021 composerRuntimeMode ??
1022 (isServerThread ? activeThread?.runtimeMode : undefined) ??
1023 defaultRuntimeMode;
1024 const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
1025 const canCheckoutPullRequestIntoThread = canWriteSourceControl && isLocalDraftThread;
1026 const activeThreadId = activeThread?.id ?? null;
1027 // Turn items can lag projection hydration; keep the environment locked through that gap.
1028 const activeMessageCount = isServerThread
1029 ? Math.max(committedServerMessageIds.size, serverProjection?.messages.length ?? 0)
1030 : 0;
1031 const runningTerminalIds = useThreadRunningTerminalIds({
1032 environmentId: activeThread?.environmentId ?? null,
1033 threadId: activeThreadId,
1034 });
1035 const activeThreadKnownSessionsRaw = useKnownTerminalSessions({
1036 environmentId: activeThread?.environmentId ?? null,
1037 threadId: activeThreadId,
1038 });
1039 const activeThreadKnownSessions = (() => {
1040 if (activeThreadId === null || activeThreadKnownSessionsRaw === null) {
1041 return [];
1042 }
1043 return activeThreadKnownSessionsRaw.filter(
1044 (session) => session.target.threadId === activeThreadId,
1045 );
1046 })();
1047 const activeServerOrderedTerminalIds = activeThreadKnownSessions.map(
1048 (session) => session.target.terminalId,
1049 );
1050 const activeTerminalLabelsById = (() => {
1051 const labels = new Map<string, string>();
1052 for (const session of activeThreadKnownSessions) {
1053 labels.set(
1054 session.target.terminalId,
1055 resolveTerminalSessionLabel(session.target.terminalId, session.state.summary, messages),
1056 );
1057 }
1058 return labels;
1059 })();
1060 const activeThreadRef = useActiveThreadRef(activeThread);
1061 const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
1062 const activeEnvironmentServerBrowser = useEnvironmentSupportsServerBrowser(
1063 activeThreadRef?.environmentId ?? null,
1064 );
1065 const browserAvailable = isPreviewSupportedInRuntime() || activeEnvironmentServerBrowser;
1066 const activeThreadShell = serverThread;
1067 const limitRecoveryRun =
1068 serverRuntime?.status === "failed" && serverRuntime.lastErrorClass === "usage_limit"
1069 ? (activeThreadShell?.latestRun ?? null)
1070 : null;
1071 // The recovery banner offers Wake now for a snooze it set.
1072 const limitRecoveryHoldsSnooze = limitRecoveryOwnsSnooze({
1073 runId: limitRecoveryRun?.runId,
1074 resetAt: serverRuntime?.usageLimitResetAt,
1075 recovery: activeThreadShell?.limitRecovery,
1076 snoozedUntil: activeThreadShell?.snoozedUntil,
1077 });
1078 const timelineThreadError =
1079 limitRecoveryRun !== null && visibleThreadError === serverRuntime?.lastError
1080 ? null
1081 : visibleThreadError;
1082
1083 const [timelineAnchor, setTimelineAnchor] = useState<{
1084 readonly threadKey: string | null;
1085 readonly messageId: MessageId | null;
1086 }>({ threadKey: activeThreadKey, messageId: null });
1087 if (timelineAnchor.threadKey !== activeThreadKey) {
1088 setTimelineAnchor({ threadKey: activeThreadKey, messageId: null });
1089 }
1090 const timelineAnchorMessageId = timelineAnchor.messageId;
1091 // LegendList never recomputes anchored end-space geometry, leaving phantom scroll range after content fits.
1092 const anchorRunSettled = (() => {
1093 if (timelineAnchorMessageId === null) return false;
1094 const anchorRun = serverProjection?.runs.find(
1095 (run) => run.userMessageId === timelineAnchorMessageId,
1096 );
1097 if (anchorRun === undefined) return false;
1098 return (
1099 anchorRun.status !== "preparing" &&
1100 anchorRun.status !== "queued" &&
1101 anchorRun.status !== "starting" &&
1102 anchorRun.status !== "running" &&
1103 anchorRun.status !== "waiting"
1104 );
1105 })();
1106 if (anchorRunSettled) {
1107 setTimelineAnchor({ threadKey: activeThreadKey, messageId: null });
1108 }
1109 const activeRightPanelKind = useRightPanelStore((state) =>
1110 selectActiveRightPanel(state.byThreadKey, activeThreadRef),
1111 );
1112 const diffOpen = activeRightPanelKind === "diff";
1113 const rightPanelState = useRightPanelStore((state) =>
1114 selectThreadRightPanelState(state.byThreadKey, activeThreadRef),
1115 );
1116 const shouldUsePlanSidebarSheet = prefersPlanSidebarSheet && rightPanelState.maximized !== true;
1117 const activeRightPanelSurface = useRightPanelStore((state) =>
1118 selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef),
1119 );
1120 const activePreviewState = useThreadPreviewState(activeThreadRef);
1121 const activePreviewServerEpoch = activePreviewState.serverEpoch;
1122 const resolvePreviewRuntimeTabId = activeThreadRef
1123 ? (tabId: string) => previewRuntimeTabId(activeThreadRef, activePreviewServerEpoch, tabId)
1124 : undefined;
1125 const activePreviewMiniPlayer = usePreviewMiniPlayerStore((state) =>
1126 selectThreadPreviewMiniPlayer(state.byThreadKey, activeThreadRef),
1127 );
1128 const panelTerminalIds = new Set(
1129 rightPanelState.surfaces.flatMap((surface) =>
1130 surface.kind === "terminal" ? surface.terminalIds : [],
1131 ),
1132 );
1133 const canReuseTerminal = activeThreadKnownSessionsRaw !== null;
1134 const previewPanelOpen = activeRightPanelKind === "preview" && browserAvailable;
1135 const rightPanelOpen = rightPanelState.isOpen;
1136 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
1137 usePanelAnimationSettings();
1138 const rightPanelPresenceValue = {
1139 activeSurface: activeRightPanelSurface,
1140 surfaces: rightPanelState.surfaces,
1141 };
1142 const rightPanelPresence = usePanelPresence(
1143 rightPanelOpen && activeThreadRef !== null,
1144 rightPanelPresenceValue,
1145 panelAnimationsActive,
1146 activeThreadKey,
1147 panelAnimationDurationMs,
1148 );
1149 const rightPanelPresent = rightPanelPresence.present;
1150 const rightPanelControlsInPanel =
1151 shouldUsePlanSidebarSheet && rightPanelPresent && rightPanelOpen;
1152 const rightPanelControlsAtRoot = rightPanelPresent && !shouldUsePlanSidebarSheet;
1153 const renderedRightPanelSurface = rightPanelPresence.value?.activeSurface ?? null;
1154 const renderedRightPanelSurfaces = rightPanelPresence.value?.surfaces ?? [];
1155 const previewMiniPlayerVisible = shouldRenderPreviewMiniPlayer(
1156 activePreviewMiniPlayer?.source ?? null,
1157 renderedRightPanelSurface,
1158 );
1159 const canMaximizeRightPanel = rightPanelOpen;
1160 // An embedded side chat has no panel; a stale maximized flag would hide its own column.
1161 const rightPanelMaximized =
1162 !embedded && canMaximizeRightPanel && rightPanelState.maximized === true;
1163 const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet;
1164 const [threadPanelPopoverHandle] = useState(PopoverCreateHandle);
1165 const [chatCanvasStore] = useState(createChatCanvasStore);
1166
1167 const latestRunSettled = isLatestRunSettled(activeLatestRun, activeRuntime);
1168 const activeThreadEnvironmentId = activeThread?.environmentId;
1169 const activeThreadProjectId = activeThread?.projectId;
1170 const activeProjectRef =
1171 activeThreadEnvironmentId !== undefined && activeThreadProjectId !== undefined
1172 ? scopeProjectRef(activeThreadEnvironmentId, activeThreadProjectId)
1173 : null;
1174 const activeProject = useProject(activeProjectRef);
1175 const activeProjectSettings = resolveProjectSettings(
1176 settings,
1177 activeProject?.id ?? null,
1178 activeProject ?? undefined,
1179 );
1180 const activeProjectScripts = activeProject ? resolveProjectScripts(settings, activeProject) : [];
1181 const { projectCloneBannerItem, projectCloneSendBlockReason } =
1182 useProjectCloneBanner(activeProjectRef);
1183 const activeProjectDefaultModelSelection =
1184 !isServerThread && draftFallback
1185 ? draftFallback.selection
1186 : activeProjectSettings.settings.defaultModelSelection;
1187 const handleNewThreadInActiveProject = () => {
1188 startNewThreadForProject(activeProjectRef, handleNewThread);
1189 };
1190 const handleNewThreadInActiveProjectStable = useStableCallback(handleNewThreadInActiveProject);
1191 const projectGroupingSettings = selectProjectGroupingSettings(settings);
1192 const activeDraftLogicalProjectKey =
1193 !isServerThread && activeProject
1194 ? deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings)
1195 : undefined;
1196 const handleOpenDraftProjectSettings = () => {
1197 if (!activeDraftLogicalProjectKey) return;
1198 void navigate({
1199 to: "/projects/$projectKey",
1200 params: { projectKey: activeDraftLogicalProjectKey },
1201 });
1202 };
1203 const handleOpenDraftProjectSettingsStable = useStableCallback(handleOpenDraftProjectSettings);
1204 const activeEnvironmentBootstrapComplete = useEnvironmentShellHasSnapshot(
1205 activeThread?.environmentId ?? null,
1206 );
1207 const activeProjectKey = activeProject
1208 ? `${activeProject.environmentId}:${activeProject.workspaceRoot}`
1209 : null;
1210 const [pendingFileSurfaceIdsByProject, setPendingFileSurfaceIdsByProject] = useState<
1211 ReadonlyMap<string, ReadonlySet<string>>
1212 >(() => new Map());
1213 const pendingFileSurfaceIds = activeProjectKey
1214 ? (pendingFileSurfaceIdsByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS)
1215 : EMPTY_PENDING_FILE_SURFACE_IDS;
1216 const handleFilePendingChange = (relativePath: string, pending: boolean) => {
1217 if (!activeProjectKey) return;
1218 setPendingFileSurfaceIdsByProject((currentByProject) => {
1219 const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS;
1220 const surfaceId = `file:${relativePath}`;
1221 if (current.has(surfaceId) === pending) return currentByProject;
1222 const next = new Set(current);
1223 if (pending) next.add(surfaceId);
1224 else next.delete(surfaceId);
1225 const nextByProject = new Map(currentByProject);
1226 if (next.size === 0) nextByProject.delete(activeProjectKey);
1227 else nextByProject.set(activeProjectKey, next);
1228 return nextByProject;
1229 });
1230 };
1231 const handleFilePendingChangeStable = useStableCallback(handleFilePendingChange);
1232 const configuredPreviewUrls = getConfiguredPreviewUrls(activeProjectScripts);
1233
1234 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- drops file surfaces from the right panel store once bootstrap shows the thread has no workspace
1235 useEffect(() => {
1236 if (!activeThreadRef || !activeEnvironmentBootstrapComplete) return;
1237 useRightPanelStore.getState().reconcileFileSurfaces(activeThreadRef, activeProject !== null);
1238 }, [activeEnvironmentBootstrapComplete, activeProject, activeThreadRef]);
1239
1240 const activeEnvironment =
1241 activeThread == null ? null : (environmentById.get(activeThread.environmentId) ?? null);
1242 const activeEnvironmentUnavailable =
1243 activeEnvironment !== null && activeEnvironment.connection.phase !== "connected";
1244 const activeEnvironmentUnavailableLabel = activeEnvironment?.label ?? null;
1245 const activeEnvironmentUnavailableState = (() => {
1246 if (!activeEnvironmentUnavailable || !activeEnvironmentUnavailableLabel || !activeEnvironment) {
1247 return null;
1248 }
1249
1250 return {
1251 environmentId: activeEnvironment.environmentId,
1252 label: activeEnvironmentUnavailableLabel,
1253 connection: activeEnvironment.connection,
1254 };
1255 })() as EnvironmentUnavailableState | null;
1256 const activeProjectIsScratch =
1257 activeProject !== null &&
1258 isScratchProject(
1259 activeProject,
1260 environmentById.get(activeProject.environmentId)?.serverConfig?.scratchWorkspaceRoot ?? null,
1261 );
1262 const logicalProjectEnvironments = useLogicalProjectEnvironments(
1263 activeProject,
1264 activeProjectIsScratch && draftId !== null,
1265 );
1266 const hasMultipleEnvironments = logicalProjectEnvironments.length > 1;
1267 const canAutoBalanceEnvironments = hasMultipleEnvironments && !activeProjectIsScratch;
1268 const activeEnvironmentOption =
1269 logicalProjectEnvironments.find(
1270 (environment) => environment.environmentId === activeThread?.environmentId,
1271 ) ?? null;
1272 const showComposerEnvironmentIndicator = shouldShowEnvironmentIndicator({
1273 activeEnvironment: activeEnvironmentOption,
1274 canPickEnvironment: hasMultipleEnvironments,
1275 });
1276
1277 const pullRequestLinking = usePullRequestLinking(environmentId);
1278 // Best effort: the thread already exists, so a failed link is only logged.
1279 const linkCheckoutPullRequest = useStableCallback((threadRef: ScopedThreadRef, url: string) => {
1280 pullRequestLinking.changeLink(threadRef, url, true).catch((error: unknown) => {
1281 console.warn("Failed to link the checked-out pull request to its thread.", error);
1282 });
1283 });
1284 const { handlePreparedPullRequestThreadStable, openPullRequestDialogStable } =
1285 usePullRequestDraftThread({
1286 routeKind,
1287 draftId,
1288 settings,
1289 projectGroupingSettings,
1290 activeProject,
1291 activeThreadKey,
1292 isServerThread,
1293 canCheckoutPullRequestIntoThread,
1294 });
1295 const serverConfig = activeThread
1296 ? (activeEnvironment?.serverConfig ?? null)
1297 : (primaryEnvironment?.serverConfig ?? null);
1298 const providerEnvironmentId = (activeThread ? activeEnvironment : primaryEnvironment)
1299 ?.environmentId;
1300 const gitCwd = activeProject
1301 ? projectScriptCwd({
1302 project: { cwd: activeProject.workspaceRoot },
1303 worktreePath: activeThread?.worktreePath ?? null,
1304 })
1305 : null;
1306 const providerStatuses = resolveProvidersForCwd(
1307 (providerEnvironmentId === undefined
1308 ? undefined
1309 : providersByEnvironment.get(providerEnvironmentId)) ?? EMPTY_PROVIDERS,
1310 gitCwd,
1311 );
1312 const composerModelSelectionApplies = draftModelSelectionApplies(
1313 { modelSelectionExplicit: composerModelSelectionExplicit },
1314 threadHasStarted(activeThread),
1315 );
1316 const selectedProviderByThreadId = composerModelSelectionApplies ? composerActiveProvider : null;
1317 const threadProvider =
1318 activeThread?.modelSelection.instanceId ??
1319 activeProjectDefaultModelSelection?.instanceId ??
1320 null;
1321 const lockedProvider = deriveLockedProvider({
1322 thread: activeThread,
1323 selectedProvider: selectedProviderByThreadId,
1324 threadProvider,
1325 providers: providerStatuses,
1326 });
1327 const modelPickerLockedProvider = supportsProviderSwitchingViaHandoff ? null : lockedProvider;
1328 const pullRequestsCapabilityKnown = serverConfig !== null;
1329 const supportsPullRequests = serverConfig !== null;
1330 const attachmentEnvironmentConfig = environmentById.get(environmentId)?.serverConfig ?? null;
1331 const attachmentUploadsCapabilityKnown = attachmentEnvironmentConfig !== null;
1332 const supportsQuestionAttachments = attachmentEnvironmentConfig !== null;
1333 const supportsAttachmentUploads = attachmentEnvironmentConfig !== null;
1334 const advertisedFileAttachmentBytes =
1335 attachmentEnvironmentConfig?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null;
1336 const maxFileAttachmentBytes =
1337 advertisedFileAttachmentBytes === null
1338 ? null
1339 : clampFileAttachmentUploadBytes(advertisedFileAttachmentBytes);
1340 const envLocked =
1341 Boolean(activeThread) &&
1342 isThreadEnvironmentLocked({
1343 messageCount: activeMessageCount,
1344 hasRuntime: activeRuntime !== null,
1345 activeProviderThreadId: serverThread?.activeProviderThreadId ?? null,
1346 });
1347 // onEnvironmentChange only retargets an unsent draft. envLocked alone does not
1348 // rule out a started thread: one whose machine is offline never loads its
1349 // messages, so it would otherwise be offered a machine picker that does nothing.
1350 const canChangeEnvironment =
1351 hasMultipleEnvironments && !envLocked && draftId !== null && !draftThread?.promotedTo;
1352
1353 const loadBalancingSettings = useClientSettings((settings) => ({
1354 loadBalancingEnabled: settings.loadBalancingEnabled,
1355 loadBalancingWeights: settings.loadBalancingWeights,
1356 }));
1357 const automaticEnvironment = Boolean(
1358 clientSettingsHydrated &&
1359 draftId &&
1360 !envLocked &&
1361 canAutoBalanceEnvironments &&
1362 loadBalancingSettings.loadBalancingEnabled &&
1363 draftThread?.environmentSelection !== "manual" &&
1364 (!composerHasAttachments || Boolean(draftThread?.loadBalancedEnvironmentId)) &&
1365 (!draftThread?.branch || draftThread.environmentSelection === "auto") &&
1366 !draftThread?.worktreePath,
1367 );
1368 const autoUpdateEnvironments = automaticEnvironment
1369 ? logicalProjectEnvironments.flatMap(({ environmentId }) => {
1370 const environment = environmentById.get(environmentId);
1371 return environment ? [environment] : [];
1372 })
1373 : EMPTY_AUTO_UPDATE_ENVIRONMENTS;
1374 const systemComposerBannerItems = useSystemComposerBanners({
1375 activeEnvironment,
1376 activeEnvironmentUnavailable,
1377 activeEnvironmentUnavailableState,
1378 activeThreadEnvironmentId: activeThread?.environmentId ?? null,
1379 serverConfig,
1380 hasMultipleRegisteredEnvironments: environments.length > 1,
1381 automaticEnvironment,
1382 autoUpdateEnvironments,
1383 });
1384 const providerInstanceEntries = providerInstanceEntriesFor(
1385 providerStatuses,
1386 settings,
1387 activeProject?.id ?? null,
1388 );
1389 const activeThreadModelInstanceId = activeThread?.modelSelection.instanceId;
1390 const { selectedProviderEntry, requestedDriverKind } = resolveComposerProviderSelection({
1391 entries: providerInstanceEntries,
1392 candidateInstanceIds: [
1393 selectedProviderByThreadId,
1394 activeRuntime?.providerInstanceId,
1395 activeThreadModelInstanceId,
1396 activeProjectDefaultModelSelection?.instanceId,
1397 ],
1398 lockedProvider,
1399 lockedInstanceId: activeRuntime?.providerInstanceId ?? activeThreadModelInstanceId,
1400 });
1401 const selectedProvider = selectedProviderEntry?.driverKind ?? requestedDriverKind;
1402 const activeProviderInstanceId = selectedProviderEntry?.instanceId ?? null;
1403 const activeProviderStatus = selectedProviderEntry?.snapshot ?? null;
1404 const activeUsageModel =
1405 [
1406 composerModelSelectionApplies ? composerSelectedModelSelection : null,
1407 activeThread?.modelSelection,
1408 ].find((selection) => selection?.instanceId === activeProviderInstanceId)?.model ?? null;
1409 const conversationProviderStatus =
1410 providerStatuses.find((status) => status.instanceId === activeRuntime?.providerInstanceId) ??
1411 activeProviderStatus;
1412 const supportsConversationRollback =
1413 canOperateThread &&
1414 conversationProviderStatus !== null &&
1415 conversationProviderStatus.supportsConversationRollback !== false;
1416 const phase = derivePhase(activeRuntime);
1417 const serverThreadId = serverThread?.id;
1418 const serverThreadEnvironmentId = serverThread?.environmentId;
1419 const setThreadError = makeThreadErrorSetter({
1420 routeThreadRef,
1421 routeThreadKey,
1422 draftId,
1423 serverThreadRef:
1424 serverThreadId !== undefined && serverThreadEnvironmentId !== undefined
1425 ? { threadId: serverThreadId, environmentId: serverThreadEnvironmentId }
1426 : null,
1427 setLocalServerErrorsByThreadKey,
1428 setLocalDraftErrorsByDraftId,
1429 });
1430 const {
1431 pendingApprovals,
1432 pendingUserInputs,
1433 activePendingApproval,
1434 activePendingUserInput,
1435 activePendingIsResponding,
1436 respondingRequestIds,
1437 onRespondToApproval: onRespondToApprovalStable,
1438 onDismissUserInput: onDismissUserInputStable,
1439 onSelectActivePendingUserInputOption: onSelectActivePendingUserInputOptionStable,
1440 onChangeActivePendingUserInputCustomAnswer,
1441 onAdvanceActivePendingUserInput,
1442 onAdvanceActivePendingUserInputStable,
1443 onPreviousActivePendingUserInputQuestion: onPreviousActivePendingUserInputQuestionStable,
1444 } = usePendingThreadRequests({
1445 environmentId,
1446 activeThreadId,
1447 serverProjection,
1448 supportsQuestionAttachments,
1449 composerDraftTarget,
1450 setComposerDraftPrompt,
1451 promptRef,
1452 composerRef,
1453 setThreadError,
1454 });
1455 const [heldApprovalRequestIds, setHeldApprovalRequestIds] = useState<ReadonlySet<string>>(
1456 () => new Set(),
1457 );
1458 const onHeldRequestIdsChange = useStableCallback((requestIds: ReadonlySet<string>) => {
1459 setHeldApprovalRequestIds((current) => (shallow(current, requestIds) ? current : requestIds));
1460 });
1461 // Answering an approval or question on any client resumes quota spending, so include it in the key.
1462 const usageLimitsKey =
1463 activeProviderInstanceId === null || (isServerThread && activeThread === undefined)
1464 ? null
1465 : [
1466 routeThreadKey,
1467 activeProviderInstanceId,
1468 activeThread?.latestRun?.runId ?? "",
1469 activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? "",
1470 ].join(":");
1471 const {
1472 banner: usageLimitsBanner,
1473 offered: usageLimitsOffered,
1474 open: openUsageLimits,
1475 clearFor: clearUsageLimitsFor,
1476 } = useUsageLimitsPanel({
1477 environmentId,
1478 threadKey: routeThreadKey,
1479 panelKey: usageLimitsKey,
1480 providerInstanceId: activeProviderInstanceId,
1481 model: activeUsageModel,
1482 providerDriver: activeProviderStatus?.driver ?? null,
1483 providers: providerStatuses,
1484 sources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES,
1485 });
1486 const {
1487 beginLocalDispatch,
1488 resetLocalDispatch,
1489 localDispatchStartedAt,
1490 isPreparingWorktree: isLocallyPreparingWorktree,
1491 isSendBusy,
1492 backgroundSubmissionPending,
1493 } = useLocalDispatchState({
1494 environmentId,
1495 activeThread,
1496 activeLatestRun,
1497 latestUserMessageId:
1498 serverProjection?.messages.findLast((message) => message.role === "user")?.id ?? null,
1499 phase,
1500 activePendingApproval: activePendingApproval?.requestId ?? null,
1501 activePendingUserInput: activePendingUserInput?.requestId ?? null,
1502 threadError,
1503 });
1504 const optimisticCompactionMessage = optimisticUserMessages.at(-1);
1505 const latestServerUserItem = serverVisibleTurnItems.findLast(
1506 (row) => row.item.type === "user_message",
1507 )?.item;
1508 const compactRequestIsActive =
1509 (isSendBusy &&
1510 optimisticCompactionMessage !== undefined &&
1511 isCompactCommandMessage(optimisticCompactionMessage)) ||
1512 (latestServerUserItem?.type === "user_message" &&
1513 latestServerUserItem.text.trim().toLowerCase() === "/compact" &&
1514 latestServerUserItem.attachments.length === 0 &&
1515 latestServerUserItem.runId === activeActivityRun?.runId &&
1516 !isLatestRunSettled(activeActivityRun, activeRuntime));
1517 const compactionSettled = serverVisibleTurnItems.some(
1518 ({ item }) =>
1519 item.type === "compaction" &&
1520 item.runId === activeActivityRun?.runId &&
1521 (item.status === "completed" ||
1522 item.status === "failed" ||
1523 item.status === "interrupted" ||
1524 item.status === "cancelled"),
1525 );
1526 const compactionRunning = serverVisibleTurnItems.some(
1527 ({ item }) =>
1528 item.type === "compaction" &&
1529 item.runId !== null &&
1530 item.runId === activeRuntime?.activeRunId &&
1531 item.status === "running",
1532 );
1533 const compactCommandIsActive = compactRequestIsActive && !compactionSettled;
1534 const isCompacting =
1535 (isSendBusy || phase === "connecting" || phase === "running") &&
1536 (compactionRunning || compactCommandIsActive);
1537 const compactionBlocksSteer = compactionBlocksSteering({
1538 compactCommandIsActive,
1539 compactionRunning,
1540 steersDuringCompaction: threadSteersDuringCompaction(serverProjection),
1541 run: serverProjection?.runs.find((run) => run.id === activeRuntime?.activeRunId),
1542 messages: serverProjection?.messages,
1543 });
1544 const isWorking = deriveTimelineWorking({
1545 phase,
1546 isSendBusy,
1547 isCompacting,
1548 runlessWorkStartedAt,
1549 });
1550 const activeContextWindow = deriveLatestContextWindowSnapshot(
1551 serverVisibleTurnItems ?? [],
1552 activeThreadLiveTokenUsage,
1553 activeProviderThread,
1554 );
1555 const pendingBackgroundTasks = deriveThreadPendingBackgroundTasks(serverProjection);
1556 const activeWorkStartedAt =
1557 deriveActiveWorkStartedAt(activeActivityRun, activeRuntime, localDispatchStartedAt) ??
1558 runlessWorkStartedAt;
1559 const activeRunPreparing = activeActivityRun?.status === "preparing";
1560 const sendQueuesBehindSetup =
1561 isServerThread && (activeRunPreparing || activeActivityRun?.status === "starting");
1562 const [setupQueueSendThreadKey, setSetupQueueSendThreadKey] = useState<string | null>(null);
1563 const downloadFileAttachment = async (attachment: ChatFileAttachment) => {
1564 const connection = readPreparedConnection(environmentId);
1565 if (!connection) {
1566 toastManager.add({ type: "error", title: gt("The environment is not connected.") });
1567 return;
1568 }
1569
1570 try {
1571 const url = await resolveFileAttachmentUrl({
1572 attachment,
1573 environmentId,
1574 httpBaseUrl: connection.httpBaseUrl,
1575 createAssetUrl: createAttachmentAssetUrl,
1576 });
1577 const anchor = document.createElement("a");
1578 anchor.href = url;
1579 anchor.download = attachment.name;
1580 anchor.click();
1581 } catch (error) {
1582 toastManager.add({
1583 type: "error",
1584 title: gt("Could not download {name}", { name: attachment.name }),
1585 description: thrownErrorMessage(error, m) ?? gt("The attachment is unavailable."),
1586 });
1587 }
1588 };
1589 const downloadFileAttachmentStable = useStableCallback(downloadFileAttachment);
1590 const openFileAttachment = (attachment: ChatFileAttachment) => {
1591 if (activeThreadRef) {
1592 useRightPanelStore.getState().openAttachment(activeThreadRef, attachment);
1593 return;
1594 }
1595 };
1596 const openFileAttachmentStable = useStableCallback(openFileAttachment);
1597 const { timelineAttachmentUrlById } = useAttachmentPreviewHandoff({
1598 environmentId,
1599 threadId,
1600 serverVisibleTurnItems,
1601 handoff: optimisticState.handoff,
1602 blobPreviews: optimisticBlobPreviews,
1603 setOptimisticUserMessages: setHeldOptimisticUserMessages,
1604 });
1605 const anchoredTimelineMessages = feedbackSubmissions.flatMap((submission) =>
1606 submission.status === "interrupted"
1607 ? []
1608 : [
1609 { ...codexFeedbackMessage(submission, "user", messages), runId: null },
1610 { ...codexFeedbackMessage(submission, "assistant", messages), runId: null },
1611 ],
1612 );
1613 const timelineEntriesInput = {
1614 optimisticMessages: optimisticUserMessages,
1615 anchoredMessages: anchoredTimelineMessages,
1616 attachmentUrlById: timelineAttachmentUrlById,
1617 ...(serverProjection === null
1618 ? {}
1619 : {
1620 attempts: serverProjection.attempts,
1621 nodes: serverProjection.nodes,
1622 plans: serverProjection.plans,
1623 }),
1624 };
1625 // The structure has no assistant or reasoning text, so those rows stay out of
1626 // ChatView's own entries (anchoring, rewind, prompt history); ThreadTimeline
1627 // renders every row from the live turn items.
1628 const serverTimelineRows = serverVisibleTurnItems.filter(isCompleteTurnItemRow);
1629 const hasStreamedTimelineRows =
1630 isServerThread && serverTimelineRows.length !== serverVisibleTurnItems.length;
1631 const serverTimelineEntries = useIncrementalTimelineEntries(activeThreadKey, {
1632 ...timelineEntriesInput,
1633 visibleTurnItems: serverTimelineRows,
1634 });
1635 const draftTimelineEntries = optimisticUserMessages.map(
1636 (message) =>
1637 ({
1638 id: message.id,
1639 kind: "message",
1640 createdAt: message.createdAt,
1641 message,
1642 }) as const,
1643 );
1644 const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries;
1645 const timelineMessages = timelineEntries.flatMap((entry) =>
1646 entry.kind === "message" ? [entry.message] : [],
1647 );
1648 const timelineEmpty = timelineEntries.length === 0 && !hasStreamedTimelineRows;
1649 const displayedTimelineKey = activeThreadKey ?? routeThreadKey;
1650 const displayedThreadRef = parseScopedThreadKey(displayedTimelineKey);
1651 const {
1652 worktreeSetup,
1653 isPreparingWorktree,
1654 blocksSend: worktreeSetupBlocksSend,
1655 retryableRunIds: retryableWorkspacePreparationRunIds,
1656 begin: beginWorktreeSetup,
1657 cancel: cancelWorktreeSetup,
1658 retryPreparation: onRetryWorkspacePreparationStable,
1659 openSetupTerminal: onOpenWorktreeSetupTerminal,
1660 } = useWorktreeSetup({
1661 routeThreadRef,
1662 ownerKey: draftId ?? routeThreadKey,
1663 activeThread,
1664 threadRef: activeThreadRef,
1665 serverProjection,
1666 activityRun: activeActivityRun,
1667 localPreparing: isLocallyPreparingWorktree,
1668 sendQueuesBehindSetup,
1669 // Include optimistic sends to retire the row before the server echo.
1670 followUpSent: timelineMessages.filter((message) => message.role === "user").length > 1,
1671 });
1672 const onCancelWorktreeSetupStable = useStableCallback(() => void cancelWorktreeSetup());
1673 const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);
1674 const draftHeroDockRequested =
1675 activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;
1676 const isDraftHeroState = resolveDraftHeroState({
1677 isLocalDraftThread,
1678 hasTimelineEntries: !timelineEmpty,
1679 isWorking,
1680 draftHeroDockRequested,
1681 backgroundSubmissionPending,
1682 hasWorktreeSetupCard: worktreeSetup !== null,
1683 });
1684 const {
1685 transitionGroupRef: draftHeroTransitionGroupRef,
1686 composerAnchorRef: draftHeroComposerAnchorRef,
1687 captureComposerRect: captureDraftHeroComposerRect,
1688 } = useDraftHeroLayoutTransition(
1689 isDraftHeroState,
1690 panelAnimationsActive,
1691 panelAnimationDurationMs,
1692 );
1693 const turnDiffSummaries = useThreadCheckpointSummaries(routeThreadDetailRef);
1694 const availableRevertTurnCounts = deriveAvailableRevertTurnCounts(serverProjection);
1695 // A paged history window cannot identify the first loaded run as the thread start.
1696 const threadStartCheckpointAvailable =
1697 !serverThreadHistory.hasMoreHistory &&
1698 findRevertCheckpoint(serverProjection?.checkpoints ?? [], 0) !== undefined;
1699
1700 const workspaceMutationId = deriveWorkspaceMutationId(
1701 serverVisibleTurnItems,
1702 turnDiffSummaries.at(-1)?.completedAt ?? null,
1703 );
1704
1705 const gitStatusCwd = activeThread?.worktreePath ?? gitCwd;
1706 const gitStatusAtom =
1707 gitStatusCwd === null
1708 ? null
1709 : vcsEnvironment.status({
1710 environmentId,
1711 input: { cwd: gitStatusCwd },
1712 });
1713 const gitStatusQuery = {
1714 data: useAtomValue(gitStatusAtom ? chatGitStatusAtom(gitStatusAtom) : NO_CHAT_GIT_STATUS_ATOM),
1715 refresh: useEnvironmentQueryRefresh(gitStatusAtom).refresh,
1716 };
1717 useWorkspaceMutationRefresh({
1718 enabled: gitStatusCwd !== null,
1719 mutationId: workspaceMutationId,
1720 refresh: gitStatusQuery.refresh,
1721 resourceKey: `git-status:${activeThreadKey ?? ""}:${gitStatusCwd ?? ""}`,
1722 });
1723 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
1724 const backgroundThread = use(BackgroundThreadContext);
1725 const scriptKeybindings =
1726 useAtomValue(serverEnvironment.configValueAtom(environmentId))?.keybindings ??
1727 DEFAULT_RESOLVED_KEYBINDINGS;
1728 const openInEnvironmentId = activeThread?.environmentId ?? environmentId;
1729 const availableEditors =
1730 useAtomValue(serverEnvironment.configValueAtom(openInEnvironmentId))?.availableEditors ?? [];
1731 const hostEnvironmentId = useAtomValue(hostEnvironmentIdAtom);
1732 const remoteOpenState = useRemoteOpenState(openInEnvironmentId);
1733 const showOpenInPicker = shouldShowOpenInPicker({
1734 activeProjectName: activeProject?.title,
1735 activeThreadEnvironmentId: openInEnvironmentId,
1736 primaryEnvironmentId: primaryEnvironment?.environmentId ?? null,
1737 hostEnvironmentId,
1738 remoteOpenMode: remoteOpenState.mode,
1739 });
1740 useOpenFavoriteEditorShortcut({
1741 enabled: showOpenInPicker && !backgroundThread,
1742 environmentId: openInEnvironmentId,
1743 keybindings,
1744 availableEditors,
1745 openInCwd: gitCwd,
1746 });
1747 const manualCompactionProviderAvailable = hasAvailableCompactionProvider({
1748 providers: providerInstanceEntries,
1749 driverKind: selectedProvider,
1750 instanceId: activeProviderInstanceId,
1751 lockedInstanceId: lockedProvider
1752 ? (activeRuntime?.providerInstanceId ?? activeThread?.modelSelection.instanceId ?? null)
1753 : null,
1754 });
1755 const [resumeCompactionPermanentlyDismissed, setResumeCompactionPermanentlyDismissed] =
1756 useLocalStorage(
1757 `t3code:resume-compaction-dismissed:${environmentId}:${activeProviderInstanceId ?? "claudeAgent"}`,
1758 false,
1759 Schema.Boolean,
1760 );
1761 const nativeResumeCompactionDismissed = hasDismissedResumeCompaction(
1762 (serverProjection?.runtimeRequests ?? [])
1763 .filter((request) => request.kind === "user_input" && request.status === "resolved")
1764 .map((request) => ({
1765 kind: "user-input.resolved",
1766 payload: { answers: request.answers },
1767 })),
1768 );
1769 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- persists the server-reported resume compaction dismissal to localStorage
1770 useEffect(() => {
1771 if (nativeResumeCompactionDismissed && !resumeCompactionPermanentlyDismissed) {
1772 setResumeCompactionPermanentlyDismissed(true);
1773 }
1774 }, [
1775 nativeResumeCompactionDismissed,
1776 resumeCompactionPermanentlyDismissed,
1777 setResumeCompactionPermanentlyDismissed,
1778 ]);
1779 const [dismissedFallbackWindow, setDismissedFallbackWindow] = useLocalStorage(
1780 `t3code:fallback-notice-dismissed:${environmentId}`,
1781 null,
1782 DismissedFallbackWindowSchema,
1783 );
1784 const providerStatusDismissalKey = getProviderStatusDismissalKey(
1785 providerEnvironmentId,
1786 activeProviderStatus,
1787 );
1788 const providerStatusDismissed = useProviderStatusBannerDismissed(providerStatusDismissalKey);
1789 const visibleProviderStatus = shouldShowProviderStatusBanner(
1790 activeProviderStatus,
1791 providerStatusDismissed,
1792 )
1793 ? activeProviderStatus
1794 : null;
1795 const hasTimelineTopBanner = Boolean(timelineThreadError) || visibleProviderStatus !== null;
1796 const activeProjectCwd = activeProject?.workspaceRoot ?? null;
1797 const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
1798 const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
1799 const activeTerminalLaunchContext =
1800 terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null;
1801 const liveIsGitRepo = gitStatusQuery.data?.isRepo;
1802 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- records live git repo status in the session cache read while the status query is unavailable
1803 useEffect(() => {
1804 if (gitStatusCwd !== null && liveIsGitRepo !== undefined) {
1805 rememberCheckoutIsRepo(environmentId, gitStatusCwd, liveIsGitRepo);
1806 }
1807 }, [environmentId, gitStatusCwd, liveIsGitRepo]);
1808 const isGitRepo = liveIsGitRepo ?? recallCheckoutIsRepo(environmentId, gitStatusCwd) ?? true;
1809 // Provider-native subagents cannot take messages; approvals and questions go to the top-level parent.
1810 const showProviderSubagentBar = isProviderSubagent;
1811 const composerMounted = !showProviderSubagentBar;
1812 const providerSubagentModels = selectedProviderEntry?.models ?? EMPTY_PROVIDER_MODELS;
1813 // Providers can report dated model ids or aliases.
1814 const providerSubagentModelSlug = selectedProviderEntry
1815 ? resolveSelectableModel(
1816 selectedProviderEntry.driverKind,
1817 activeThread?.modelSelection.model,
1818 providerSubagentModels,
1819 )
1820 : null;
1821 const providerSubagentCatalogModel = providerSubagentModels.find(
1822 (model) => model.slug === providerSubagentModelSlug,
1823 );
1824 const providerSubagentModelLabel = providerSubagentCatalogModel
1825 ? getTriggerDisplayModelName(providerSubagentCatalogModel, selectedProviderEntry?.driverKind)
1826 : formatModelSlugName(activeThread?.modelSelection.model ?? "");
1827 const providerSubagentEffortLabel =
1828 activeThread === undefined
1829 ? null
1830 : formatModelSelectionEffort(
1831 activeThread.modelSelection,
1832 providerSubagentModels,
1833 reportedModelSelection,
1834 );
1835 const showComposerContextStrip =
1836 !embedded &&
1837 shouldShowComposerContextStrip({
1838 isDraftHeroState,
1839 persistInActiveThreads: settings.persistComposerContextStrip,
1840 hasActiveProject: activeProject !== null && !showProviderSubagentBar,
1841 isGitRepo,
1842 showEnvironmentIndicator: showComposerEnvironmentIndicator,
1843 });
1844 const terminalShortcutLabelOptions = {
1845 context: {
1846 terminalFocus: true,
1847 terminalOpen: Boolean(terminalUiState.terminalOpen),
1848 },
1849 };
1850 const splitTerminalShortcutLabel = shortcutLabelForCommand(
1851 keybindings,
1852 "terminal.split",
1853 terminalShortcutLabelOptions,
1854 );
1855 const splitTerminalVerticalShortcutLabel = shortcutLabelForCommand(
1856 keybindings,
1857 "terminal.splitVertical",
1858 terminalShortcutLabelOptions,
1859 );
1860 const newTerminalShortcutLabel = shortcutLabelForCommand(
1861 keybindings,
1862 "terminal.new",
1863 terminalShortcutLabelOptions,
1864 );
1865 const closeTerminalShortcutLabel = shortcutLabelForCommand(
1866 keybindings,
1867 "terminal.close",
1868 terminalShortcutLabelOptions,
1869 );
1870
1871 const {
1872 needsLoadBalancing,
1873 loadBalancing,
1874 refreshBeforeSend,
1875 onAutoEnvironmentStable,
1876 autoEnvironmentLabel,
1877 isEnvironmentChanging,
1878 readPendingEnvironmentChange,
1879 onEnvironmentChangeStable,
1880 } = useDraftEnvironmentRouting({
1881 draftId,
1882 draftThread,
1883 envLocked,
1884 automaticEnvironment,
1885 logicalProjectEnvironments,
1886 environmentById,
1887 providersByEnvironment,
1888 loadBalancingSettings,
1889 referencedThreadContexts,
1890 activeProviderInstanceId,
1891 selectedProvider,
1892 composerHasAttachments,
1893 activeProjectKey,
1894 activeProjectIsScratch,
1895 projectGroupingSettings,
1896 sendInFlightRef,
1897 });
1898
1899 const { focusComposer: focusComposerStable, scheduleComposerFocus: scheduleComposerFocusStable } =
1900 useComposerFocus(composerRef);
1901 const canInterruptRunningThread =
1902 canOperateThread && deriveCanInterruptRunningThread(activeThread !== undefined, activeRuntime);
1903 const onInterrupt = async () => {
1904 if (
1905 !activeThread ||
1906 !readEnvironmentScope(activeThread.environmentId, AuthOrchestrationOperateScope)
1907 )
1908 return;
1909 const result = await interruptThreadTurn({
1910 environmentId,
1911 input: { threadId: activeThread.id },
1912 });
1913 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
1914 const error = squashAtomCommandFailure(result);
1915 setThreadError(
1916 activeThread.id,
1917 thrownErrorMessage(error, m) ?? gt("Failed to interrupt the current turn."),
1918 );
1919 }
1920 };
1921 const onInterruptStable = useStableCallback(onInterrupt);
1922 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window listener for the desktop snapshot event that focuses the composer
1923 useEffect(
1924 () => (embedded ? undefined : subscribeSnapShotComposerFocus(focusComposerStable)),
1925 [embedded, focusComposerStable],
1926 );
1927 const insertArtifactTemplate = (template: CodexArtifactTemplate) => {
1928 const composer = composerRef.current;
1929 if (!composer) return;
1930
1931 const currentDraft = composer.getSendContext().prompt;
1932 const prompt = codexArtifactTemplatePromptToAppend(currentDraft, template);
1933 if (prompt !== null && !composer.insertTextAtEnd(prompt, { ensureLeadingBoundary: true })) {
1934 toastManager.add({
1935 type: "error",
1936 title: gt("Unable to add to chat"),
1937 description: gt("The composer is busy; try again once it is ready."),
1938 });
1939 return;
1940 }
1941 scheduleComposerFocusStable();
1942 };
1943 const insertArtifactTemplateStable = useStableCallback(insertArtifactTemplate);
1944 const sendAppMessage = async (text: string) => {
1945 if (!isServerThread || activeThreadId === null) {
1946 throw new Error(gt("Messages from apps need a started thread."));
1947 }
1948 const result = await startThreadTurn({
1949 environmentId,
1950 input: {
1951 threadId: activeThreadId,
1952 message: { messageId: newMessageId(), role: "user", text, attachments: [] },
1953 runtimeMode,
1954 interactionMode: DEFAULT_INTERACTION_MODE,
1955 dispatchMode: "queue",
1956 },
1957 });
1958 if (result._tag === "Failure") {
1959 const error = squashAtomCommandFailure(result);
1960 throw error instanceof Error ? error : new Error(gt("Could not send the app's message."));
1961 }
1962 };
1963 const sendAppMessageStable = useStableCallback(sendAppMessage);
1964 const queuedRunsControlRef = useRef<QueuedRunsControlHandle>(null);
1965
1966 const {
1967 activatePanelTerminalStable,
1968 addTerminalContextToDraftStable,
1969 addTerminalSurfaceStable,
1970 closePanelTerminalStable,
1971 lastInvokedScriptByProjectId,
1972 runProjectScriptStable,
1973 runShellCommandStable,
1974 splitPanelTerminalStable,
1975 splitPanelTerminalVerticalStable,
1976 toggleTerminalVisibilityStable,
1977 shortcuts: terminalShortcuts,
1978 } = useChatTerminalActions({
1979 environmentId,
1980 composerRef,
1981 terminalUiState,
1982 activeThread,
1983 activeThreadId,
1984 activeThreadRef,
1985 activeProject,
1986 activeRightPanelSurface,
1987 runningTerminalIds,
1988 activeServerOrderedTerminalIds,
1989 activeTerminalLabelsById,
1990 panelTerminalIds,
1991 canReuseTerminal,
1992 gitCwd,
1993 setTerminalUiLaunchContext,
1994 setThreadError,
1995 });
1996 const {
1997 saveProjectScript: saveProjectScriptStable,
1998 updateProjectScript: updateProjectScriptStable,
1999 deleteProjectScript: deleteProjectScriptStable,
2000 } = useProjectScriptEditing({
2001 environmentId,
2002 project: activeProject,
2003 scripts: activeProjectScripts,
2004 settings,
2005 });
2006 const canOperatePreview = useEnvironmentScope(
2007 activeThreadRef?.environmentId ?? null,
2008 AuthPreviewOperateScope,
2009 );
2010 const shownPreviewMiniPlayer =
2011 activeThreadRef &&
2012 activePreviewMiniPlayer &&
2013 previewMiniPlayerVisible &&
2014 (activePreviewMiniPlayer.source.kind === "device" || canOperatePreview)
2015 ? activePreviewMiniPlayer
2016 : null;
2017 const canvasPreview = useThreadPreviewCanvasSource(activeThreadRef, shownPreviewMiniPlayer);
2018 const threadPanelInlineOpen = useRightPanelStore((state) =>
2019 selectThreadPanelOpen(state.threadPanelVisibilityByThreadKey, activeThreadRef, "inline"),
2020 );
2021 // Selects only the mode, so canvas resizes rerender the chat view only when the
2022 // card switches presentation.
2023 const threadPanelPresentation = useStore(
2024 chatCanvasStore,
2025 (state) =>
2026 resolveChatCanvasModel({
2027 measurements: state.measurements,
2028 detailsCardMeasurement: state.detailsCardMeasurement,
2029 threadRef: activeThreadRef,
2030 preview: canvasPreview,
2031 detailsCardInlineOpen: threadPanelInlineOpen,
2032 }).detailsCardMode,
2033 );
2034 const threadPanelOpen = useRightPanelStore((state) =>
2035 selectThreadPanelOpen(
2036 state.threadPanelVisibilityByThreadKey,
2037 activeThreadRef,
2038 threadPanelPresentation,
2039 ),
2040 );
2041 const supportsThreadPullRequests = serverConfig !== null;
2042 const visiblePullRequests = visibleThreadPullRequests(
2043 (activeThreadShell ?? activeThread)?.pullRequests ?? [],
2044 );
2045 const visiblePullRequestCount = visiblePullRequests.length;
2046 const pullRequestsSurfaceAvailable =
2047 isServerThread && supportsThreadPullRequests && visiblePullRequestCount > 0;
2048 const linkedItemsSurfaceAvailable =
2049 pullRequestsSurfaceAvailable ||
2050 (isServerThread && (activeThreadShell?.issues?.length ?? 0) > 0);
2051 const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState(
2052 activeThreadRef?.environmentId ?? null,
2053 );
2054 // The thread's own change request, placed against the project it belongs to. Without a
2055 // project there is nothing to resolve it against, so the caller falls back to the browser.
2056 const activeProjectRepository = sourceControlClients.repositorySelector(
2057 activeProject?.repositoryIdentity,
2058 );
2059 const {
2060 linked: linkedThreadPullRequest,
2061 linkedKey: linkedThreadPullRequestKey,
2062 hasDetail: hasLinkedPullRequestDetail,
2063 } = useThreadLinkedPullRequest({
2064 serverThreadRef: isServerThread ? activeThreadRef : null,
2065 environmentId: activeThreadRef?.environmentId ?? null,
2066 persisted: isServerThread
2067 ? (activeThreadShell?.linkedPullRequest ?? activeThread?.linkedPullRequest ?? null)
2068 : (activeThread?.linkedPullRequest ?? null),
2069 projectId: activeProject?.id ?? null,
2070 projectRepository: activeProjectRepository,
2071 threadBranch: activeThread?.branch ?? null,
2072 gitStatus: gitStatusQuery.data ?? null,
2073 });
2074 const proactivePullRequestsKey = pullRequestsSurfaceAvailable
2075 ? JSON.stringify(
2076 visiblePullRequests.map((link) => [link.host, link.repository, link.number]).sort(),
2077 )
2078 : linkedThreadPullRequestKey;
2079 const activeRunningTurnId = activeRuntime?.activeRunId ?? null;
2080 useProactivePanels({
2081 threadRef: isServerThread && !embedded ? activeThreadRef : null,
2082 enabled: settings.proactivePanelsEnabled && !shouldUsePlanSidebarSheet && !embedded,
2083 settingsHydrated: clientSettingsHydrated,
2084 threadDetailLoading,
2085 runningTurnId: activeRunningTurnId,
2086 latestRun: activeLatestRun,
2087 latestRunSettled,
2088 turnDiffSummaries,
2089 isGitRepo: gitStatusQuery.data?.isRepo,
2090 linkedPullRequest: linkedThreadPullRequest,
2091 hasLinkedPullRequestDetail,
2092 pullRequestsKey: proactivePullRequestsKey,
2093 pullRequestsCapabilityKnown,
2094 supportsPullRequests,
2095 pullRequestsSurfaceAvailable,
2096 visiblePullRequestCount,
2097 onDiffPanelOpen,
2098 });
2099 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- consumes a pending maximize request from the right panel store once the panel can maximize
2100 useEffect(() => {
2101 if (!canMaximizeRightPanel) return;
2102 if (useRightPanelStore.getState().consumeMaximizeRequest(routeThreadRef)) {
2103 useRightPanelStore.getState().setMaximized(routeThreadRef, true);
2104 }
2105 }, [canMaximizeRightPanel, routeThreadRef]);
2106 const {
2107 closeSurface: closeRightPanelSurface,
2108 closeOtherSurfaces: closeOtherRightPanelSurfacesStable,
2109 closeSurfacesToRight: closeRightPanelSurfacesToRightStable,
2110 closeAllSurfaces: closeAllRightPanelSurfacesStable,
2111 } = useRightPanelSurfaceClose({
2112 threadRef: activeThreadRef,
2113 terminalLabelsById: activeTerminalLabelsById,
2114 });
2115 const closeRightPanelSurfaceStable = closeRightPanelSurface;
2116 const persistThreadSettingsForNextTurn = async (input: {
2117 threadId: ThreadId;
2118 createdAt: string;
2119 branch?: string;
2120 runtimeMode: RuntimeMode;
2121 interactionMode: ProviderInteractionMode;
2122 }): Promise<AtomCommandResult<void, unknown>> => {
2123 if (!serverThread) {
2124 return AsyncResult.success(undefined);
2125 }
2126
2127 let result: AtomCommandResult<void, unknown> = AsyncResult.success(undefined);
2128 const metadataUpdate = resolveThreadMetadataUpdateForNextTurn({
2129 currentModelSelection: serverThread.modelSelection,
2130 currentBranch: serverThread.branch,
2131 ...(input.branch ? { nextBranch: input.branch } : {}),
2132 });
2133 if (metadataUpdate) {
2134 result = mapAtomCommandResult(
2135 await updateThreadMetadata({
2136 environmentId,
2137 input: {
2138 threadId: input.threadId,
2139 ...metadataUpdate,
2140 },
2141 }),
2142 () => undefined,
2143 );
2144 if (result._tag === "Failure") {
2145 return result;
2146 }
2147 }
2148
2149 if (input.runtimeMode !== serverThread.runtimeMode) {
2150 result = mapAtomCommandResult(
2151 await setThreadRuntimeMode({
2152 environmentId,
2153 input: {
2154 threadId: input.threadId,
2155 runtimeMode: input.runtimeMode,
2156 createdAt: input.createdAt,
2157 },
2158 }),
2159 () => undefined,
2160 );
2161 if (result._tag === "Failure") {
2162 return result;
2163 }
2164 }
2165
2166 if (input.interactionMode !== serverThread.interactionMode) {
2167 result = mapAtomCommandResult(
2168 await setThreadInteractionMode({
2169 environmentId,
2170 input: {
2171 threadId: input.threadId,
2172 interactionMode: input.interactionMode,
2173 createdAt: input.createdAt,
2174 },
2175 }),
2176 () => undefined,
2177 );
2178 }
2179 return result;
2180 };
2181
2182 const {
2183 showScrollToBottom,
2184 timelineLiveFollowEnabled,
2185 onComposerPageScrollKeyDownStable,
2186 onComposerPageScrollKeyUpStable,
2187 onComposerPageScrollReleaseStable,
2188 scrollToEnd,
2189 onTimelineAnchorReadyStable,
2190 onTimelineAnchorSizeChangedStable,
2191 onTimelineFooterGrowStable,
2192 onIsAtEndChangeStable,
2193 anchorNewTurn,
2194 attachTimelineViewport,
2195 attachComposerOverlay: attachFollowComposerOverlay,
2196 } = useTimelineFollow({
2197 legendListRef,
2198 composerTimelineInset,
2199 routeThreadKey,
2200 activeThreadKey,
2201 isServerThread,
2202 serverProjection,
2203 threadStatus,
2204 activeActivityRun,
2205 activeRunningTurnId,
2206 timelineEntries,
2207 timelineAnchorMessageId,
2208 setTimelineAnchor,
2209 });
2210
2211 useFocusComposerOnThreadOpen(
2212 activeThreadRef,
2213 workspaceLayoutElement,
2214 !embedded,
2215 terminalUiState.terminalOpen,
2216 isCoarsePointer ? ignoreComposerFocus : focusComposerStable,
2217 );
2218
2219 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window focus listener that refocuses the composer after the window regains focus on a fine pointer
2220 useEffect(() => {
2221 if (
2222 embedded ||
2223 !activeThread?.id ||
2224 terminalUiState.terminalOpen ||
2225 isMobileViewport ||
2226 isCoarsePointer
2227 ) {
2228 return;
2229 }
2230 let frame: number | null = null;
2231 const onWindowFocus = () => {
2232 if (frame !== null) window.cancelAnimationFrame(frame);
2233 // Wait an extra frame after window focus so the composer treats focus as an expansion request.
2234 frame = window.requestAnimationFrame(() => {
2235 frame = window.requestAnimationFrame(() => {
2236 frame = null;
2237 if (document.querySelector("[data-mcp-app-fullscreen]") !== null) return;
2238 if (
2239 !isInSideChatPane(document.activeElement) &&
2240 shouldRefocusComposerOnWindowFocus(document.activeElement, document.getSelection())
2241 ) {
2242 focusComposerStable();
2243 }
2244 });
2245 });
2246 };
2247 window.addEventListener("focus", onWindowFocus);
2248 return () => {
2249 window.removeEventListener("focus", onWindowFocus);
2250 if (frame !== null) window.cancelAnimationFrame(frame);
2251 };
2252 }, [
2253 activeThread?.id,
2254 embedded,
2255 focusComposerStable,
2256 isCoarsePointer,
2257 isMobileViewport,
2258 terminalUiState.terminalOpen,
2259 ]);
2260
2261 // Promotion drops draftId while a send may still be dispatching, so key by thread.
2262 const [localDispatchThreadId, setLocalDispatchThreadId] = useState(threadId);
2263 if (localDispatchThreadId !== threadId) {
2264 setLocalDispatchThreadId(threadId);
2265 resetLocalDispatch();
2266 }
2267
2268 const activeWorktreePath = activeThread?.worktreePath ?? null;
2269 const derivedEnvMode: DraftThreadEnvMode = resolveEffectiveEnvMode({
2270 activeWorktreePath,
2271 hasServerThread: isServerThread,
2272 draftThreadEnvMode: isLocalDraftThread ? draftThread?.envMode : undefined,
2273 preparingWorktree: isPreparingWorktree,
2274 });
2275 const canOverrideServerThreadEnvMode = Boolean(
2276 isServerThread &&
2277 activeThread &&
2278 activeMessageCount === 0 &&
2279 activeThread.worktreePath === null &&
2280 !envLocked,
2281 );
2282 if (
2283 !canOverrideServerThreadEnvMode &&
2284 (pendingServerThreadEnvModeEntry !== null || pendingServerThreadBranchEntry !== null)
2285 ) {
2286 setPendingServerThreadEnvModeEntry(null);
2287 setPendingServerThreadBranchEntry(null);
2288 }
2289 const pendingServerThreadEnvMode =
2290 pendingServerThreadEnvModeEntry !== null &&
2291 pendingServerThreadEnvModeEntry.threadId === activeThread?.id
2292 ? pendingServerThreadEnvModeEntry.mode
2293 : null;
2294 const pendingServerThreadBranchEntryForThread =
2295 pendingServerThreadBranchEntry?.threadId === activeThread?.id
2296 ? pendingServerThreadBranchEntry
2297 : null;
2298 const setPendingServerThreadBranch = (branch: string | null) => {
2299 if (activeThread) setPendingServerThreadBranchEntry({ threadId: activeThread.id, branch });
2300 };
2301 const envMode: DraftThreadEnvMode = canOverrideServerThreadEnvMode
2302 ? (pendingServerThreadEnvMode ?? draftThread?.envMode ?? derivedEnvMode)
2303 : derivedEnvMode;
2304 const activeThreadBranch =
2305 canOverrideServerThreadEnvMode && pendingServerThreadBranchEntryForThread !== null
2306 ? pendingServerThreadBranchEntryForThread.branch
2307 : (activeThread?.branch ?? null);
2308 const startFromOrigin = isLocalDraftThread
2309 ? (draftThread?.startFromOrigin ?? false)
2310 : canOverrideServerThreadEnvMode
2311 ? (pendingServerThreadStartFromOriginByThreadId[activeThread?.id ?? ""] ??
2312 activeProjectSettings.settings.newWorktreesStartFromOrigin)
2313 : false;
2314 const sendEnvMode = resolveSendEnvMode({
2315 requestedEnvMode: envMode,
2316 isGitRepo,
2317 });
2318 const localCheckoutBranchMismatch = isServerThread
2319 ? resolveLocalCheckoutBranchMismatch({
2320 effectiveEnvMode: envMode,
2321 activeWorktreePath,
2322 activeThreadBranch,
2323 currentGitBranch: gitStatusQuery.data?.refName ?? null,
2324 })
2325 : null;
2326 const publishComposerOverlayHeight = (height: number) => {
2327 const nextHeight = Math.ceil(height);
2328 if (nextHeight <= 0) return;
2329 if (composerTimelineInsetRef.current !== nextHeight) {
2330 composerTimelineInsetRef.current = nextHeight;
2331 setComposerTimelineInset(nextHeight);
2332 }
2333 // Reserve the expanded composer height for the terminal drawer and empty placeholder.
2334 // Keep it while the mobile strip collapses, but allow growth from approvals or tasks.
2335 // A hero overlay fills the pane, so reserve only its stack.
2336 const stack = composerOverlayElement?.querySelector<HTMLElement>(
2337 '[data-chat-composer-stack="true"]',
2338 );
2339 const expandedComposerHeight =
2340 isDraftHeroState && stack ? Math.ceil(stack.getBoundingClientRect().height) : nextHeight;
2341 const mobileCollapsed = Boolean(
2342 stack?.querySelector('[data-chat-composer-mobile-collapsed="true"]'),
2343 );
2344 if (!mobileCollapsed) composerExpandedHeightRef.current = expandedComposerHeight;
2345 const reservedHeight = Math.max(composerExpandedHeightRef.current, expandedComposerHeight);
2346 if (composerReservedHeightRef.current !== reservedHeight) {
2347 composerReservedHeightRef.current = reservedHeight;
2348 setComposerReservedHeight(reservedHeight);
2349 }
2350 const mainSurface = composerOverlayElement?.querySelector<HTMLElement>(
2351 '[data-chat-composer-main-surface="true"]',
2352 );
2353 const button =
2354 composerOverlayElement?.parentElement?.querySelector<HTMLElement>("[data-scroll-to-end]");
2355 const clearance =
2356 composerOverlayElement && mainSurface && button
2357 ? resolveScrollToEndClearance({
2358 overlayHeight: nextHeight,
2359 mainSurfaceTop: mainSurface.getBoundingClientRect().top,
2360 button: button.getBoundingClientRect(),
2361 attachments: Array.from(
2362 composerOverlayElement.querySelectorAll<HTMLElement>(
2363 '[data-composer-banner-surface="attached"]',
2364 ),
2365 (element) => element.getBoundingClientRect(),
2366 ),
2367 })
2368 : nextHeight;
2369 setScrollToEndClearance(clearance);
2370 };
2371 const publishComposerOverlayHeightStable = useStableCallback(publishComposerOverlayHeight);
2372 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the composer overlay element before paint for a new thread or composer mount
2373 useLayoutEffect(() => {
2374 if (!composerOverlayElement) return;
2375 composerTimelineInsetRef.current = 0;
2376 composerReservedHeightRef.current = 0;
2377 composerExpandedHeightRef.current = 0;
2378 publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height);
2379 }, [
2380 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch or a composer mount/unmount must re-measure the overlay for the new timeline.
2381 activeThreadKey,
2382 composerMounted,
2383 composerOverlayElement,
2384 publishComposerOverlayHeightStable,
2385 ]);
2386
2387 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes the composer overlay element's size before paint and publishes its height
2388 useLayoutEffect(() => {
2389 if (!composerOverlayElement) return;
2390
2391 const updateHeight = () => {
2392 publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height);
2393 };
2394
2395 updateHeight();
2396 // The hero overlay fills the pane, so the composer's own growth only shows on its stack.
2397 const stack = isDraftHeroState
2398 ? composerOverlayElement.querySelector<HTMLElement>('[data-chat-composer-stack="true"]')
2399 : null;
2400 return observeResize(
2401 stack ? [composerOverlayElement, stack] : composerOverlayElement,
2402 updateHeight,
2403 );
2404 }, [
2405 composerOverlayElement,
2406 isDraftHeroState,
2407 publishComposerOverlayHeightStable,
2408 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- The scroll-to-bottom button changes the overlay's height without resizing the observed node first.
2409 showScrollToBottom,
2410 ]);
2411 const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(activeThreadRef);
2412 const activeThreadReferenceCopyTarget =
2413 activeThreadRef === null || !isServerThread
2414 ? null
2415 : resolveThreadReferenceCopyTarget(
2416 {
2417 threadRef: activeThreadRef,
2418 title: activeThread?.title ?? "",
2419 openPanelPullRequestUrl,
2420 pullRequests: activeThread?.pullRequests,
2421 linkedPullRequestUrl: linkedThreadPullRequest?.url ?? null,
2422 hostedAppUrl: configuredHostedAppUrl(),
2423 },
2424 messages,
2425 );
2426 const copyActiveThreadReference = () => {
2427 if (activeThreadReferenceCopyTarget === null) return;
2428 void copyThreadReference(activeThreadReferenceCopyTarget);
2429 };
2430 const pullRequestPanelTarget = activeThread
2431 ? threadPullRequestPanelTarget({
2432 projectId: activeThread.projectId,
2433 pullRequests: visiblePullRequests,
2434 linkedPullRequest: linkedThreadPullRequest,
2435 branchPullRequest: activeThreadShell?.branchPullRequest ?? activeThread.branchPullRequest,
2436 })
2437 : null;
2438 const {
2439 activateRightPanelSurfaceStable,
2440 addDeviceSurfaceStable,
2441 addDiffSurfaceStable,
2442 addFilesSurfaceStable,
2443 addPullRequestSurfaceStable,
2444 addPullRequestsSurfaceStable,
2445 closePreviewPanelStable,
2446 copyRightPanelFilePathStable,
2447 createBrowserSurface,
2448 createBrowserSurfaceStable,
2449 moveRightPanelSurfaceStable,
2450 onOpenToolDiffStable,
2451 onOpenTurnDiffStable,
2452 openChangesFromThreadPanelStable,
2453 openFileSurfaceStable,
2454 toggleRightPanelMaximizedStable,
2455 toggleRightPanelStable,
2456 toggleThreadPanelStable,
2457 shortcuts: rightPanelShortcuts,
2458 } = useRightPanelActions({
2459 activeThreadRef,
2460 activeProject,
2461 activeRightPanelSurface,
2462 activePreviewState,
2463 deviceState,
2464 deviceStateLoaded,
2465 pullRequestPanelTarget,
2466 threadPanelPresentation,
2467 isServerThread,
2468 embedded,
2469 isGitRepo,
2470 browserAvailable,
2471 canOperatePreview,
2472 diffOpen,
2473 previewPanelOpen,
2474 rightPanelOpen,
2475 canMaximizeRightPanel,
2476 rightPanelMaximized,
2477 supportsPullRequests,
2478 pullRequestsSurfaceAvailable: linkedItemsSurfaceAvailable,
2479 gitCwd,
2480 activeProjectCwd,
2481 onDiffPanelOpen,
2482 closeRightPanelSurface,
2483 });
2484 const pullRequestSurfaceAvailable = supportsPullRequests && pullRequestPanelTarget !== null;
2485 const {
2486 acknowledgeActiveThreadWoke,
2487 activeBranchMismatchKey,
2488 attentionNow,
2489 workNow,
2490 childInputNow,
2491 goalNow,
2492 handleSwitchCheckoutToThread,
2493 handleSwitchCheckoutToThreadStable,
2494 isRestoringThreadBranch,
2495 onOpenRelatedThreadStable,
2496 sendStandaloneCommand,
2497 setBranchMismatchDismissTick,
2498 showBranchMismatchBanner,
2499 threadStatusLine,
2500 shortcuts: threadLifecycleShortcuts,
2501 } = useThreadLifecycle({
2502 environmentId,
2503 routeThreadKey,
2504 currentRouteThreadKeyRef,
2505 canOperateThread,
2506 clientSettingsHydrated,
2507 activeThread,
2508 activeThreadId,
2509 activeThreadRef,
2510 threadDetailRef: routeThreadDetailRef,
2511 activeThreadKey,
2512 activeThreadShell,
2513 activeLatestRun,
2514 limitRecoveryHoldsSnooze,
2515 activeProjectCwd,
2516 serverConfig,
2517 runtimeMode,
2518 isWorking,
2519 // A waiting run is checkpoint drain; Stop there reaches its background work.
2520 runIsLive: (isWorking && activeRuntime?.status !== "waiting") || phase === "connecting",
2521 pendingBackgroundTasks,
2522 turnItems: serverProjection?.turnItems ?? EMPTY_TURN_ITEMS,
2523 activePendingApproval,
2524 activePendingUserInput,
2525 localCheckoutBranchMismatch,
2526 gitStatusQuery,
2527 nowMinute,
2528 composerRef,
2529 composerDraftTarget,
2530 sendInFlightRef,
2531 setOptimisticUserMessages,
2532 setThreadError,
2533 clearUsageLimitsFor,
2534 beginLocalDispatch,
2535 resetLocalDispatch,
2536 scrollToEnd,
2537 persistThreadSettingsForNextTurn,
2538 });
2539 const activeThreadHasCompactableConversation = hasCompactableConversation({
2540 visibleTurnItems: serverVisibleTurnItems,
2541 hasMoreHistory: serverThreadHistory.hasMoreHistory,
2542 latestUserMessageAt: serverThread?.latestUserMessageAt ?? null,
2543 });
2544 const pendingHandoffSelection =
2545 (composerModelSelectionApplies ? composerSelectedModelSelection : null) ??
2546 activeThread?.modelSelection;
2547 const pendingHandoffSelectionUsable = providerInstanceEntries.some(
2548 (entry) =>
2549 entry.instanceId === pendingHandoffSelection?.instanceId &&
2550 entry.enabled &&
2551 entry.isAvailable,
2552 );
2553 const pendingHandoff = resolvePendingHandoff(
2554 serverProjection,
2555 pendingHandoffSelectionUsable ? pendingHandoffSelection : null,
2556 providerStatuses,
2557 );
2558 const compactThreadUnavailable =
2559 !canOperateThread ||
2560 !activeThread ||
2561 !activeThreadHasCompactableConversation ||
2562 !activeProject ||
2563 !isServerThread ||
2564 !manualCompactionProviderAvailable ||
2565 isWorking ||
2566 isRevertingCheckpoint ||
2567 threadDetailLoading ||
2568 isPreparingWorktree ||
2569 activeEnvironmentUnavailable ||
2570 feedbackUploading ||
2571 pendingApprovals.length > 0 ||
2572 pendingUserInputs.length > 0;
2573 const compactDisabled = compactThreadUnavailable;
2574 const freshSessionAvailable =
2575 activeMessageCount > 0 && serverConfig?.environment.capabilities.freshContext === true;
2576 const freshSessionArmed = useFreshSessionArmed(routeThreadKey);
2577 const freshSessionPending = freshSessionAvailable && freshSessionArmed;
2578 // The context window is the current conversation's, so neither a handoff destination nor
2579 // the fresh session armed by /clear inherits it.
2580 const resumeCompactionTokens =
2581 activeContextWindow &&
2582 pendingHandoff === null &&
2583 !freshSessionPending &&
2584 resolveIdleCompaction(
2585 settings,
2586 activeProviderInstanceId ?? ProviderInstanceId.make("claudeAgent"),
2587 ) !== "off" &&
2588 !resumeCompactionPermanentlyDismissed &&
2589 !nativeResumeCompactionDismissed &&
2590 !compactDisabled &&
2591 !hasHeldQueuedRuns &&
2592 multipleModelSelections === null &&
2593 shouldOfferResumeCompaction({
2594 provider: selectedProvider,
2595 usedTokens: activeContextWindow.usedTokens,
2596 updatedAt: activeContextWindow.updatedAt,
2597 promptCacheTtlMs: activeThreadLiveTokenUsage?.promptCacheTtlMs,
2598 now: `${nowMinute}:00.000Z`,
2599 })
2600 ? activeContextWindow.usedTokens
2601 : null;
2602 const [fullHistoryThreadKeys, setFullHistoryThreadKeys] = useState<ReadonlySet<string>>(
2603 () => new Set(),
2604 );
2605 const keepFullHistory = fullHistoryThreadKeys.has(routeThreadKey);
2606 const setKeepFullHistory = (threadKey: string, keep: boolean) => {
2607 setFullHistoryThreadKeys((current) => {
2608 if (current.has(threadKey) === keep) return current;
2609 const next = new Set(current);
2610 if (keep) next.add(threadKey);
2611 else next.delete(threadKey);
2612 return next;
2613 });
2614 };
2615 // While a question or approval owns the composer, its text answers that, not the agent.
2616 const freshSessionCommandAvailable =
2617 freshSessionAvailable && activePendingApproval === null && pendingUserInputs.length === 0;
2618 const toggleKeepFullHistory = () => setKeepFullHistory(routeThreadKey, !keepFullHistory);
2619 const toggleKeepFullHistoryStable = useStableCallback(toggleKeepFullHistory);
2620 const armFreshSessionStable = useStableCallback(() => armFreshSession(routeThreadKey));
2621 const handleRestoreThreadBranch = () => {
2622 if (!canWriteSourceControl) return;
2623 if (gitStatusQuery.data?.hasWorkingTreeChanges) {
2624 if (activeThreadKey !== null) openBranchRestoreConfirm(activeThreadKey);
2625 return;
2626 }
2627 void handleSwitchCheckoutToThread();
2628 };
2629 const handleRestoreThreadBranchStable = useStableCallback(handleRestoreThreadBranch);
2630 const feedbackBannerItems = feedbackSubmissions.flatMap((submission) => {
2631 const item = feedbackBannerItem(
2632 submission,
2633 () => {
2634 setFeedbackSubmissionsByThreadKey((current) => ({
2635 ...current,
2636 [routeThreadKey]: (current[routeThreadKey] ?? []).filter(
2637 (entry) => entry.id !== submission.id,
2638 ),
2639 }));
2640 },
2641 messages,
2642 );
2643 return item ? [item] : [];
2644 });
2645 const limitRecoveryBanner = useUsageLimitRecoveryBannerItem(
2646 limitRecoveryRun !== null && activeThreadShell !== null
2647 ? {
2648 runId: limitRecoveryRun.runId,
2649 errorCode: serverRuntime?.lastErrorCode ?? null,
2650 resetAt: serverRuntime?.usageLimitResetAt ?? null,
2651 stoppedAt: limitRecoveryRun.completedAt ?? activeThreadShell.updatedAt,
2652 settled: activeThreadShell.settledOverride === "settled",
2653 requestPending: pendingApprovals.length > 0 || pendingUserInputs.length > 0,
2654 recovery: activeThreadShell.limitRecovery ?? null,
2655 snoozedUntil: activeThreadShell.snoozedUntil,
2656 timestampFormat,
2657 onChange: async (limitRecovery) => {
2658 const result = await updateThreadMetadata({
2659 environmentId,
2660 input: { threadId: activeThreadShell.id, limitRecovery },
2661 });
2662 if (result._tag === "Failure") throw squashAtomCommandFailure(result);
2663 },
2664 }
2665 : null,
2666 messages,
2667 );
2668 const composerBannerItems = (() => {
2669 const fallbackSelection = draftFallback?.selection;
2670 const defaultSelection =
2671 draftDefaultModelSelection ??
2672 resolveProjectDefaultProviderModelSelection(
2673 providerStatuses,
2674 settings,
2675 draftThread?.projectId ?? null,
2676 );
2677 const fallback =
2678 !isServerThread &&
2679 multipleModelSelections === null &&
2680 !composerModelSelectionExplicit &&
2681 draftFallback?.fallback &&
2682 (!composerSelectedModelSelection ||
2683 (composerSelectedModelSelection.instanceId === fallbackSelection?.instanceId &&
2684 composerSelectedModelSelection.model === fallbackSelection?.model))
2685 ? draftFallback.fallback
2686 : null;
2687 const fallbackWindow = fallback
2688 ? `${fallback.provider.instanceId}:${fallback.resetsAt ?? ""}`
2689 : null;
2690 const fallbackItems: ComposerBannerStackItem[] =
2691 fallback &&
2692 fallbackSelection &&
2693 defaultSelection &&
2694 fallbackWindow !== dismissedFallbackWindow
2695 ? [
2696 modelFallbackBannerItem(
2697 {
2698 fallbackModelName:
2699 providerStatuses
2700 .find((provider) => provider.instanceId === fallbackSelection.instanceId)
2701 ?.models.find((model) => model.slug === fallbackSelection.model)?.name ??
2702 fallbackSelection.model,
2703 defaultProviderName: fallback.provider.displayName ?? fallback.provider.driver,
2704 defaultModelName:
2705 fallback.provider.models.find((model) => model.slug === defaultSelection.model)
2706 ?.name ?? defaultSelection.model,
2707 resetsAt: fallback.resetsAt,
2708 timestampFormat,
2709 onUseDefault: () =>
2710 onProviderModelSelectStable(defaultSelection.instanceId, defaultSelection.model),
2711 onDismiss: () => setDismissedFallbackWindow(fallbackWindow),
2712 },
2713 messages,
2714 ),
2715 ]
2716 : [];
2717 const limitRecoveryItems = limitRecoveryBanner === null ? [] : [limitRecoveryBanner];
2718 const extensionStatusBanner = extensionStatusBannerItem(
2719 deriveProviderExtensionStatuses(serverProjection),
2720 );
2721 const extensionStatusItems = extensionStatusBanner === null ? [] : [extensionStatusBanner];
2722 const usageLimitsItems = usageLimitsBanner === null ? [] : [usageLimitsBanner];
2723 const projectCloneItems = projectCloneBannerItem === null ? [] : [projectCloneBannerItem];
2724 // An approval's feedback goes to that approval; the armed session waits for the next message.
2725 const freshSessionItems =
2726 freshSessionPending && activePendingApproval === null
2727 ? [freshSessionBannerItem(() => disarmFreshSession(routeThreadKey), messages)]
2728 : [];
2729 if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {
2730 return [
2731 ...feedbackBannerItems,
2732 ...fallbackItems,
2733 ...limitRecoveryItems,
2734 ...extensionStatusItems,
2735 ...usageLimitsItems,
2736 ...projectCloneItems,
2737 ...freshSessionItems,
2738 ...systemComposerBannerItems,
2739 ];
2740 }
2741 return [
2742 ...feedbackBannerItems,
2743 ...fallbackItems,
2744 ...limitRecoveryItems,
2745 ...extensionStatusItems,
2746 ...usageLimitsItems,
2747 ...projectCloneItems,
2748 ...freshSessionItems,
2749 ...systemComposerBannerItems,
2750 branchMismatchBannerItem(
2751 {
2752 mismatchKey: activeBranchMismatchKey,
2753 mismatch: localCheckoutBranchMismatch,
2754 restoreDisabled: !canWriteSourceControl || isRestoringThreadBranch,
2755 restoring: isRestoringThreadBranch,
2756 onRestore: handleRestoreThreadBranchStable,
2757 onDismiss: () => {
2758 dismissBranchMismatchForSession(activeBranchMismatchKey);
2759 setBranchMismatchDismissTick((tick) => tick + 1);
2760 },
2761 },
2762 messages,
2763 ),
2764 ];
2765 })() as ComposerBannerStackItem[];
2766
2767 if (
2768 terminalUiLaunchContext !== null &&
2769 (terminalUiLaunchContext.threadId !== activeThreadId ||
2770 !terminalUiState.terminalOpen ||
2771 (activeProjectCwd !== null &&
2772 projectScriptCwd({
2773 project: { cwd: activeProjectCwd },
2774 worktreePath: activeThreadWorktreePath,
2775 }) === terminalUiLaunchContext.cwd &&
2776 (activeThreadWorktreePath ?? null) === terminalUiLaunchContext.worktreePath))
2777 ) {
2778 setTerminalUiLaunchContext(null);
2779 }
2780
2781 const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({
2782 terminalFocus: getTerminalFocusOwner() !== null,
2783 terminalOpen: Boolean(terminalUiState.terminalOpen),
2784 previewFocus: isPreviewFocused(),
2785 previewOpen: previewPanelOpen,
2786 rightPanelOpen,
2787 editableFocus: isEditableFocused(eventTarget),
2788 modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,
2789 composerFocus:
2790 document.activeElement?.getAttribute("data-testid") === "composer-editor" &&
2791 isInSideChatPane(document.activeElement) === embedded,
2792 draftThreadRoute: routeKind === "draft",
2793 turnRunning: phase === "running" || phase === "connecting",
2794 // A queued-message edit or a question's answer owns the composer even when its text is empty.
2795 composerEmpty:
2796 !queuedRunEdit.isEditing &&
2797 pendingUserInputs.length === 0 &&
2798 !composerHasNonPromptContent &&
2799 promptRef.current.trim().length === 0,
2800 composerRequiresModifier: composerRequiresModifier(settings.sendShortcut, promptRef.current),
2801 isWeb: !isElectron,
2802 isDesktop: isElectron,
2803 });
2804 const getShortcutContextStable = useStableCallback(getShortcutContext);
2805 const timelineSkills = activeProviderStatus
2806 ? resolveProviderSkillsForCwd(activeProviderStatus, gitCwd)
2807 : EMPTY_PROVIDER_SKILLS;
2808 const threadFindEnabled = isServerThread && serverConfig?.threadFind === true;
2809 const isThreadFindActive = useThreadFindOpen(activeThreadRef, threadFindEnabled);
2810 const openThreadFindStable = useStableCallback((threadRef: ScopedThreadRef) => {
2811 if (threadFindEnabled && scopedThreadKey(threadRef) === activeThreadKey) {
2812 openThreadFind(activeThreadKey);
2813 }
2814 });
2815
2816 useChatShortcuts({
2817 enabled: activeThreadId !== null && !backgroundThread,
2818 embedded,
2819 composerElement: composerOverlayElement,
2820 keybindings,
2821 scriptKeybindings,
2822 getShortcutContext,
2823 threadFindActive: isThreadFindActive,
2824 composerRef,
2825 branchToolbarRef,
2826 closeThreadFind: () => {
2827 closeThreadFind();
2828 focusComposerStable();
2829 },
2830 commands: {
2831 ...terminalShortcuts,
2832 ...rightPanelShortcuts,
2833 ...threadLifecycleShortcuts,
2834 "thread.copyReference": ({ event }) => {
2835 if (!event.repeat) copyActiveThreadReference();
2836 },
2837 "chat.find": () => {
2838 if (!isServerThread || serverConfig?.threadFind !== true || activeThreadKey === null)
2839 return false;
2840 openThreadFind(activeThreadKey);
2841 },
2842 "composer.cycleHost": ({ event }) => {
2843 if (!canChangeEnvironment) return false;
2844 if (event.repeat) return;
2845 const currentId = readPendingEnvironmentChange()?.environmentId ?? environmentId;
2846 const index = logicalProjectEnvironments.findIndex(
2847 (env) => env.environmentId === currentId,
2848 );
2849 const next = logicalProjectEnvironments[(index + 1) % logicalProjectEnvironments.length];
2850 if (next) onEnvironmentChangeStable(next.environmentId);
2851 },
2852 "thread.steerQueuedMessage": ({ event }) =>
2853 routeKind !== "draft" && queuedRunsControlRef.current?.steerNext(event.repeat) === true,
2854 "thread.editQueuedMessage": ({ event }) =>
2855 routeKind !== "draft" &&
2856 composerRef.current?.isCaretAtStart() === true &&
2857 queuedRunsControlRef.current?.editLatest(event.repeat) === true,
2858 "thread.stop": ({ event }) => {
2859 if (!canInterruptRunningThread) return false;
2860 if (!event.repeat) void onInterruptStable();
2861 },
2862 },
2863 fallback: (command) => {
2864 const scriptId = projectScriptIdFromCommand(command);
2865 if (!scriptId || !activeProject || !canOperateTerminal) return undefined;
2866 const script = activeProjectScripts.find((entry) => entry.id === scriptId);
2867 return script ? () => void runProjectScriptStable(script) : undefined;
2868 },
2869 });
2870
2871 const closeActiveRightPanelSurfaceStable = useStableCallback(() => {
2872 if (activeRightPanelSurface) closeRightPanelSurface(activeRightPanelSurface);
2873 });
2874
2875 // A focused desktop browser page forwards these chords as menu actions.
2876 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to desktop bridge menu actions that toggle or close the right panel
2877 useEffect(() => {
2878 if (embedded || backgroundThread) return;
2879 return window.desktopBridge?.onMenuAction((action) => {
2880 if (action === "rightPanel.toggle") toggleRightPanelStable();
2881 else if (action === "rightPanel.toggleMaximized") toggleRightPanelMaximizedStable();
2882 else if (action === "rightPanel.close") closeActiveRightPanelSurfaceStable();
2883 });
2884 }, [
2885 embedded,
2886 backgroundThread,
2887 toggleRightPanelStable,
2888 toggleRightPanelMaximizedStable,
2889 closeActiveRightPanelSurfaceStable,
2890 ]);
2891
2892 usePasteToFocusComposer(embedded ? null : activeThreadId, composerRef);
2893 // A delegated task is a remote thread's subagent.
2894 const isSubagentThread =
2895 activeThread?.lineage.relationshipToParent === "subagent" || delegatedFrom !== null;
2896 // Side chats do not nest or start from subagents, and older servers would fork a listed thread.
2897 const sideChatsOffered =
2898 !embedded &&
2899 canOperateThread &&
2900 activeThread?.lineage.sideChat !== true &&
2901 !isSubagentThread &&
2902 serverConfig?.environment.capabilities.sideChats === true;
2903 const sideChat = useSideChat({
2904 threadRef: sideChatsOffered && isServerThread ? activeThreadRef : null,
2905 readSettings: () => ({
2906 runtimeMode,
2907 modelSelection: composerRef.current?.getSendContext().selectedModelSelection,
2908 }),
2909 onError: (message) => {
2910 if (activeThread) setThreadError(activeThread.id, message);
2911 },
2912 });
2913 // An embedded thread's commands run in its host's terminal, which is the host's checkout.
2914 const runsOutsideHostCheckout =
2915 embedded && (activeThread?.worktreePath ?? null) !== (panelHostShell?.worktreePath ?? null);
2916 // A maximized panel covers the terminal drawer the command runs in.
2917 const runSideChatShellCommandStable = useStableCallback((command: string) => {
2918 if (activeThreadRef) useRightPanelStore.getState().setMaximized(activeThreadRef, false);
2919 runShellCommandStable(command);
2920 });
2921 // Main-thread surfaces show this reason; `/side` sent anyway gets it as a toast.
2922 const sideChatDisabledReason =
2923 activeThread?.lineage.sideChat === true
2924 ? gt("Side chats cannot start side chats.")
2925 : isSubagentThread
2926 ? gt("Subagent threads cannot start side chats.")
2927 : serverConfig === null
2928 ? gt("Side chats are not ready yet. Try again in a moment.")
2929 : serverConfig.environment.capabilities.sideChats !== true
2930 ? gt("Update this environment's T3 Code server to use side chats.")
2931 : sideChatsOffered && !isServerThread
2932 ? gt("Side chats start after the first message.")
2933 : sideChat.available &&
2934 orchestrationV2WorktreePending(
2935 activeThread?.worktreePath ?? null,
2936 serverProjection?.runs ?? [],
2937 )
2938 ? gt("Available once the thread's worktree is set up.")
2939 : null;
2940 const openSideChatStable = useStableCallback(() => void sideChat.open());
2941 const openSurfaceInMainView = useOpenSurfaceInMainView(activeThreadRef);
2942 const sendSideChatStable = useStableCallback(sideChat.open);
2943 const { onConfirmRevertStable, onForkFromRunStable, onRevertTimelineTurnStable } =
2944 useTimelineRewind({
2945 environmentId,
2946 routeThreadRef,
2947 routeThreadKey,
2948 currentRouteThreadKeyRef,
2949 serverProjection,
2950 activeThread,
2951 timelineMessages,
2952 phase,
2953 isSendBusy,
2954 isRevertingCheckpoint,
2955 supportsConversationRollback,
2956 activeEnvironmentUnavailable,
2957 activeEnvironmentUnavailableLabel,
2958 promptRef,
2959 composerRef,
2960 composerDraftTarget,
2961 setThreadError,
2962 });
2963 const onCompactContext = () => {
2964 if (compactDisabled) return;
2965 void sendStandaloneCommand("/compact", gt("Failed to compact context."));
2966 };
2967
2968 const {
2969 getModelDisabledReason,
2970 handleRuntimeModeChangeStable,
2971 onEnvModeChangeStable,
2972 onProviderModelSelectStable,
2973 onStartFromOriginChange,
2974 openProviderSetupStable,
2975 } = useComposerSelection({
2976 environmentId,
2977 composerDraftTarget,
2978 draftThread,
2979 activeThread,
2980 activeRuntime,
2981 activeProjectSettings,
2982 settings,
2983 providerStatuses,
2984 lockedProvider,
2985 supportsProviderSwitchingViaHandoff,
2986 multipleModelSelections,
2987 runtimeMode,
2988 isLocalDraftThread,
2989 canOverrideServerThreadEnvMode,
2990 setPendingServerThreadEnvModeEntry,
2991 setPendingServerThreadStartFromOriginByThreadId,
2992 scheduleComposerFocus: scheduleComposerFocusStable,
2993 });
2994 const { onResume, isResuming } = useComposerResume({
2995 environmentId,
2996 routeThreadKey,
2997 currentRouteThreadKeyRef,
2998 activeThread,
2999 resumableRunId,
3000 hasHeldQueuedRuns,
3001 canResume,
3002 isSendBusy,
3003 isRevertingCheckpoint,
3004 threadDetailLoading,
3005 activeEnvironmentUnavailable,
3006 runtimeMode,
3007 localCheckoutBranchMismatch,
3008 composerRef,
3009 persistThreadSettingsForNextTurn,
3010 clearUsageLimitsFor,
3011 scrollToEnd,
3012 setThreadError,
3013 });
3014 const { onSend } = useComposerSend({
3015 environmentId,
3016 routeThreadKey,
3017 currentRouteThreadKeyRef,
3018 draftId,
3019 draftThread,
3020 activeThread,
3021 activeThreadKey,
3022 activeThreadBranch,
3023 activeProject,
3024 activeProjectIsScratch,
3025 activeProjectDefaultModelSelection,
3026 activeMessageCount,
3027 isServerThread,
3028 isLocalDraftThread,
3029 isGitRepo,
3030 phase,
3031 runtimeMode,
3032 sendEnvMode,
3033 startFromOrigin,
3034 localCheckoutBranchMismatch,
3035 logicalProjectEnvironments,
3036 providerInstanceEntries,
3037 composerRef,
3038 composerDraftTarget,
3039 promptRef,
3040 composerImagesRef,
3041 composerFilesRef,
3042 composerTerminalContextsRef,
3043 feedbackUploadsInFlightRef,
3044 queuedRunEdit,
3045 isRevertingCheckpoint,
3046 threadDetailLoading,
3047 activeEnvironmentUnavailable,
3048 isSendBusy,
3049 sendQueuesBehindSetup,
3050 isDraftHeroState,
3051 panelAnimationsActive,
3052 panelAnimationDurationMs,
3053 keepFullHistory,
3054 freshSessionAvailable: freshSessionCommandAvailable,
3055 resumeCompactionTokens,
3056 usageLimitsKey,
3057 usageLimitsOffered,
3058 openUsageLimits,
3059 clearUsageLimitsFor,
3060 needsLoadBalancing,
3061 loadBalancing,
3062 refreshBeforeSend,
3063 readPendingEnvironmentChange,
3064 pendingApprovals,
3065 respondingRequestIds,
3066 activePendingUserInput,
3067 onAdvanceActivePendingUserInput,
3068 onRespondToApproval: onRespondToApprovalStable,
3069 beginLocalDispatch,
3070 resetLocalDispatch,
3071 beginWorktreeSetup,
3072 captureDraftHeroComposerRect,
3073 setDockedDraftHeroThreadKey,
3074 setSetupQueueSendThreadKey,
3075 setOptimisticUserMessages,
3076 optimisticBlobPreviews: {
3077 track: (message) => optimisticBlobPreviews.track(threadId, message),
3078 release: (message) => optimisticBlobPreviews.release(threadId, message),
3079 },
3080 setFeedbackSubmissionsByThreadKey,
3081 setThreadError,
3082 setKeepFullHistory,
3083 anchorNewTurn,
3084 acknowledgeActiveThreadWoke,
3085 onSideChat: sideChat.available ? sendSideChatStable : undefined,
3086 sideChatDisabledReason,
3087 handleNewThreadInActiveProject,
3088 persistThreadSettingsForNextTurn,
3089 linkCheckoutPullRequest,
3090 });
3091
3092 const onWorktreeSetupWorkLocally = () => {
3093 if (!worktreeSetup || worktreeSetup.phase !== "running" || !draftId) {
3094 return;
3095 }
3096 void cancelWorktreeSetup().then((cancelled) => {
3097 if (cancelled) setWorkLocallyResendDraftId(draftId);
3098 });
3099 };
3100 const onWorktreeSetupWorkLocallyStable = useStableCallback(onWorktreeSetupWorkLocally);
3101 const onComposerSendStable = useStableCallback(onSend);
3102 const sendPreviewAnnotation = (
3103 annotation: PreviewAnnotationPayload,
3104 image: ComposerImageAttachment | null,
3105 ) => {
3106 void onSend(undefined, "auto", "foreground", { annotation, image });
3107 };
3108 const sendPreviewAnnotationStable = useStableCallback(sendPreviewAnnotation);
3109 const onComposerResumeStable = useStableCallback(onResume);
3110 const onComposerCompactContextStable = useStableCallback(onCompactContext);
3111 // Read from the projection the footer renders, so the scroll below sees the new message.
3112 const pendingGuestMessageIds =
3113 serverProjection?.thread.guestShare?.messages.flatMap((message) =>
3114 message.status === "pending" ? [message.id] : [],
3115 ) ?? [];
3116 const pendingGuestMessageCount = pendingGuestMessageIds.length;
3117 const pendingGuestMessageKey = pendingGuestMessageIds.join(",");
3118 const previousPendingGuestMessagesRef = useRef({
3119 threadKey: routeThreadKey,
3120 key: pendingGuestMessageKey,
3121 });
3122 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the timeline list to the end when a new pending guest message joins its footer
3123 useEffect(() => {
3124 const previous = previousPendingGuestMessagesRef.current;
3125 previousPendingGuestMessagesRef.current = {
3126 threadKey: routeThreadKey,
3127 key: pendingGuestMessageKey,
3128 };
3129 // Opening another thread is not a new message; its own scroll position wins.
3130 if (previous.threadKey !== routeThreadKey) return;
3131 // Pending guest messages sit in the list footer, which the list does not follow on its own.
3132 // The follow flag reflects the owner's position before the footer grew; a live measure may not.
3133 // Any new id counts, even when another one was resolved in the same update.
3134 const previousIds = new Set(previous.key.split(","));
3135 const hasNewMessage = pendingGuestMessageKey
3136 .split(",")
3137 .some((id) => id !== "" && !previousIds.has(id));
3138 if (hasNewMessage && timelineLiveFollowEnabled) scrollToEnd(true);
3139 }, [routeThreadKey, pendingGuestMessageKey, timelineLiveFollowEnabled, scrollToEnd]);
3140 const onExpandTimelineImage = (preview: ExpandedImagePreview) => {
3141 openExpandedImagePreview(routeThreadKey, preview);
3142 };
3143 const onExpandTimelineImageStable = useStableCallback(onExpandTimelineImage);
3144 const queuedRunsControl =
3145 isServerThread && activeThread ? (
3146 <>
3147 <QueuedRunsControl
3148 ref={queuedRunsControlRef}
3149 steerShortcutLabel={shortcutLabelForCommand(keybindings, "thread.steerQueuedMessage", {
3150 context: { terminalFocus: false },
3151 })}
3152 editShortcutLabel={shortcutLabelForCommand(keybindings, "thread.editQueuedMessage", {
3153 context: { composerFocus: true },
3154 })}
3155 environmentId={activeThread.environmentId}
3156 threadId={activeThread.id}
3157 optimisticMessages={optimisticUserMessages}
3158 editingRunId={queuedRunEdit.editingRunId}
3159 editBlockedReason={queuedRunEditBlockedReason(
3160 { openQuestionCount: pendingUserInputs.length },
3161 messages,
3162 )}
3163 onEditQueuedRun={queuedRunEdit.beginEdit}
3164 onCancelEdit={queuedRunEdit.cancelEdit}
3165 timestampFormat={timestampFormat}
3166 onOpenThread={onOpenRelatedThreadStable}
3167 onImageExpand={onExpandTimelineImageStable}
3168 />
3169 </>
3170 ) : null;
3171 const resendAfterWorkLocally = () => {
3172 setWorkLocallyResendDraftId(null);
3173 void onComposerSendStable();
3174 };
3175 const resendAfterWorkLocallyStable = useStableCallback(resendAfterWorkLocally);
3176 const workLocallyResendReady =
3177 workLocallyResendDraftId !== null &&
3178 workLocallyResendDraftId === draftId &&
3179 isLocalDraftThread &&
3180 !isSendBusy &&
3181 !isRevertingCheckpoint &&
3182 !threadDetailLoading &&
3183 clientSettingsHydrated &&
3184 !needsLoadBalancing &&
3185 !activeEnvironmentUnavailable &&
3186 !activePendingUserInput &&
3187 !feedbackUploading;
3188 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- switches the draft to local mode, then resends the waiting message once sending is idle
3189 useEffect(() => {
3190 if (
3191 !workLocallyResendReady ||
3192 sendInFlightRef.current ||
3193 feedbackUploadsInFlightRef.current.has(routeThreadKey)
3194 ) {
3195 return;
3196 }
3197 if (sendEnvMode !== "local") {
3198 setDraftThreadContext(composerDraftTarget, { envMode: "local", startFromOrigin: false });
3199 return;
3200 }
3201 resendAfterWorkLocallyStable();
3202 }, [
3203 composerDraftTarget,
3204 feedbackUploadsInFlightRef,
3205 resendAfterWorkLocallyStable,
3206 sendInFlightRef,
3207 routeThreadKey,
3208 sendEnvMode,
3209 setDraftThreadContext,
3210 workLocallyResendReady,
3211 ]);
3212
3213 const shownThreadSyncPhase = activeEnvironmentUnavailable ? null : delayedThreadSyncPhase;
3214 const hasThreadNow =
3215 attentionNow !== null || workNow !== null || goalNow !== null || shownThreadSyncPhase !== null;
3216 const queuedRunCount = serverProjection ? getUserQueuedThreadRuns(serverProjection).length : 0;
3217 // The queue control is mounted for every server thread but joins the footer only while it shows
3218 // something, by its own rule: an optimistic message stops counting once the server has it.
3219 const hasQueuedTurns =
3220 queuedRunCount > 0 ||
3221 optimisticUserMessages.some(
3222 (message) =>
3223 message.inputIntent === "queued_turn" &&
3224 !serverProjection?.messages.some((committed) => committed.id === message.id),
3225 );
3226 const scrollToEndSummary =
3227 [
3228 childInputNow?.waitingLabel ?? null,
3229 queuedRunCount === 0
3230 ? null
3231 : gt("{count, plural, one {{count} queued} other {{count} queued}}", {
3232 count: queuedRunCount,
3233 }),
3234 ]
3235 .filter((part) => part !== null)
3236 .join(" · ") || null;
3237 // The end of the timeline holds the thread's present and next turns: what it is doing now,
3238 // its lifecycle status, guest messages awaiting you, then your queued messages.
3239 const timelineFooter =
3240 pendingHandoff === null &&
3241 !hasThreadNow &&
3242 threadStatusLine === null &&
3243 pendingGuestMessageCount === 0 &&
3244 !hasQueuedTurns ? null : (
3245 <>
3246 {pendingHandoff === null ? null : (
3247 <div className="chat-content-lane">
3248 <HandoffRow
3249 environmentId={environmentId}
3250 endpoints={pendingHandoff}
3251 providers={providerStatuses}
3252 pending
3253 />
3254 </div>
3255 )}
3256 <ThreadNow
3257 key={routeThreadKey}
3258 attention={attentionNow}
3259 work={workNow}
3260 syncPhase={shownThreadSyncPhase}
3261 goal={goalNow}
3262 />
3263 {threadStatusLine}
3264 {pendingGuestMessageCount > 0 && isServerThread && activeThread ? (
3265 <GuestPendingMessages
3266 threadRef={scopeThreadRef(activeThread.environmentId, activeThread.id)}
3267 onImageExpand={onExpandTimelineImageStable}
3268 onFileOpen={openFileAttachmentStable}
3269 />
3270 ) : null}
3271 {hasQueuedTurns ? queuedRunsControl : null}
3272 </>
3273 );
3274
3275 const pendingSidebarFileDrops = useSidebarPendingFileDropStore((state) => state.pending);
3276 const consumePendingFileDrop = useSidebarPendingFileDropStore(
3277 (state) => state.consumePendingFileDrop,
3278 );
3279 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hands pending sidebar file drops to the composer's imperative API once it mounts
3280 useEffect(() => {
3281 if (pendingSidebarFileDrops.length === 0) return;
3282 if (
3283 typeof composerDraftTarget === "string" ||
3284 !pendingSidebarFileDrops.some((drop) =>
3285 isSameSidebarThreadRef(composerDraftTarget, drop.threadRef),
3286 )
3287 ) {
3288 return;
3289 }
3290 if (!activeThread) return;
3291 if (!composerRef.current) {
3292 const raf = window.requestAnimationFrame(() => {
3293 if (!composerRef.current || typeof composerDraftTarget === "string") return;
3294 const files = consumePendingFileDrop(composerDraftTarget);
3295 if (files !== null) composerRef.current?.addDroppedFiles(files);
3296 });
3297 return () => window.cancelAnimationFrame(raf);
3298 }
3299 const files = consumePendingFileDrop(composerDraftTarget);
3300 if (files !== null) composerRef.current.addDroppedFiles(files);
3301 }, [
3302 activeThread,
3303 composerDraftTarget,
3304 composerRef,
3305 consumePendingFileDrop,
3306 pendingSidebarFileDrops,
3307 ]);
3308
3309 const addDroppedFilesToComposer = useStableCallback(
3310 (files: Parameters<ChatComposerHandle["addDroppedFiles"]>[0]) =>
3311 composerRef.current?.addDroppedFiles(files),
3312 );
3313 const addDroppedFoldersToComposer = useStableCallback(
3314 (folders: Parameters<ChatComposerHandle["addDroppedFolders"]>[0]) =>
3315 composerRef.current?.addDroppedFolders(folders),
3316 );
3317 // Above the early return, where React Compiler can cache it for the side chat pane.
3318 const sideChatParentPanel = {
3319 hostRef: scopeThreadRef(environmentId, threadId),
3320 openToolDiff: onOpenToolDiffStable,
3321 runShellCommand: runSideChatShellCommandStable,
3322 };
3323
3324 if (!activeThread) {
3325 return embedded ? null : <NoActiveThreadState />;
3326 }
3327
3328 const rightPanelContent = activeThreadRef ? (
3329 <RightPanelSurfaceContent
3330 surface={renderedRightPanelSurface}
3331 activeSurfaceId={activeRightPanelSurface?.id ?? null}
3332 threadRef={activeThreadRef}
3333 environmentId={activeThread.environmentId}
3334 visible={rightPanelOpen}
3335 composerDraftTarget={composerDraftTarget}
3336 keybindings={keybindings}
3337 configuredPreviewUrls={configuredPreviewUrls}
3338 workspaceMutationId={workspaceMutationId}
3339 getShortcutContext={getShortcutContextStable}
3340 onSendAnnotation={sendPreviewAnnotationStable}
3341 onCloseSurface={closeRightPanelSurface}
3342 sideChatParentPanel={sideChatParentPanel}
3343 terminal={{
3344 launchContext: activeTerminalLaunchContext ?? null,
3345 keybindings,
3346 onAddTerminalContext: addTerminalContextToDraftStable,
3347 onSplitTerminal: splitPanelTerminalStable,
3348 onSplitTerminalVertical: splitPanelTerminalVerticalStable,
3349 onNewTerminal: addTerminalSurfaceStable,
3350 onActiveTerminalChange: activatePanelTerminalStable,
3351 onCloseTerminal: closePanelTerminalStable,
3352 splitShortcutLabel: splitTerminalShortcutLabel ?? undefined,
3353 splitVerticalShortcutLabel: splitTerminalVerticalShortcutLabel ?? undefined,
3354 newShortcutLabel: newTerminalShortcutLabel ?? undefined,
3355 closeShortcutLabel: closeTerminalShortcutLabel ?? undefined,
3356 }}
3357 pullRequest={{
3358 capabilityKnown: pullRequestsCapabilityKnown,
3359 supported: supportsPullRequests,
3360 projectId: activeThread.projectId,
3361 pullRequests: visiblePullRequests,
3362 linkedPullRequest: linkedThreadPullRequest,
3363 branchPullRequest: activeThreadShell?.branchPullRequest ?? activeThread.branchPullRequest,
3364 onBack:
3365 pullRequestsSurfaceAvailable && visiblePullRequestCount > 1
3366 ? addPullRequestsSurfaceStable
3367 : undefined,
3368 }}
3369 issuesSupported={serverConfig?.environment.capabilities.issues === true}
3370 files={{
3371 projectId: activeProject?.id,
3372 projectName: activeProject?.title ?? null,
3373 workspaceRoot: activeWorkspaceRoot,
3374 availableEditors,
3375 pendingSurfaceIds: pendingFileSurfaceIds,
3376 onOpenFile: openFileSurfaceStable,
3377 onPendingChange: handleFilePendingChangeStable,
3378 }}
3379 />
3380 ) : null;
3381 const panelToggleControlProps = {
3382 terminalAvailable: activeProject !== null,
3383 terminalOpen: terminalUiState.terminalOpen,
3384 terminalShortcutLabel: shortcutLabelForCommand(keybindings, "terminal.toggle"),
3385 threadPanelOpen,
3386 threadPanelPresentation,
3387 threadPanelPopoverHandle,
3388 threadPanelShortcutLabel: shortcutLabelForCommand(keybindings, "threadPanel.toggle"),
3389 rightPanelAvailable: activeProject !== null,
3390 rightPanelOpen,
3391 rightPanelShortcutLabel: shortcutLabelForCommand(keybindings, "rightPanel.toggle"),
3392 onToggleTerminal: toggleTerminalVisibilityStable,
3393 onToggleThreadPanel: toggleThreadPanelStable,
3394 onToggleRightPanel: toggleRightPanelStable,
3395 } satisfies PanelLayoutControlsProps;
3396 const panelToggleControls = (
3397 <PanelLayoutControls
3398 {...panelToggleControlProps}
3399 showThreadPanelControl={!inlineRightPanelOwnsTitleBar}
3400 />
3401 );
3402 const threadPanelHeaderControl = <ThreadPanelHeaderControl {...panelToggleControlProps} />;
3403 const panelLayoutControls = (
3404 <WorkspaceTitlebarControls
3405 showMaximizeControl={!shouldUsePlanSidebarSheet}
3406 rightPanelOpen={rightPanelOpen}
3407 animationsActive={panelAnimationsActive}
3408 maximized={rightPanelMaximized}
3409 onToggleMaximized={toggleRightPanelMaximizedStable}
3410 >
3411 {panelToggleControls}
3412 </WorkspaceTitlebarControls>
3413 );
3414 const workspaceFileDropHandlers = makeWorkspaceFileDropHandlers({
3415 setDragActive: setIsWorkspaceFileDragActive,
3416 addFiles: addDroppedFilesToComposer,
3417 addFolders: addDroppedFoldersToComposer,
3418 });
3419
3420 const content = (
3421 <div
3422 ref={setWorkspaceLayoutElement}
3423 className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background"
3424 >
3425 {embedded ? null : (
3426 <DeviceSetupDialogHost
3427 threadKey={activeThreadKey}
3428 threadRef={activeThreadRef}
3429 state={deviceState}
3430 />
3431 )}
3432 {rightPanelControlsAtRoot && !embedded ? panelLayoutControls : null}
3433 <div
3434 className={cn(
3435 "flex min-h-0 min-w-0 flex-col overflow-x-hidden",
3436 rightPanelMaximized ? "w-0 flex-none" : "flex-1",
3437 )}
3438 data-chat-column-maximized-away={rightPanelMaximized ? "true" : "false"}
3439 data-chat-column
3440 inert={rightPanelMaximized}
3441 onMouseUp={preventMiddleClickPasteOutsideEditable}
3442 >
3443 {embedded ? null : (
3444 <header
3445 ref={threadPanelPopoverAnchorRef}
3446 data-chat-header
3447 className={cn(
3448 "relative bg-background [[data-panel-animations=true]_&]:motion-safe:transition-[padding-left] [[data-panel-animations=true]_&]:motion-safe:duration-(--panel-animation-duration) [[data-panel-animations=true]_&]:motion-safe:ease-out",
3449 isElectron
3450 ? cn(
3451 "drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 sm:px-5",
3452 reserveTitleBarControlInset &&
3453 !inlineRightPanelOwnsTitleBar &&
3454 "wco:pr-(--workspace-native-controls-inset)",
3455 )
3456 : "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center pl-(--workspace-gutter-start) pr-(--workspace-gutter-end)",
3457 COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
3458 )}
3459 >
3460 {isElectron && rightPanelControlsAtRoot ? (
3461 <span
3462 aria-hidden
3463 className="pointer-events-none fixed top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] h-[var(--workspace-topbar-height)] w-28 [-webkit-app-region:no-drag]"
3464 />
3465 ) : null}
3466 {!rightPanelControlsAtRoot && !rightPanelControlsInPanel ? panelLayoutControls : null}
3467 {inlineRightPanelOwnsTitleBar ? threadPanelHeaderControl : null}
3468 <ChatHeader
3469 activeThreadEnvironmentId={activeThread.environmentId}
3470 activeThreadId={activeThread.id}
3471 isServerThread={isServerThread}
3472 activeThreadTitle={activeThread.title}
3473 activeThreadLinkOrigin={activeThreadShell?.linkOrigin?.label ?? null}
3474 activeProject={activeProject ?? null}
3475 parentThreadLink={headerParentThreadLink}
3476 onOpenThread={onOpenRelatedThreadStable}
3477 rightPanelOpen={inlineRightPanelOwnsTitleBar}
3478 onNewThreadInProject={handleNewThreadInActiveProjectStable}
3479 {...(activeDraftLogicalProjectKey
3480 ? { onOpenProjectSettings: handleOpenDraftProjectSettingsStable }
3481 : {})}
3482 {...(threadFindEnabled ? { onFindInThread: openThreadFindStable } : {})}
3483 />
3484 </header>
3485 )}
3486
3487 <div className="relative flex min-h-0 min-w-0 flex-1">
3488 <ThreadFindCanvas
3489 findOptions={{
3490 skills: timelineSkills,
3491 progressive: serverConfig?.threadFindProgressive === true,
3492 thread: activeThreadRef,
3493 enabled: threadFindEnabled,
3494 }}
3495 store={chatCanvasStore}
3496 threadRef={activeThreadRef}
3497 preview={canvasPreview}
3498 detailsCardTopInset={isThreadFindActive ? THREAD_FIND_BAR_RESERVED_HEIGHT : 0}
3499 composerOverlayElement={isDraftHeroState ? null : composerOverlayElement}
3500 data-chat-workspace-drop-target="true"
3501 onDragEnter={workspaceFileDropHandlers.onDragEnter}
3502 onDragOver={workspaceFileDropHandlers.onDragOver}
3503 onDragLeave={workspaceFileDropHandlers.onDragLeave}
3504 onDrop={workspaceFileDropHandlers.onDrop}
3505 >
3506 <ThreadFind onClose={focusComposerStable} />
3507 {isWorkspaceFileDragActive ? <WorkspaceFileDropOverlay /> : null}
3508 <ChatBannerLane
3509 environmentId={activeThread.environmentId}
3510 providerStatus={visibleProviderStatus}
3511 providerStatusDismissalKey={providerStatusDismissalKey}
3512 onOpenProviderSetup={openProviderSetupStable}
3513 threadId={activeThread.id}
3514 threadError={timelineThreadError}
3515 threadErrorClass={
3516 threadErrorIsServerRuntimeError ? (serverRuntime?.lastErrorClass ?? null) : null
3517 }
3518 threadErrorCode={
3519 threadErrorIsServerRuntimeError ? (serverRuntime?.lastErrorCode ?? null) : null
3520 }
3521 threadErrorBannerKey={threadErrorBannerKey}
3522 setThreadError={setThreadError}
3523 setThreadErrorBannerDismissTick={setThreadErrorBannerDismissTick}
3524 />
3525 <div
3526 {...conversationArea}
3527 className="relative flex min-h-0 flex-1 flex-col bg-background"
3528 >
3529 <WorkspaceMutationIdContext value={workspaceMutationId}>
3530 <ThreadTimeline
3531 pendingApprovals={pendingApprovals}
3532 heldApprovalRequestIds={heldApprovalRequestIds}
3533 respondingRequestIds={respondingRequestIds}
3534 onRespondToApproval={onRespondToApprovalStable}
3535 canOperateThread={canOperateThread}
3536 threadDetailRef={routeThreadDetailRef}
3537 entriesInput={timelineEntriesInput}
3538 draftEntries={isServerThread ? null : draftTimelineEntries}
3539 activeThreadKey={activeThreadKey}
3540 syncing={threadSyncPhase !== null}
3541 detailLoading={threadDetailLoading}
3542 citationRequest={citationRequest}
3543 citationHistory={citationHistory}
3544 onCiteAssistantText={citeAssistantTextStable}
3545 onReplyToResponse={replyToResponseStable}
3546 {...(activeProject && !runsOutsideHostCheckout
3547 ? { onRunShellCommand: parentPanel?.runShellCommand ?? runShellCommandStable }
3548 : {})}
3549 isWorking={isWorking}
3550 runlessWorkActive={runlessWorkStartedAt !== null}
3551 isCompacting={isCompacting}
3552 awaitingUser={
3553 activePendingApproval !== null
3554 ? "approval"
3555 : activePendingUserInput !== null ||
3556 // A secret request has no runtime request; the shell carries it.
3557 activeThreadShell?.hasPendingUserInput === true
3558 ? "input"
3559 : null
3560 }
3561 awaitingRequestId={
3562 activePendingApproval?.requestId ?? activePendingUserInput?.requestId ?? null
3563 }
3564 activeTurnStartedAt={activeWorkStartedAt}
3565 providerStartingLabel={
3566 activeActivityRun?.providerStartingLabelMsg
3567 ? messages(activeActivityRun.providerStartingLabelMsg)
3568 : null
3569 }
3570 worktreeSetup={worktreeSetup}
3571 onCancelWorktreeSetup={onCancelWorktreeSetupStable}
3572 retryableWorkspacePreparationRunIds={retryableWorkspacePreparationRunIds}
3573 onRetryWorkspacePreparation={onRetryWorkspacePreparationStable}
3574 {...(draftId
3575 ? { onWorktreeSetupWorkLocally: onWorktreeSetupWorkLocallyStable }
3576 : {})}
3577 {...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}
3578 isPreparingWorktree={isPreparingWorktree}
3579 footer={timelineFooter}
3580 listRef={legendListRef}
3581 runs={serverProjection?.runs ?? []}
3582 latestRun={activeActivityRun}
3583 announcedRun={announcedRun(activeActivityRun, serverProjection?.runs ?? [])}
3584 detailBehindShell={isDetailBehindShell(
3585 activeLatestRun,
3586 activeThreadShell?.latestRun ?? null,
3587 )}
3588 runningRunId={activeRunningTurnId}
3589 turnDiffSummaries={turnDiffSummaries}
3590 activeThreadEnvironmentId={
3591 displayedThreadRef?.environmentId ?? activeThread.environmentId
3592 }
3593 routeThreadKey={displayedTimelineKey}
3594 displayThreadKey={displayedTimelineKey}
3595 announceTurnStatus={!isProviderSubagent}
3596 onOpenToolDiff={parentPanel?.openToolDiff ?? onOpenToolDiffStable}
3597 // Side chat runs keep no checkpoints to diff, and a fork would promote the side chat.
3598 {...(embedded
3599 ? {}
3600 : { onOpenTurnDiff: onOpenTurnDiffStable, onForkFromRun: onForkFromRunStable })}
3601 onOpenThread={onOpenRelatedThreadStable}
3602 parentThreadLink={parentThreadLink}
3603 workflowOpening={workflowOpening}
3604 supportsConversationRollback={supportsConversationRollback}
3605 threadStartCheckpointAvailable={threadStartCheckpointAvailable}
3606 availableRevertTurnCounts={availableRevertTurnCounts}
3607 onRevertToTurnCount={onRevertTimelineTurnStable}
3608 onUseArtifactTemplate={insertArtifactTemplateStable}
3609 onSendAppMessage={sendAppMessageStable}
3610 isRevertingCheckpoint={isRevertingCheckpoint}
3611 onImageExpand={onExpandTimelineImageStable}
3612 onFileOpen={openFileAttachmentStable}
3613 onFileDownload={downloadFileAttachmentStable}
3614 markdownCwd={gitCwd ?? undefined}
3615 resolvedTheme={resolvedTheme}
3616 timestampFormat={timestampFormat}
3617 workspaceRoot={activeWorkspaceRoot}
3618 skills={timelineSkills}
3619 anchorMessageId={timelineAnchorMessageId}
3620 onAnchorReady={onTimelineAnchorReadyStable}
3621 onAnchorSizeChanged={onTimelineAnchorSizeChangedStable}
3622 contentInsetEndAdjustment={composerTimelineInset}
3623 liveFollowEnabled={timelineLiveFollowEnabled}
3624 onIsAtEndChange={onIsAtEndChangeStable}
3625 onViewportAttach={attachTimelineViewport}
3626 onFooterGrow={onTimelineFooterGrowStable}
3627 hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}
3628 emptyPlaceholderInset={composerReservedHeight}
3629 topFadeEnabled={!hasTimelineTopBanner}
3630 {...(threadHistoryControls === undefined
3631 ? {}
3632 : { historyControls: threadHistoryControls })}
3633 />
3634 </WorkspaceMutationIdContext>
3635
3636 {showScrollToBottom && !isThreadFindActive && (
3637 <ScrollToEndButton
3638 bottom={scrollToEndClearance + 4}
3639 summary={scrollToEndSummary}
3640 onScrollToEnd={() => scrollToEnd(true)}
3641 />
3642 )}
3643 </div>
3644
3645 <div
3646 {...workspaceAreaProps(
3647 "composer",
3648 2,
3649 showProviderSubagentBar ? "Subagent" : undefined,
3650 )}
3651 ref={(overlay: HTMLDivElement | null) => {
3652 setComposerOverlayElement(overlay);
3653 attachFollowComposerOverlay(overlay);
3654 }}
3655 inert={isRevertingCheckpoint}
3656 data-chat-composer-overlay="true"
3657 className={
3658 isDraftHeroState
3659 ? "pointer-events-none absolute inset-0 z-20 flex items-center [@media(max-height:34rem)]:items-end"
3660 : "pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
3661 }
3662 >
3663 <div ref={draftHeroTransitionGroupRef} className="chat-composer-lane w-full">
3664 <div
3665 data-chat-composer-stack="true"
3666 className="group/composer-stack pointer-events-auto relative z-10 mx-auto w-full max-w-(--chat-content-max-width)"
3667 >
3668 {isDraftHeroState ? (
3669 <div className="absolute inset-x-0 bottom-full">
3670 <div
3671 className="pb-4 group-has-data-[composer-shoulder-tab]/composer-stack:pb-0"
3672 style={
3673 forceExpandedMobileComposer
3674 ? { viewTransitionName: MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME }
3675 : undefined
3676 }
3677 >
3678 <DraftHeroHeadline
3679 draftId={draftId}
3680 activeProjectRef={activeProjectRef}
3681 activeProjectTitle={activeProject?.title ?? null}
3682 />
3683 </div>
3684 </div>
3685 ) : null}
3686 <div
3687 ref={draftHeroComposerAnchorRef}
3688 className="relative z-10"
3689 style={
3690 forceExpandedMobileComposer
3691 ? { viewTransitionName: MOBILE_COMPOSER_VIEW_TRANSITION_NAME }
3692 : undefined
3693 }
3694 >
3695 <ChildThreadApprovals threadRef={activeThreadRef} />
3696 <div className="relative">
3697 <ComposerSurface.Shell contextRow={showComposerContextStrip}>
3698 <ComposerSurface.Host
3699 inert={queuedRunEdit.isSaving}
3700 aria-busy={queuedRunEdit.isSaving}
3701 >
3702 <div className="relative z-10">
3703 {showProviderSubagentBar ? (
3704 <ProviderSubagentBar
3705 provider={selectedProviderEntry ?? null}
3706 showInstanceBadge={
3707 selectedProviderEntry !== undefined &&
3708 shouldShowInstanceBadge(
3709 selectedProviderEntry,
3710 providerInstanceEntries,
3711 )
3712 }
3713 modelLabel={providerSubagentModelLabel}
3714 effortLabel={providerSubagentEffortLabel}
3715 status={providerSubagentStatus}
3716 onOpenParent={parentThreadLink?.open ?? null}
3717 actions={
3718 selectedProviderEntry?.driverKind === "antigravity" ? (
3719 <NativeChildWorkDialog
3720 environmentId={environmentId}
3721 threadId={threadId}
3722 />
3723 ) : null
3724 }
3725 />
3726 ) : null}
3727 {!composerMounted ? null : (
3728 <ChatComposer
3729 canOperateThread={canOperateThread}
3730 reportedModelSelection={reportedModelSelection}
3731 multipleModelSelections={multipleModelSelections}
3732 supportsMultipleModels={
3733 serverConfig?.environment.capabilities
3734 .requiredWorktreeBootstrap === true
3735 }
3736 onMultipleModelSelectionsChange={setMultipleModelSelectionsStable}
3737 composerRef={composerRef}
3738 composerDraftTarget={composerDraftTarget}
3739 environmentId={environmentId}
3740 attachmentUploadsCapabilityKnown={attachmentUploadsCapabilityKnown}
3741 supportsAttachmentUploads={supportsAttachmentUploads}
3742 supportsQuestionAttachments={supportsQuestionAttachments}
3743 maxFileAttachmentBytes={maxFileAttachmentBytes}
3744 routeKind={routeKind}
3745 routeThreadRef={routeThreadRef}
3746 draftId={draftId}
3747 activeThreadId={activeThreadId}
3748 activeThread={activeThread}
3749 activeThreadRuns={serverProjection?.runs ?? EMPTY_RUNS}
3750 promptHistoryEntries={timelineEntries}
3751 forceExpandedOnMobile={
3752 forceExpandedMobileComposer && isDraftHeroState
3753 }
3754 projectSelectionRequired={
3755 isLocalDraftThread && activeProject === null
3756 }
3757 phase={phase}
3758 canSteer={!compactionBlocksSteer}
3759 canInterrupt={canInterruptRunningThread}
3760 isSendBusy={
3761 (isSendBusy && !sendQueuesBehindSetup) ||
3762 (setupQueueSendThreadKey !== null &&
3763 setupQueueSendThreadKey === activeThreadKey) ||
3764 queuedRunEdit.isSaving ||
3765 isResuming
3766 }
3767 canResume={canResume}
3768 isRevertingCheckpoint={isRevertingCheckpoint}
3769 sendDisabledReason={
3770 !canOperateThread
3771 ? gt("This connection cannot change threads.")
3772 : isEnvironmentChanging
3773 ? gt("Preparing machine")
3774 : isRevertingCheckpoint
3775 ? gt("Rewinding conversation")
3776 : feedbackUploading
3777 ? gt("Sending feedback")
3778 : threadDetailLoading
3779 ? gt("Messages loading")
3780 : worktreeSetupBlocksSend
3781 ? gt("Preparing worktree")
3782 : projectCloneSendBlockReason
3783 }
3784 isPreparingWorktree={isPreparingWorktree && !sendQueuesBehindSetup}
3785 bannerItems={
3786 isDraftHeroState || composerBannerItems.length === 0
3787 ? EMPTY_COMPOSER_BANNER_ITEMS
3788 : composerBannerItems
3789 }
3790 resumeCompactionTokens={resumeCompactionTokens}
3791 keepFullHistory={keepFullHistory}
3792 onToggleKeepFullHistory={toggleKeepFullHistoryStable}
3793 sideChatAvailable={sideChat.available}
3794 sideChatDisabledReason={sideChatDisabledReason}
3795 onFreshSession={
3796 freshSessionCommandAvailable ? armFreshSessionStable : undefined
3797 }
3798 onUsageLimitsCommand={
3799 usageLimitsOffered &&
3800 usageLimitsKey !== null &&
3801 !composerHasNonPromptContent
3802 ? openUsageLimits
3803 : undefined
3804 }
3805 environmentUnavailable={activeEnvironmentUnavailableState}
3806 activePendingApproval={activePendingApproval}
3807 pendingApprovals={pendingApprovals}
3808 onHeldRequestIdsChange={onHeldRequestIdsChange}
3809 pendingUserInputs={pendingUserInputs}
3810 activePendingIsResponding={activePendingIsResponding}
3811 respondingRequestIds={respondingRequestIds}
3812 runtimeMode={runtimeMode}
3813 defaultRuntimeMode={defaultRuntimeMode}
3814 lockedProvider={modelPickerLockedProvider}
3815 providerStatuses={providerStatuses as ServerProvider[]}
3816 providerCatalogKnown={serverConfig !== null}
3817 activeProjectDefaultModelSelection={
3818 activeProjectDefaultModelSelection
3819 }
3820 activeThreadModelSelection={activeThread?.modelSelection}
3821 activeProjectId={activeProject?.id ?? null}
3822 projectName={activeProject?.title}
3823 compactThreadUnavailable={compactThreadUnavailable}
3824 compactDisabled={compactDisabled}
3825 resolvedTheme={resolvedTheme}
3826 settings={settings}
3827 keybindings={keybindings}
3828 getShortcutContext={getShortcutContextStable}
3829 terminalOpen={Boolean(terminalUiState.terminalOpen)}
3830 gitCwd={gitCwd}
3831 pullRequestProjectId={
3832 supportsPullRequests ? (activeProject?.id ?? null) : null
3833 }
3834 pullRequestRepository={
3835 supportsPullRequests ? activeProjectRepository : null
3836 }
3837 threadPullRequests={
3838 (activeThreadShell ?? activeThread)?.pullRequests
3839 }
3840 onComposerOverlayHeightChange={publishComposerOverlayHeightStable}
3841 permissionsShownInStrip={
3842 showComposerContextStrip && !isServerThread
3843 }
3844 promptRef={promptRef}
3845 composerImagesRef={composerImagesRef}
3846 composerFilesRef={composerFilesRef}
3847 composerTerminalContextsRef={composerTerminalContextsRef}
3848 onPageScrollKeyDown={onComposerPageScrollKeyDownStable}
3849 onPageScrollKeyUp={onComposerPageScrollKeyUpStable}
3850 onPageScrollRelease={onComposerPageScrollReleaseStable}
3851 onCompactContext={onComposerCompactContextStable}
3852 onSend={onComposerSendStable}
3853 onResume={onComposerResumeStable}
3854 onInterrupt={onInterruptStable}
3855 onSelectActivePendingUserInputOption={
3856 onSelectActivePendingUserInputOptionStable
3857 }
3858 onAdvanceActivePendingUserInput={
3859 onAdvanceActivePendingUserInputStable
3860 }
3861 onDismissActivePendingUserInput={onDismissUserInputStable}
3862 onPreviousActivePendingUserInputQuestion={
3863 onPreviousActivePendingUserInputQuestionStable
3864 }
3865 onChangeActivePendingUserInputCustomAnswer={
3866 onChangeActivePendingUserInputCustomAnswer
3867 }
3868 onProviderModelSelect={onProviderModelSelectStable}
3869 onOpenProviderSetup={openProviderSetupStable}
3870 getModelDisabledReason={getModelDisabledReason}
3871 handleRuntimeModeChange={handleRuntimeModeChangeStable}
3872 focusComposer={focusComposerStable}
3873 scheduleComposerFocus={scheduleComposerFocusStable}
3874 setThreadError={setThreadError}
3875 onExpandImage={onExpandTimelineImageStable}
3876 onFileOpen={openFileAttachmentStable}
3877 editingQueuedAttachments={queuedRunEdit.editingAttachments}
3878 onRemoveEditingQueuedAttachment={
3879 queuedRunEdit.removeEditingAttachment
3880 }
3881 />
3882 )}
3883 </div>
3884 </ComposerSurface.Host>
3885 <div className="min-h-0">
3886 <div
3887 data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}
3888 className="relative z-0"
3889 >
3890 {showComposerContextStrip && (
3891 <div className="pointer-events-auto">
3892 <BranchToolbar
3893 forceNewWorktree={multipleModelSelections !== null}
3894 ref={branchToolbarRef}
3895 environmentId={activeThread.environmentId}
3896 threadId={activeThread.id}
3897 projectId={activeThread.projectId}
3898 worktreePath={activeThread.worktreePath}
3899 isServerThread={isServerThread}
3900 showGitControls={isGitRepo}
3901 {...(routeKind === "draft" && draftId ? { draftId } : {})}
3902 onEnvModeChange={onEnvModeChangeStable}
3903 startFromOrigin={startFromOrigin}
3904 onStartFromOriginChange={onStartFromOriginChange}
3905 envMode={envMode}
3906 {...(canOverrideServerThreadEnvMode
3907 ? {
3908 activeThreadBranchOverride: activeThreadBranch,
3909 onActiveThreadBranchOverrideChange:
3910 setPendingServerThreadBranch,
3911 }
3912 : {})}
3913 envLocked={envLocked}
3914 onComposerFocusRequest={scheduleComposerFocusStable}
3915 {...(canCheckoutPullRequestIntoThread
3916 ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }
3917 : {})}
3918 {...(canChangeEnvironment
3919 ? { onEnvironmentChange: onEnvironmentChangeStable }
3920 : {})}
3921 autoEnvironmentLabel={autoEnvironmentLabel}
3922 onAutoEnvironment={
3923 draftId &&
3924 !envLocked &&
3925 canAutoBalanceEnvironments &&
3926 loadBalancingSettings.loadBalancingEnabled
3927 ? onAutoEnvironmentStable
3928 : undefined
3929 }
3930 availableEnvironments={logicalProjectEnvironments}
3931 {...(isServerThread
3932 ? {}
3933 : {
3934 trailing: (
3935 <ComposerContextPermissions
3936 environmentId={environmentId}
3937 runtimeMode={runtimeMode}
3938 supportedRuntimeModes={
3939 activeProviderStatus?.supportedRuntimeModes
3940 }
3941 onRuntimeModeChange={handleRuntimeModeChangeStable}
3942 />
3943 ),
3944 })}
3945 />
3946 </div>
3947 )}
3948 </div>
3949 </div>
3950 </ComposerSurface.Shell>
3951 {isDraftHeroState && composerBannerItems.length > 0 ? (
3952 // Out of flow, like the headline, so a notice never moves the centered composer.
3953 // Short windows pin the composer to the bottom, where an out-of-flow notice
3954 // would fall off-screen, so there it takes space and lifts the composer.
3955 <div className="absolute inset-x-0 top-full flex flex-col gap-1 pt-4 [@media(max-height:34rem)]:static">
3956 <ComposerBannerStack items={composerBannerItems} detached />
3957 </div>
3958 ) : null}
3959 </div>
3960 <div
3961 aria-hidden
3962 className="h-[calc(env(safe-area-inset-bottom)+1rem)] sm:h-[calc(env(safe-area-inset-bottom)+1.25rem)]"
3963 />
3964 </div>
3965 </div>
3966 </div>
3967 </div>
3968
3969 {canOperatePreview && activeThreadRef && activeEnvironmentServerBrowser && !embedded ? (
3970 <PreviewSessionSync threadRef={activeThreadRef} />
3971 ) : null}
3972 {activeThreadRef && shownPreviewMiniPlayer && !embedded ? (
3973 <ThreadPreviewMiniPlayer
3974 key={`${activeThreadKey}:${previewMiniPlayerSourceKey(shownPreviewMiniPlayer.source)}`}
3975 threadRef={activeThreadRef}
3976 miniPlayer={shownPreviewMiniPlayer}
3977 />
3978 ) : null}
3979
3980 {embedded ? null : (
3981 <>
3982 <BranchRestoreConfirmHost
3983 threadKey={activeThreadKey}
3984 threadBranch={localCheckoutBranchMismatch?.threadBranch ?? ""}
3985 canWriteSourceControl={canWriteSourceControl}
3986 onConfirm={handleSwitchCheckoutToThreadStable}
3987 />
3988
3989 <ThreadDetailsPanel
3990 anchor={threadPanelPopoverAnchorRef}
3991 handle={threadPanelPopoverHandle}
3992 forceNewWorktree={multipleModelSelections !== null}
3993 environmentId={activeThread.environmentId}
3994 threadId={activeThread.id}
3995 projectId={activeThread.projectId}
3996 worktreePath={activeThread.worktreePath}
3997 isServerThread={isServerThread}
3998 {...(draftId ? { draftId } : {})}
3999 composerDraftTarget={composerDraftTarget}
4000 activeProjectName={activeProject?.title}
4001 activeProjectScripts={activeProject ? activeProjectScripts : undefined}
4002 preferredScriptId={
4003 activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
4004 }
4005 keybindings={keybindings}
4006 availableEditors={availableEditors}
4007 showOpenInPicker={showOpenInPicker}
4008 openInShortcutEnabled={
4009 !(
4010 rightPanelOpen &&
4011 renderedRightPanelSurface?.kind === "file" &&
4012 renderedRightPanelSurface.attachment === undefined
4013 )
4014 }
4015 gitCwd={gitCwd}
4016 workspaceMutationId={workspaceMutationId}
4017 isGitRepo={isGitRepo}
4018 envLocked={envLocked}
4019 availableEnvironments={logicalProjectEnvironments}
4020 autoEnvironmentLabel={autoEnvironmentLabel}
4021 onAutoEnvironment={
4022 draftId &&
4023 !envLocked &&
4024 canAutoBalanceEnvironments &&
4025 loadBalancingSettings.loadBalancingEnabled
4026 ? onAutoEnvironmentStable
4027 : undefined
4028 }
4029 {...(canChangeEnvironment
4030 ? { onEnvironmentChange: onEnvironmentChangeStable }
4031 : {})}
4032 onEnvModeChange={onEnvModeChangeStable}
4033 envMode={envMode}
4034 {...(canOverrideServerThreadEnvMode
4035 ? {
4036 activeThreadBranchOverride: activeThreadBranch,
4037 onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
4038 }
4039 : {})}
4040 startFromOrigin={startFromOrigin}
4041 onStartFromOriginChange={onStartFromOriginChange}
4042 {...(canCheckoutPullRequestIntoThread
4043 ? { onCheckoutPullRequestRequest: openPullRequestDialogStable }
4044 : {})}
4045 onComposerFocusRequest={scheduleComposerFocusStable}
4046 {...(isServerThread && isGitRepo
4047 ? { onOpenChanges: openChangesFromThreadPanelStable }
4048 : {})}
4049 onRunProjectScript={runProjectScriptStable}
4050 onAddProjectScript={saveProjectScriptStable}
4051 onUpdateProjectScript={updateProjectScriptStable}
4052 onDeleteProjectScript={deleteProjectScriptStable}
4053 usage={{
4054 providerInstanceId: activeProviderInstanceId,
4055 model: activeUsageModel,
4056 providers: providerStatuses,
4057 sources: serverConfig?.usageLimitSources ?? EMPTY_USAGE_LIMIT_SOURCES,
4058 contextWindow: activeContextWindow,
4059 }}
4060 />
4061
4062 <PullRequestThreadDialogHost
4063 threadKey={activeThreadKey}
4064 environmentId={activeThread.environmentId}
4065 threadId={activeThread.id}
4066 cwd={activeProject?.workspaceRoot ?? null}
4067 onPrepared={handlePreparedPullRequestThreadStable}
4068 />
4069 </>
4070 )}
4071 </ThreadFindCanvas>
4072 </div>
4073
4074 {embedded ? null : (
4075 <ChatTerminalDrawers
4076 activeThreadKey={activeThreadKey}
4077 activeTerminalOpen={Boolean(terminalUiState.terminalOpen)}
4078 composerHeight={composerReservedHeight}
4079 launchContext={activeTerminalLaunchContext ?? null}
4080 splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
4081 splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
4082 newShortcutLabel={newTerminalShortcutLabel ?? undefined}
4083 closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}
4084 keybindings={keybindings}
4085 onAddTerminalContext={addTerminalContextToDraftStable}
4086 />
4087 )}
4088 </div>
4089
4090 {rightPanelPresent && activeThreadRef && !embedded ? (
4091 <ChatRightPanel
4092 sheet={shouldUsePlanSidebarSheet}
4093 workspaceLayoutElement={workspaceLayoutElement}
4094 widthStorageKey={`t3code:preview-panel-width:${activeThreadKey}`}
4095 sheetAnimationDurationMs={panelAnimationsActive ? panelAnimationDurationMs : 0}
4096 onCloseSheet={closePreviewPanelStable}
4097 open={rightPanelOpen}
4098 keybindings={keybindings}
4099 getShortcutContext={getShortcutContextStable}
4100 maximized={rightPanelMaximized}
4101 layoutControls={
4102 rightPanelOpen ? (
4103 <div className="mr-px flex items-center gap-1">
4104 <RightPanelMaximizeControl
4105 maximized={rightPanelMaximized}
4106 onToggle={toggleRightPanelMaximizedStable}
4107 />
4108 {panelToggleControls}
4109 </div>
4110 ) : null
4111 }
4112 surfaces={renderedRightPanelSurfaces}
4113 environmentId={activeThreadRef.environmentId}
4114 activeSurfaceId={renderedRightPanelSurface?.id ?? null}
4115 pendingSurfaceIds={pendingFileSurfaceIds}
4116 previewSessions={activePreviewState.sessions}
4117 desktopByTabId={activePreviewState.desktopByTabId}
4118 previewRuntimeTabId={resolvePreviewRuntimeTabId}
4119 terminalLabelsById={activeTerminalLabelsById}
4120 onActivate={activateRightPanelSurfaceStable}
4121 onCloseSurface={closeRightPanelSurfaceStable}
4122 onOpenInMainView={openSurfaceInMainView}
4123 onRenameDevice={(surfaceId, title) => {
4124 if (activeThreadRef)
4125 useRightPanelStore.getState().renameDevice(activeThreadRef, surfaceId, title);
4126 }}
4127 onCloseOtherSurfaces={closeOtherRightPanelSurfacesStable}
4128 onCloseSurfacesToRight={closeRightPanelSurfacesToRightStable}
4129 onCloseAllSurfaces={closeAllRightPanelSurfacesStable}
4130 onMoveSurface={moveRightPanelSurfaceStable}
4131 onCopyFilePath={copyRightPanelFilePathStable}
4132 onAddBrowser={() => createBrowserSurface()}
4133 onAddBrowserInProfile={createBrowserSurfaceStable}
4134 onAddTerminal={addTerminalSurfaceStable}
4135 onAddDiff={addDiffSurfaceStable}
4136 onAddFiles={addFilesSurfaceStable}
4137 onAddPullRequest={addPullRequestSurfaceStable}
4138 onAddPullRequests={addPullRequestsSurfaceStable}
4139 onAddDevice={addDeviceSurfaceStable}
4140 onAddSideChat={sideChatsOffered ? openSideChatStable : undefined}
4141 browserAvailable={canOperatePreview && browserAvailable}
4142 terminalAvailable={activeProject !== null && canOperateTerminal}
4143 diffAvailable={isServerThread && isGitRepo}
4144 filesAvailable={activeProject !== null}
4145 pullRequestAvailable={pullRequestSurfaceAvailable}
4146 pullRequestsAvailable={linkedItemsSurfaceAvailable}
4147 deviceAvailable={activeThreadRef !== null}
4148 sideChatAvailable={sideChat.available}
4149 sideChatDisabledReason={sideChatDisabledReason}
4150 >
4151 {rightPanelContent}
4152 </ChatRightPanel>
4153 ) : null}
4154
4155 <RevertConfirmHost
4156 threadKey={routeThreadKey}
4157 checkpoints={serverProjection?.checkpoints}
4158 worktreePath={activeThread?.worktreePath ?? null}
4159 onConfirm={onConfirmRevertStable}
4160 />
4161 {embedded ? null : <LinkPullRequestDialogHost />}
4162 <ThreadVisitWatermark threadRef={routeThreadRef} />
4163 <ExpandedImageDialogHost threadKey={routeThreadKey} />
4164 </div>
4165 );
4166 return (
4167 <FileMetadataThreadProvider
4168 threadRef={activeThreadRef}
4169 cwd={activeWorkspaceRoot}
4170 checkpoints={serverProjection?.checkpoints}
4171 >
4172 {content}
4173 </FileMetadataThreadProvider>
4174 );
4175 }
4176
4177 // Chromium on Linux pastes PRIMARY into the focused editable unless the middle mouseup is cancelled.
4178 function preventMiddleClickPasteOutsideEditable(event: ReactMouseEvent) {
4179 if (event.button !== 1 || isEditableFocused(event.target)) return;
4180 event.preventDefault();
4181 }
4182
4183 function PreviewSessionSync(props: { readonly threadRef: ScopedThreadRef }) {
4184 usePreviewSession(props.threadRef);
4185 return null;
4186 }