Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadRouteScreen.tsx

1,399 lines53.6 KB

1import * as Dialog from "../../components/ui/Dialog";
2import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
3import { useRememberThreadProject } from "./useRememberThreadProject";
4import { useOpenPullRequest } from "../../native/useOpenPullRequest";
5import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
6import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
7import { useWorktreeSetup } from "./use-worktree-setup";
8import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
9import { AppBar } from "../../components/ui/AppBar";
10import {
11 StackActions,
12 useIsFocused,
13 useNavigation,
14 useRoute,
15 type StaticScreenProps,
16} from "@react-navigation/native";
17import {
18 createContext,
19 use,
20 useEffect,
21 useEffectEvent,
22 useRef,
23 useState,
24 type ReactNode,
25} from "react";
26import { useGT, useMessages } from "gt-react-native";
27import * as Option from "effect/Option";
28import {
29 AuthOrchestrationOperateScope,
30 AuthTerminalOperateScope,
31 AuthTerminalReadScope,
32 DEFAULT_SERVER_SETTINGS,
33 EnvironmentId,
34 isProviderNativeSubagentThread,
35 MessageId,
36 ThreadId,
37 type ProjectScript,
38} from "@t3tools/contracts";
39import {
40 projectScriptCwd,
41 projectScriptRuntimeEnv,
42 projectScriptTerminalInput,
43 resolveProjectScripts,
44} from "@t3tools/shared/projectScripts";
45import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
46import { useConnectionsReady } from "../../state/workspace";
47import { useEnvironmentShellReadiness } from "../../state/shell";
48import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
49import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
50import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
51import { useEnvironmentQuery } from "../../state/query";
52import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
53import { vcsEnvironment } from "../../state/vcs";
54import { LoadingScreen } from "../../components/LoadingScreen";
55import { Platform, Pressable, View } from "react-native";
56import { HeaderHeightContext } from "@react-navigation/elements";
57import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
58import { AppText as Text } from "../../components/ui/AppText";
59import { cn } from "../../lib/cn";
60import { scopedThreadKey } from "../../lib/scopedEntities";
61import { useDelayedStatus } from "../../lib/useDelayedStatus";
62import { connectionRetryLabel } from "./floating-working-status";
63import { scopeThreadRef } from "@t3tools/client-runtime/environment";
64import { useThreadShell } from "../../state/entities";
65import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
66import { connectionTone } from "../connection/connectionTone";
67import { runtimeConnectionErrorText } from "../connection/environmentStatusText";
68import {
69 useRemoteConnections,
70 useRemoteConnectionStatus,
71 useRemoteEnvironmentRuntime,
72} from "../../state/use-remote-environment-registry";
73import { useKnownTerminalSessions } from "../../state/use-terminal-session";
74import { uuidv4 } from "../../lib/uuid";
75import {
76 isAtomCommandInterrupted,
77 squashAtomCommandFailure,
78} from "@t3tools/client-runtime/state/runtime";
79import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
80import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
81import { useThreadSelection } from "../../state/use-thread-selection";
82import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
83import {
84 buildTerminalMenuSessions,
85 nextOpenTerminalId,
86 resolveProjectScriptTerminalId,
87} from "../terminal/terminalMenu";
88import {
89 resolvePreferredThreadWorktreePath,
90 stagePendingTerminalLaunch,
91} from "../terminal/terminalLaunchContext";
92import type { ThreadDetailScreenProps } from "./ThreadDetailScreen";
93import { ThreadScreenBinding, ThreadScreenFallback, ThreadScreenHost } from "./ThreadScreenHost";
94import { draftRouteIdentity } from "./thread-route-state";
95import { NewTaskDraftRouteScreen, type NewTaskDraftRouteParams } from "./NewTaskDraftRouteScreen";
96import { GitOverviewSheet } from "./git/GitOverviewSheet";
97import { useAtomCommand } from "../../state/use-atom-command";
98import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
99import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
100import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
101import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
102import { useThreadComposerState } from "../../state/use-thread-composer-state";
103import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
104import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
105import { threadEnvironment } from "../../state/threads";
106import { threadErrorText } from "@t3tools/client-runtime/state/threads";
107import { useProjects } from "../../state/entities";
108import {
109 projectThreadContentPresentation,
110 THREAD_CONTENT_READY,
111 threadSyncStatusLabel,
112} from "./threadContentPresentation";
113import {
114 Inspector,
115 useAdaptiveWorkspaceLayout,
116 useWorkspacePaneState,
117} from "../layout/AdaptiveWorkspaceLayout";
118import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
119import { InspectorSheetContext } from "../layout/workspace-inspector-sheet";
120import type { InspectorContent } from "../layout/inspector-panes";
121import {
122 threadDetailErrorIsCurrent,
123 threadRouteConnectionWait,
124 threadRouteIsHydrating,
125 threadRouteOpensDraft,
126 threadUnavailableReason,
127 type ThreadUnavailableReason,
128} from "./thread-route-hydration";
129import { ThreadHeader } from "./ThreadHeader";
130import { resumeThread } from "./resume-thread";
131import {
132 useAndroidWorkspaceBack,
133 useWorkspaceBackNavigation,
134} from "../layout/workspace/useAndroidWorkspaceNavigation";
135import { ThreadInspectorHeader, type ThreadInspectorPresentation } from "./thread-inspector-header";
136import { InspectorContentScope, ThreadInspectorPreview } from "./thread-inspector-preview";
137import { useStartSideChat } from "./useStartSideChat";
138import { useThreadStatusAnnouncements } from "./useThreadStatusAnnouncements";
139import type { ThreadInspectorMode, ThreadInspectorTarget } from "./thread-inspector-navigation";
140import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
141​
142function firstRouteParam(value: string | string[] | undefined): string | null {
143 const first = Array.isArray(value) ? value[0] : value;
144 return first === undefined || first.trim().length === 0 ? null : first;
146​
147const RECONNECT_ERROR_DELAY_MS = 5_000;
148const UNREACHABLE_WAIT_SETTLE_MS = 1_000;
149​
150// The inspector pane's bar belongs to ThreadInspectorHeader; the fallback must not draw its own.
151const InspectorHeaderShownContext = createContext(false);
152​
153function ThreadRouteFallbackLayout(props: {
154 readonly children: ReactNode;
155 readonly subtitle?: string;
156}) {
157 const gt = useGT();
158 const goBack = useWorkspaceBackNavigation();
159 const inspectorHeaderShown = use(InspectorHeaderShownContext);
160 return (
161 <ThreadScreenFallback
162 header={
163 inspectorHeaderShown ? undefined : (
164 <AppBar
165 title={gt("Thread")}
166 {...(props.subtitle === undefined ? {} : { subtitle: props.subtitle })}
167 onBackToList={goBack}
168 hideBottomBorder
169 />
170 )
171 }
172 >
173 {props.children}
174 </ThreadScreenFallback>
175 );
177​
178function OpeningThreadLoadingScreen() {
179 const gt = useGT();
180 return (
181 <ThreadRouteFallbackLayout>
182 <LoadingScreen message={gt("Opening thread…")} messagePlacement="above-spinner" embedded />
183 </ThreadRouteFallbackLayout>
184 );
186​
187type ThreadRouteScreenRouteProps = StaticScreenProps<{
188 readonly environmentId?: string;
189 readonly threadId?: string;
190 readonly draft?: NewTaskDraftRouteParams;
191 readonly inspector?: ThreadInspectorTarget;
192 readonly prompt?: string | string[];
193}>;
194​
195interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
196 readonly inspectorPresentation?: ThreadInspectorPresentation;
197 readonly onReturnToThread?: () => void;
198 readonly renderInspector?: () => ReactNode;
200​
201/** A centered message column for the thread route, the same width on every screen. */
202function ThreadRouteMessage(props: {
203 readonly title: string;
204 readonly detail: string;
205 readonly subtitle?: string;
206 readonly children: ReactNode;
207}) {
208 // iOS draws the header over this view. Even padding keeps the block centered on the whole screen
209 // while text too large to fit still starts below the header and scrolls.
210 const headerInset = use(HeaderHeightContext) ?? 0;
211 const inset = Platform.OS === "ios" ? headerInset : 0;
212 return (
213 <ThreadRouteFallbackLayout
214 {...(props.subtitle === undefined ? {} : { subtitle: props.subtitle })}
215 >
216 <ScreenScrollView
217 className="flex-1"
218 contentInsetAdjustmentBehavior="never"
219 contentContainerClassName="flex-grow items-center justify-center px-8"
220 contentContainerStyle={{ paddingTop: inset, paddingBottom: inset }}
221 >
222 {/* One fixed width for every message, so the buttons are the same size on each screen. The
223 bottom margin lifts the block a little above center, where it reads as centered. */}
224 <View className="mb-24 w-[256px] max-w-full items-center">
225 <Text textRole="title" className="text-center font-t3-bold text-foreground">
226 {props.title}
227 </Text>
228 <Text
229 textRole="body"
230 className="mt-1.5 text-center font-sans leading-normal text-foreground-muted"
231 >
232 {props.detail}
233 </Text>
234 <View className="mt-6 flex-row justify-center gap-2 self-stretch">{props.children}</View>
235 </View>
236 </ScreenScrollView>
237 </ThreadRouteFallbackLayout>
238 );
240​
241/** One of the thread route's pill buttons; they split the message column's width evenly. */
242function ThreadRouteButton(props: {
243 readonly label: string;
244 readonly onPress: () => void;
245 readonly tone: "primary" | "secondary";
246 readonly busy?: boolean;
247}) {
248 const busy = props.busy === true;
249 return (
250 <Pressable
251 accessibilityRole="button"
252 accessibilityState={{ disabled: busy, busy }}
253 disabled={busy}
254 onPress={props.onPress}
255 className={cn(
256 "min-h-[44px] flex-1 flex-row items-center justify-center gap-2 rounded-full px-3 active:opacity-70 android:min-h-[48px]",
257 props.tone === "primary" ? "bg-primary" : "border border-foreground/15",
258 busy && "opacity-55",
259 )}
260 >
261 {busy ? <AppActivityIndicator size={14} colorClassName="accent-primary-foreground" /> : null}
262 {/* Large text sizes shrink the label rather than clip it, so both buttons keep their width. */}
263 <Text
264 textRole="footnote"
265 numberOfLines={1}
266 adjustsFontSizeToFit
267 minimumFontScale={0.7}
268 className={cn(
269 "shrink font-t3-bold",
270 props.tone === "primary" ? "text-primary-foreground" : "text-foreground",
271 )}
272 >
273 {props.label}
274 </Text>
275 </Pressable>
276 );
278​
279function ThreadUnavailableScreen(props: {
280 readonly reason: ThreadUnavailableReason;
281 readonly environment: string;
282 readonly onReconnect: () => void;
283 readonly onOpenConnections: () => void;
284 readonly onAddEnvironment: () => void;
285}) {
286 const gt = useGT();
287 const { environment } = props;
288 if (props.reason === "unknown-environment") {
289 return (
290 <ThreadRouteMessage
291 title={gt("Environment not added")}
292 detail={gt("Add it to open this thread.")}
293 >
294 <ThreadRouteButton
295 tone="primary"
296 label={gt("Add environment")}
297 onPress={props.onAddEnvironment}
298 />
299 </ThreadRouteMessage>
300 );
301 }
302 if (props.reason === "unsupported") {
303 // The supervisor pauses an incompatible environment, so Reconnect could not help here.
304 return (
305 <ThreadRouteMessage
306 title={gt("Client not supported")}
307 detail={gt("Use compatible versions of the app and server to connect.")}
308 subtitle={environment}
309 >
310 <ThreadRouteButton
311 tone="primary"
312 label={gt("Connections")}
313 onPress={props.onOpenConnections}
314 />
315 </ThreadRouteMessage>
316 );
317 }
318 const switchedOff = props.reason === "switched-off";
319 return (
320 <ThreadRouteMessage
321 title={
322 switchedOff ? gt("{environment} is switched off", { environment }) : gt("Thread not found")
323 }
324 detail={
325 switchedOff
326 ? gt("Turn it on to open this thread.")
327 : gt("It may be deleted or not on {environment}.", { environment })
328 }
329 subtitle={environment}
330 >
331 <ThreadRouteButton
332 tone="primary"
333 label={
334 switchedOff ? gt("Turn on", { $context: "switch an environment on" }) : gt("Reconnect")
335 }
336 onPress={props.onReconnect}
337 />
338 <ThreadRouteButton
339 tone="secondary"
340 label={gt("Connections")}
341 onPress={props.onOpenConnections}
342 />
343 </ThreadRouteMessage>
344 );
346​
347function ThreadConnectionWaitScreen(props: {
348 readonly environment: string;
349 readonly connecting: boolean;
350 readonly onRetry: () => void;
351 readonly onOpenConnections: () => void;
352}) {
353 const gt = useGT();
354 return (
355 <ThreadRouteMessage
356 title={
357 props.connecting
358 ? gt("Connecting to {environment}", { environment: props.environment })
359 : gt("Can't reach {environment}", { environment: props.environment })
360 }
361 detail={gt("The thread opens once it connects.")}
362 subtitle={props.environment}
363 >
364 <ThreadRouteButton
365 tone="primary"
366 label={props.connecting ? gt("Retrying…") : gt("Retry")}
367 busy={props.connecting}
368 onPress={props.onRetry}
369 />
370 <ThreadRouteButton
371 tone="secondary"
372 label={gt("Connections")}
373 onPress={props.onOpenConnections}
374 />
375 </ThreadRouteMessage>
376 );
378​
379/** A thread that can't load opens a new task in its environment instead of a dead end. */
380function UnavailableThreadDraftRedirect(props: { readonly environmentId: EnvironmentId }) {
381 const navigation = useNavigation();
382 const isFocused = useIsFocused();
383 const projects = useProjects();
384 const openDraft = useEffectEvent(() => {
385 // A retained copy of this route in another tab can see focus in the same commit.
386 if (!navigation.isFocused()) return;
387 const project = projects.find((candidate) => candidate.environmentId === props.environmentId);
388 navigation.dispatch(
389 StackActions.replace("Thread", {
390 draft: project
391 ? {
392 requestId: uuidv4(),
393 environmentId: String(project.environmentId),
394 projectId: String(project.id),
395 }
396 : { requestId: uuidv4() },
397 }),
398 );
399 });
400 // A route under another screen waits until it is shown again: replace acts on the focused route.
401 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- replaces this route with a new draft thread route once it is focused
402 useEffect(() => {
403 if (isFocused) openDraft();
404 }, [isFocused]);
405 return <OpeningThreadLoadingScreen />;
407​
408export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
409 return (
410 <ThreadScreenHost>
411 {props.route.params?.draft ? (
412 <NewTaskDraftRouteScreen
413 key={draftRouteIdentity(props.route.params.draft)}
414 route={{ ...props.route, params: props.route.params.draft }}
415 />
416 ) : (
417 <LiveThreadRouteController {...props} />
418 )}
419 </ThreadScreenHost>
420 );
422​
423function LiveThreadRouteController(props: ThreadRouteScreenProps) {
424 const gt = useGT();
425 useAndroidWorkspaceBack();
426 const connectionsReady = useConnectionsReady();
427 const { connectedEnvironments, connectionState } = useRemoteConnectionStatus();
428 const { selectedThread } = useThreadSelection();
429 const params = props.route.params ?? {};
430 const environmentIdRaw = firstRouteParam(params.environmentId);
431 const threadIdRaw = firstRouteParam(params.threadId);
432 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
433 const routeEnvironment = connectedEnvironments.find(
434 (environment) => environment.environmentId === environmentId,
435 );
436 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
437 const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
438 const { onReconnectEnvironment } = useRemoteConnections();
439 const navigation = useNavigation();
440 const routeName = useRoute().name;
441 const routeConnectionState =
442 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
443 const routeThreadKey =
444 environmentId !== null && threadIdRaw !== null
445 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
446 : null;
447 const selectedThreadKey =
448 selectedThread === null
449 ? null
450 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
451 const selectedThreadDetailState = useSelectedThreadDetailState();
452 const detailError = selectedThreadDetailState.error;
453 const [errorBeforeConnected, setErrorBeforeConnected] = useState(() =>
454 routeConnectionState === "connected" ? Option.none<string>() : detailError,
455 );
456 if (routeConnectionState !== "connected" && errorBeforeConnected !== detailError) {
457 setErrorBeforeConnected(detailError);
458 }
459 const routeThreadShown = selectedThread !== null && selectedThreadKey === routeThreadKey;
460 const [shownThreadKey, setShownThreadKey] = useState<string | null>(null);
461 // The screen is reused across threads, so a thread shown on an earlier visit doesn't count.
462 const nextShownThreadKey =
463 routeThreadShown || shownThreadKey === routeThreadKey ? routeThreadKey : null;
464 if (nextShownThreadKey !== shownThreadKey) {
465 setShownThreadKey(nextShownThreadKey);
466 }
467 const [unreachableThreadKey, setUnreachableThreadKey] = useState<string | null>(null);
468 const attemptWait = routeThreadShown
469 ? null
470 : threadRouteConnectionWait({
471 environmentActive: routeEnvironmentRuntime !== null && routeEnvironment?.isEnabled === true,
472 connectionState: routeConnectionState,
473 detailStatus: selectedThreadDetailState.status,
474 });
475 // A failed attempt holds for a moment before it replaces the loading screen, so a cached thread's
476 // local read or a quick reconnect never flashes the waiting screen.
477 const attemptFailed =
478 useDelayedStatus(
479 `unreachable:${routeThreadKey ?? ""}`,
480 attemptWait === "unreachable" ? "unreachable" : null,
481 UNREACHABLE_WAIT_SETTLE_MS,
482 ) !== null;
483 const waitedBefore = unreachableThreadKey === routeThreadKey;
484 const connectionWait =
485 attemptWait === "unreachable" && !attemptFailed && !waitedBefore ? "connecting" : attemptWait;
486 if (
487 unreachableThreadKey !== null &&
488 (unreachableThreadKey !== routeThreadKey || routeThreadShown)
489 ) {
490 setUnreachableThreadKey(null);
491 } else if (connectionWait === "unreachable" && unreachableThreadKey !== routeThreadKey) {
492 setUnreachableThreadKey(routeThreadKey);
493 }
494 const withInspectorHeader = (content: ReactNode) =>
495 props.inspectorPresentation ? (
496 <InspectorHeaderShownContext value>
497 <ThreadInspectorHeader
498 title={selectedThread?.title ?? gt("Thread")}
499 {...props.inspectorPresentation}
500 />
501 {content}
502 </InspectorHeaderShownContext>
503 ) : (
504 content
505 );
506​
507 if (environmentId === null || threadIdRaw === null) {
508 return withInspectorHeader(<OpeningThreadLoadingScreen />);
509 }
510​
511 if (routeThreadShown) {
512 // ThreadRouteContent draws its own inspector header so it can show the sync status.
513 return (
514 <InspectorHeaderShownContext value={props.inspectorPresentation !== undefined}>
515 <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />
516 </InspectorHeaderShownContext>
517 );
518 }
519​
520 const stillHydrating = threadRouteIsHydrating({
521 isLoadingConnections: !connectionsReady,
522 environmentRegistered: routeEnvironmentRuntime !== null,
523 localCacheRead: routeEnvironmentShellState.cacheRead,
524 connectionState: routeConnectionState,
525 shellStatus: routeEnvironmentShellState.status,
526 shellHasError: routeEnvironmentShellState.hasError,
527 detailStatus: selectedThreadDetailState.status,
528 detailHasError: threadDetailErrorIsCurrent({
529 connectionState: routeConnectionState,
530 error: detailError,
531 errorBeforeConnected,
532 }),
533 });
534​
535 // Once an attempt has failed, later attempts show on the wait screen instead of the loading screen.
536 if (connectionWait === "unreachable" || (connectionWait === "connecting" && waitedBefore)) {
537 return withInspectorHeader(
538 <ThreadConnectionWaitScreen
539 environment={routeEnvironment?.environmentLabel ?? environmentId}
540 connecting={connectionWait === "connecting"}
541 onRetry={() => onReconnectEnvironment(environmentId)}
542 onOpenConnections={() => {
543 void navigation.navigate("Connections");
544 }}
545 />,
546 );
547 }
548​
549 if (stillHydrating || connectionWait === "connecting") {
550 return withInspectorHeader(<OpeningThreadLoadingScreen />);
551 }
552​
553 if (
554 routeName === "Thread" &&
555 !props.inspectorPresentation &&
556 threadRouteOpensDraft({
557 detailStatus: selectedThreadDetailState.status,
558 threadWasShown: shownThreadKey === routeThreadKey,
559 })
560 ) {
561 return <UnavailableThreadDraftRedirect environmentId={environmentId} />;
562 }
563​
564 return withInspectorHeader(
565 <ThreadUnavailableScreen
566 reason={threadUnavailableReason({
567 environmentRegistered: routeEnvironmentRuntime !== null,
568 environmentEnabled: routeEnvironment?.isEnabled !== false,
569 connectionState: routeConnectionState,
570 })}
571 environment={routeEnvironment?.environmentLabel ?? environmentId}
572 onReconnect={() => onReconnectEnvironment(environmentId)}
573 onOpenConnections={() => {
574 void navigation.navigate("Connections");
575 }}
576 onAddEnvironment={() => {
577 void navigation.navigate("ConnectionsNew", { linked: environmentId });
578 }}
579 />,
580 );
582​
583function ThreadRouteContent(
584 props: ThreadRouteScreenProps & {
585 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
586 },
587) {
588 const gt = useGT();
589 const m = useMessages();
590 const { layout, showInspector, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
591 const { connectionState } = useRemoteConnectionStatus();
592 const { onReconnectEnvironment } = useRemoteConnections();
593 const {
594 selectedThread,
595 selectedThreadCreation,
596 selectedThreadDetailRef,
597 selectedThreadProject,
598 selectedEnvironmentConnection,
599 } = useThreadSelection();
600 useRememberThreadProject(selectedThreadProject);
601 const canOperateThread = useEnvironmentScope(
602 selectedThread?.environmentId ?? null,
603 AuthOrchestrationOperateScope,
604 );
605 const canReadTerminal = useEnvironmentScope(
606 selectedThread?.environmentId ?? null,
607 AuthTerminalReadScope,
608 );
609 const canOperateTerminal = useEnvironmentScope(
610 selectedThread?.environmentId ?? null,
611 AuthTerminalOperateScope,
612 );
613 const selectedThreadDetailState = props.selectedThreadDetailState;
614 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
615 const { selectedThreadCwd } = useSelectedThreadWorktree();
616 const startSideChat = useStartSideChat();
617 const composer = useThreadComposerState({ startSideChat });
618 const gitState = useSelectedThreadGitState();
619 const gitActions = useSelectedThreadGitActions();
620 const requests = useSelectedThreadRequests();
621 useThreadStatusAnnouncements({
622 threadKey:
623 selectedThread === null || isProviderNativeSubagentThread(selectedThread.source)
624 ? null
625 : scopedThreadKey(selectedThread.environmentId, selectedThread.id),
626 // A preview beside its host names its thread, so the two threads' statuses can't be confused.
627 subject:
628 props.inspectorPresentation !== undefined && "onMaximize" in props.inspectorPresentation
629 ? (selectedThread?.title ?? null)
630 : null,
631 approvalRequestId: requests.activePendingApproval?.requestId ?? null,
632 userInputRequestId: requests.activePendingUserInput?.requestId ?? null,
633 shellRequestId: selectedThread?.source.pendingRuntimeRequest?.id ?? null,
634 shellPendingUserInput: selectedThread?.hasPendingUserInput === true,
635 working: composer.activeWorkStartedAt !== null || composer.isCompacting,
636 run: composer.selectedThreadAnnouncedRun,
637 detailBehind: composer.selectedThreadDetailBehindShell,
638 });
639 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
640 const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, {
641 label: "resume queue",
642 reportFailure: false,
643 });
644 const continueThreadRun = useAtomCommand(threadEnvironment.startTurn, {
645 label: "continue thread",
646 reportFailure: false,
647 });
648 const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
649 label: "set thread runtime mode",
650 reportFailure: false,
651 });
652 const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
653 label: "set thread interaction mode",
654 reportFailure: false,
655 });
656 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
657 label: "load earlier thread history",
658 reportFailure: false,
659 });
660 const historyControls = (() => {
661 const history = selectedThreadDetailState.history;
662 if (!selectedThread) {
663 return undefined;
664 }
665 if (!history.hasMoreHistory && history.error === null) {
666 return undefined;
667 }
668 return {
669 hasMoreHistory: history.hasMoreHistory,
670 loading: history.loading,
671 error: history.error === null ? null : threadErrorText(history.error, m),
672 onLoadEarlier: () => {
673 void loadEarlierHistory({
674 environmentId: selectedThread.environmentId,
675 input: { threadId: selectedThread.id },
676 });
677 },
678 onLoadThrough: (throughEntryId: string) => {
679 void loadEarlierHistory({
680 environmentId: selectedThread.environmentId,
681 input: { threadId: selectedThread.id, throughEntryId },
682 });
683 },
684 };
685 })();
686 const navigation = useNavigation();
687 const selectDetail = useSelectWorkspaceDetail();
688 const openPullRequest = useOpenPullRequest();
689 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
690 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
691 const mergeBackRun =
692 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
693 const mergeBackBusyRef = useRef(false);
694 const handleMergeBack = async () => {
695 if (
696 mergeBackBusyRef.current ||
697 !selectedThread ||
698 mergeBackTargetThreadId === null ||
699 mergeBackRun === null
700 ) {
701 return;
702 }
703 mergeBackBusyRef.current = true;
704 const result = await mergeBack({
705 environmentId: selectedThread.environmentId,
706 input: {
707 sourceThreadId: selectedThread.id,
708 targetThreadId: mergeBackTargetThreadId,
709 runId: mergeBackRun.id,
710 creationSource: "mobile",
711 },
712 });
713 mergeBackBusyRef.current = false;
714 if (result._tag !== "Success") return;
715 selectDetail({
716 name: "Thread",
717 params: { environmentId: selectedThread.environmentId, threadId: mergeBackTargetThreadId },
718 });
719 };
720 const params = props.route.params ?? {};
721 const environmentIdRaw = firstRouteParam(params.environmentId);
722 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
723 const threadId = firstRouteParam(params.threadId);
724 const routeThreadIdentity =
725 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
726 // The chosen mode survives thread switches; "route" only applies while the route
727 // supplies an inspector, which is also the default whenever it does.
728 const [chosenInspectorMode, setChosenInspectorMode] = useState<ThreadInspectorMode | null>(null);
729 const previewTarget = props.inspectorPresentation ? undefined : params.inspector;
730 const inspectorMode = (() => {
731 if (previewTarget) return "preview";
732 const mode =
733 props.renderInspector === undefined
734 ? chosenInspectorMode === "route"
735 ? null
736 : chosenInspectorMode
737 : chosenInspectorMode === null || chosenInspectorMode === "route"
738 ? "route"
739 : chosenInspectorMode;
740 return mode === "files" && selectedThreadCwd === null ? null : mode;
741 })();
742 const revealPreview = useEffectEvent(() => showInspector());
743 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the workspace navigator's inspector pane when route params bring a preview target
744 useEffect(() => {
745 if (previewTarget) revealPreview();
746 }, [previewTarget]);
747 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
748 const routeConnectionState =
749 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
750 const routeConnectionError = routeEnvironmentRuntime
751 ? runtimeConnectionErrorText(routeEnvironmentRuntime, m)
752 : null;
753 const selectedThreadWithDraftSettings = selectedThread
754 ? {
755 ...selectedThread,
756 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
757 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
758 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
759 }
760 : null;
761​
762 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
763 const delegatedFrom = selectedThread?.delegatedFrom ?? null;
764 const delegatedFromRef =
765 delegatedFrom === null
766 ? null
767 : scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
768 // The title it had at delegation, until this client sees the parent itself.
769 const delegatedFromThread = useThreadShell(delegatedFromRef);
770 const headerSubtitle = [
771 selectedThreadProject?.title ?? null,
772 selectedEnvironmentConnection?.environmentLabel ?? null,
773 // A linked environment's delegated task names its parent; other linked work its origin.
774 delegatedFrom !== null
775 ? gt("Subagent of {title}", { title: delegatedFromThread?.title ?? delegatedFrom.title })
776 : selectedThread?.linkOrigin
777 ? gt("From {origin}", { origin: selectedThread.linkOrigin.label })
778 : null,
779 ]
780 .filter(Boolean)
781 .join(" · ");
782 const gitStatus = useEnvironmentQuery(
783 selectedThread !== null && selectedThreadCwd !== null
784 ? vcsEnvironment.status({
785 environmentId: selectedThread.environmentId,
786 input: { cwd: selectedThreadCwd },
787 })
788 : null,
789 );
790 const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
791 environmentId: selectedThread?.environmentId ?? null,
792 threadId: selectedThread?.id ?? null,
793 });
794 const terminalMenuSessions = buildTerminalMenuSessions(
795 {
796 knownSessions: knownTerminalSessions ?? [],
797 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
798 },
799 m,
800 );
801 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
802 const handleReconnectEnvironment = () => {
803 if (!environmentId) {
804 return;
805 }
806 onReconnectEnvironment(environmentId);
807 };
808​
809 const gitActionProgressTarget = {
810 environmentId: selectedThread?.environmentId ?? null,
811 cwd: selectedThreadCwd,
812 };
813 const gitActionThreadRef =
814 selectedThread === null
815 ? null
816 : { environmentId: selectedThread.environmentId, threadId: selectedThread.id };
817 const gitActionProgress = useGitActionProgress(gitActionProgressTarget, gitActionThreadRef);
818​
819 const handleOpenGitInspector = () => {
820 navigation.setParams({ inspector: undefined });
821 setChosenInspectorMode("git");
822 showInspector();
823 };
824 const handleOpenFilesInspector = () => {
825 if (selectedThread === null || selectedThreadCwd === null) {
826 return;
827 }
828 navigation.setParams({ inspector: undefined });
829 setChosenInspectorMode(props.renderInspector === undefined ? "files" : "route");
830 showInspector();
831 };
832 const handleSelectInspectorFile = (path: string) => {
833 if (selectedThread === null) {
834 return;
835 }
836 const params = {
837 environmentId: String(selectedThread.environmentId),
838 threadId: String(selectedThread.id),
839 path: path.split("/").filter((segment) => segment.length > 0),
840 };
841 navigation.navigate("ThreadFile", params);
842 };
843 const renderGitInspector = () => (
844 <GitOverviewSheet
845 presentation="inspector"
846 route={{ params: { environmentId: environmentId!, threadId: threadId! } }}
847 />
848 );
849 const renderFilesInspector = () =>
850 selectedThread !== null && selectedThreadCwd !== null ? (
851 <InspectorSheetContext.Consumer>
852 {(closeInspectorSheet) => (
853 <ThreadFileNavigatorPane
854 cwd={selectedThreadCwd}
855 environmentId={selectedThread.environmentId}
856 projectName={selectedThreadProject?.title ?? gt("Files")}
857 selectedPath={null}
858 onSelectFile={(path) =>
859 closeInspectorSheet
860 ? closeInspectorSheet(() => handleSelectInspectorFile(path))
861 : handleSelectInspectorFile(path)
862 }
863 />
864 )}
865 </InspectorSheetContext.Consumer>
866 ) : null;
867 const renderPreviewInspector = () =>
868 previewTarget ? (
869 <ThreadInspectorPreviewWhileVisible
870 target={previewTarget}
871 renderThread={(screen) => <ThreadRouteScreen {...screen} />}
872 onClose={toggleAuxiliaryPane}
873 onOpen={(inspector) => {
874 if (
875 inspector.type === "thread" &&
876 inspector.environmentId === environmentId &&
877 inspector.threadId === threadId
878 ) {
879 toggleAuxiliaryPane();
880 return;
881 }
882 navigation.setParams({ inspector });
883 }}
884 />
885 ) : null;
886 const inspectorContent: InspectorContent | null =
887 inspectorMode === null
888 ? null
889 : {
890 active: inspectorMode,
891 resetKeys: [routeThreadIdentity, selectedThreadCwd],
892 panes: [
893 ...(inspectorMode === "preview"
894 ? [
895 {
896 key: "preview",
897 render: renderPreviewInspector,
898 },
899 ]
900 : []),
901 { key: "files", render: renderFilesInspector, prewarm: true },
902 { key: "git", render: renderGitInspector, prewarm: true },
903 ...(props.renderInspector ? [{ key: "route", render: props.renderInspector }] : []),
904 ],
905 };
906​
907 const handleOpenConnectionEditor = () => {
908 void navigation.navigate("Connections");
909 };
910 const handleStopThread = () => {
911 if (
912 !selectedThread ||
913 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
914 composer.interruptibleRunId === null
915 ) {
916 return;
917 }
918 return interruptThreadTurn({
919 environmentId: selectedThread.environmentId,
920 input: {
921 threadId: selectedThread.id,
922 runId: composer.interruptibleRunId,
923 },
924 });
925 };
926​
927 const handleResumeQueue = async () => {
928 if (!selectedThread) return;
929 const result = await resumeThread({
930 thread: selectedThread,
931 resumableRunId: composer.resumableRunId,
932 queueHeld: composer.queueHeld,
933 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
934 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
935 modelSelection: composer.modelSelection,
936 messageId: MessageId.make(uuidv4()),
937 createdAt: new Date().toISOString(),
938 setRuntimeMode: setThreadRuntimeMode,
939 setInteractionMode: setThreadInteractionMode,
940 startTurn: continueThreadRun,
941 resumeQueue: resumeThreadQueue,
942 });
943 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
944 const error = squashAtomCommandFailure(result);
945 Dialog.alert(
946 gt("Could not resume thread"),
947 errorDisplayMessage(error, m) ?? gt("Try again."),
948 );
949 }
950 };
951​
952 const handleOpenTerminal = (nextTerminalId?: string | null) => {
953 if (
954 !selectedThread ||
955 !selectedThreadProject?.workspaceRoot ||
956 (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
957 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
958 ) {
959 return;
960 }
961​
962 void navigation.navigate("ThreadTerminal", {
963 environmentId: String(selectedThread.environmentId),
964 threadId: String(selectedThread.id),
965 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
966 });
967 };
968​
969 const handleOpenNewTerminal = () => {
970 if (
971 !selectedThread ||
972 !selectedThreadProject?.workspaceRoot ||
973 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
974 ) {
975 return;
976 }
977​
978 const nextId = nextOpenTerminalId({
979 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
980 ...(knownTerminalSessions === null ||
981 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
982 ? { uniqueSuffix: uuidv4() }
983 : {}),
984 });
985 void navigation.navigate("ThreadTerminal", {
986 environmentId: String(selectedThread.environmentId),
987 threadId: String(selectedThread.id),
988 terminalId: nextId,
989 });
990 };
991​
992 const handleRunProjectScript = async (script: ProjectScript) => {
993 if (
994 !selectedThread ||
995 !selectedThreadProject?.workspaceRoot ||
996 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
997 ) {
998 return;
999 }
1000​
1001 const targetTerminalId = resolveProjectScriptTerminalId({
1002 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
1003 ...(knownTerminalSessions === null ||
1004 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
1005 ? { uniqueSuffix: uuidv4() }
1006 : {}),
1007 hasRunningTerminal: terminalMenuSessions.some(
1008 (session) => session.status === "running" || session.status === "starting",
1009 ),
1010 });
1011 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
1012 threadShellWorktreePath: selectedThread.worktreePath ?? null,
1013 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
1014 });
1015 const cwd = projectScriptCwd({
1016 project: { cwd: selectedThreadProject.workspaceRoot },
1017 worktreePath: preferredWorktreePath,
1018 });
1019 const env = projectScriptRuntimeEnv({
1020 project: { cwd: selectedThreadProject.workspaceRoot },
1021 worktreePath: preferredWorktreePath,
1022 });
1023 stagePendingTerminalLaunch({
1024 target: {
1025 environmentId: selectedThread.environmentId,
1026 threadId: selectedThread.id,
1027 terminalId: targetTerminalId,
1028 },
1029 launch: {
1030 cwd,
1031 worktreePath: preferredWorktreePath,
1032 env,
1033 initialInput: projectScriptTerminalInput(script.command),
1034 stopOnSettle: script.stopOnSettle ?? false,
1035 },
1036 });
1037​
1038 void navigation.navigate("ThreadTerminal", {
1039 environmentId: String(selectedThread.environmentId),
1040 threadId: String(selectedThread.id),
1041 terminalId: targetTerminalId,
1042 });
1043 };
1044 const threadGitControlProps = {
1045 environmentId: environmentIdRaw ?? "",
1046 threadId: threadId ?? "",
1047 onOpenFilesInspector: selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
1048 onOpenGitInspector: handleOpenGitInspector,
1049 onMergeBack:
1050 mergeBackTargetThreadId !== null && mergeBackRun !== null
1051 ? () => void handleMergeBack()
1052 : undefined,
1053 currentBranch: selectedThread?.branch ?? null,
1054 tracksRepositories: (selectedThreadProject?.trackedFolders?.length ?? 0) > 0,
1055 gitStatus: gitStatus.data,
1056 gitOperationLabel: gitState.gitOperationLabel,
1057 canOpenTerminal:
1058 Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
1059 canOperateTerminal,
1060 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
1061 projectScripts: selectedThreadProject
1062 ? resolveProjectScripts(
1063 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
1064 selectedThreadProject,
1066 : [],
1067 terminalSessions: terminalMenuSessions,
1068 onOpenTerminal: handleOpenTerminal,
1069 onOpenNewTerminal: handleOpenNewTerminal,
1070 onRunProjectScript: handleRunProjectScript,
1071 onPull: gitActions.onPullSelectedThreadBranch,
1072 onRunAction: gitActions.onRunSelectedThreadGitAction,
1073 };
1074 const handleEditFailedCreation = async () => {
1075 const creation = selectedThreadCreation?.message;
1076 if (!creation?.creation || routeThreadIdentity === null) {
1077 return;
1079 // Open recovery by draft id or the sheet creates an empty draft and strands restored content.
1080 try {
1081 await recoverFailedThreadDraft(creation);
1082 } catch (error) {
1083 Dialog.alert(gt("Could not restore draft"), errorDisplayMessage(error, m) ?? String(error));
1084 return;
1086 clearPendingThreadCreationOutcome(routeThreadIdentity);
1087 navigation.dispatch(
1088 StackActions.replace("Thread", {
1089 draft: {
1090 draftId: restoredNewTaskDraftKey(creation.messageId),
1091 environmentId: String(creation.environmentId),
1092 projectId: String(creation.creation.projectId),
1093 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
1094 },
1095 }),
1096 );
1097 };
1098 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
1099 const { visible: worktreeSetup } = useWorktreeSetup({
1100 environmentId: selectedThread?.environmentId ?? null,
1101 threadId: selectedThread?.id ?? null,
1102 preparing:
1103 composer.selectedThreadActivityRun?.status === "preparing" ||
1104 selectedThread?.runtime?.status === "preparing" ||
1105 (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
1106 selectedThreadCreation.outcome == null),
1107 hasWorktree: selectedThread?.worktreePath != null,
1108 runs: selectedThreadDetail?.runs ?? [],
1109 followUpSent:
1110 composer.selectedThreadFeed.filter(
1111 (entry) => entry.type === "message" && entry.message.role === "user",
1112 ).length +
1113 composer.selectedThreadQueueCount >
1114 1,
1115 });
1116 const awaitingBootstrapTurn =
1117 worktreeSetup !== null
1118 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
1119 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
1120 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
1121 const handleCancelWorktreeSetup = () => {
1122 if (!selectedThread) return;
1123 void cancelWorktreeSetup({
1124 environmentId: selectedThread.environmentId,
1125 input: { threadId: selectedThread.id },
1126 });
1127 };
1128 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
1129 const localResendBusy = useRef(false);
1130 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
1131 const handleWorkLocally = async () => {
1132 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
1133 return;
1134 localResendBusy.current = true;
1135 const result = await cancelWorktreeSetup({
1136 environmentId: selectedThread.environmentId,
1137 input: { threadId: selectedThread.id },
1138 });
1139 if (result._tag !== "Success" || !result.value.cancelled) {
1140 localResendBusy.current = false;
1141 return;
1143 // V2 accepts launch before setup; cancellation cannot reject that delivery, so reuse server-owned prompt and uploads.
1144 const metadata = makeTurnCommandMetadata();
1145 const launched = await startLocalThread({
1146 environmentId: selectedThread.environmentId,
1147 input: buildProjectThreadStartTurnInput({
1148 ...metadata,
1149 projectId: selectedThread.projectId,
1150 projectCwd: selectedThreadProject.workspaceRoot,
1151 text: setupMessage.text,
1152 titleText: selectedThread.title,
1153 ...(setupMessage.context ? { context: setupMessage.context } : {}),
1154 uploadedAttachments: setupMessage.attachments,
1155 modelSelection: selectedThread.modelSelection,
1156 runtimeMode: selectedThread.runtimeMode,
1157 interactionMode: selectedThread.interactionMode,
1158 workspaceMode: "local",
1159 branch: null,
1160 worktreePath: null,
1161 startFromOrigin: false,
1162 worktreeBranchName: "",
1163 }),
1164 });
1165 localResendBusy.current = false;
1166 if (launched._tag !== "Success") return;
1167 navigation.dispatch(
1168 StackActions.replace("Thread", {
1169 environmentId: String(selectedThread.environmentId),
1170 threadId: metadata.threadId,
1171 }),
1172 );
1173 };
1174 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
1175 if (selectedThreadCreation === null) {
1176 return awaitingBootstrapTurn
1177 ? { kind: "preparing", preparingWorktree: true, serverOwned: true }
1178 : null;
1180 if (selectedThreadCreation.outcome?.kind === "failed") {
1181 return {
1182 kind: "failed",
1183 reason: selectedThreadCreation.outcome.reason,
1184 onEditTask: handleEditFailedCreation,
1185 };
1187 return {
1188 kind: "preparing",
1189 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
1190 serverOwned: false,
1191 };
1192 })();
1193 // Queued creation displays its prompt before server creation; temporary not-found is expected.
1194 const contentPresentation =
1195 creationState !== null
1196 ? THREAD_CONTENT_READY
1197 : projectThreadContentPresentation({
1198 hasDetail: selectedThreadDetail !== null,
1199 detailError: Option.getOrNull(selectedThreadDetailState.error),
1200 detailDeleted: selectedThreadDetailState.status === "deleted",
1201 connectionState: routeConnectionState,
1202 resolve: m,
1203 });
1204 const connectionRetrying =
1205 routeConnectionState === "connecting" || routeConnectionState === "reconnecting";
1206 // Connection failures survive retries and app suspension.
1207 const retryConnectionError = useDelayedStatus(
1208 `${environmentId}:${connectionRetrying && routeConnectionError !== null}`,
1209 connectionRetrying ? routeConnectionError : null,
1210 RECONNECT_ERROR_DELAY_MS,
1211 );
1212 const connectionStatusLabel = connectionRetryLabel(
1214 connectionError: retryConnectionError,
1215 connectionState: routeConnectionState,
1216 connectionAwaitingApproval: routeEnvironmentRuntime?.connectionAwaitingApproval === true,
1217 },
1218 m,
1219 );
1220 // A thread this client is creating has nothing older to sync.
1221 const threadSyncLabel =
1222 creationState === null
1223 ? threadSyncStatusLabel(
1224 selectedThreadDetailState.status,
1225 contentPresentation.kind,
1226 Option.isSome(selectedThreadDetailState.error),
1227 m,
1229 : null;
1230 // Transient states go in the header subtitle so the composer's status slot doesn't jump.
1231 const threadStatusLabel = useDelayedStatus(
1232 selectedThread === null ? "" : scopedThreadKey(selectedThread.environmentId, selectedThread.id),
1233 connectionStatusLabel !== null ? connectionStatusLabel : threadSyncLabel,
1234 );
1235 const inspectorHeader = props.inspectorPresentation ? (
1236 <ThreadInspectorHeader
1237 title={selectedThread?.title ?? gt("Thread")}
1238 subtitle={threadStatusLabel ?? undefined}
1239 {...props.inspectorPresentation}
1240 />
1241 ) : null;
1242 if (!environmentId || !threadId || !selectedThread) {
1243 return (
1244 <>
1245 {inspectorHeader}
1246 <OpeningThreadLoadingScreen />
1247 </>
1248 );
1250​
1251 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
1252 return (
1253 <>
1254 {inspectorHeader}
1255 {!props.inspectorPresentation && inspectorContent ? (
1256 <Inspector
1257 // A route's own inspector (files) opens once per thread; going back keeps the user's choice.
1258 revealKey={
1259 props.renderInspector !== undefined && selectedThreadCwd !== null
1260 ? (routeThreadIdentity ?? undefined)
1261 : undefined
1263 content={inspectorContent}
1264 />
1265 ) : null}
1266 <GitActionProgressOverlay
1267 progress={gitActionProgress}
1268 onDismiss={() => dismissGitActionResult(gitActionThreadRef)}
1269 onOpenPullRequest={openPullRequest}
1270 />
1271 <ThreadScreenBinding
1272 header={
1273 props.inspectorPresentation ? null : (
1274 <ThreadHeader
1275 title={selectedThread.title}
1276 subtitle={threadStatusLabel ?? headerSubtitle}
1277 gitControls={threadGitControlProps}
1278 hasThreadCwd={selectedThreadCwd !== null}
1279 inspectorMode={inspectorMode}
1280 onOpenFilesInspector={handleOpenFilesInspector}
1281 onReturnToThread={props.onReturnToThread}
1282 />
1285 canOperateThread={canOperateThread}
1286 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
1287 selectedThreadDetailRef={selectedThreadDetailRef}
1288 contentPresentation={contentPresentation}
1289 screenTone={connectionTone(
1290 routeConnectionState,
1291 routeEnvironmentRuntime?.connectionAwaitingApproval === true,
1292 m,
1293 )}
1294 connectionError={routeConnectionError}
1295 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
1296 feedbackSubmissions={composer.feedbackSubmissions}
1297 onDismissFeedback={composer.dismissFeedback}
1298 selectedThreadFeed={composer.selectedThreadFeed}
1299 pendingHandoff={composer.pendingHandoff}
1300 activityRun={composer.selectedThreadActivityRun}
1301 activeWorkStartedAt={
1302 creationState?.kind === "preparing" ||
1303 (worktreeSetup !== null && setupTurnStartedAt === null)
1304 ? null
1305 : composer.activeWorkStartedAt
1307 isCompacting={composer.isCompacting}
1308 compactBeforeSend={composer.compactBeforeSend}
1309 runlessWorkActive={composer.runlessWorkActive}
1310 extensionStatuses={composer.extensionStatuses}
1311 providerSubagentStatus={composer.providerSubagentStatus}
1312 creationState={creationState}
1313 worktreeSetup={
1314 worktreeSetup
1315 ? {
1316 snapshot: worktreeSetup,
1317 turnStarted: setupTurnStartedAt !== null,
1318 onCancel: handleCancelWorktreeSetup,
1319 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
1321 : null
1323 activePendingApproval={requests.activePendingApproval}
1324 activePendingApprovals={requests.activePendingApprovals}
1325 respondingApprovalId={requests.respondingApprovalId}
1326 activePendingUserInput={requests.activePendingUserInput}
1327 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1328 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1329 respondingUserInputId={requests.respondingUserInputId}
1330 connectionStateLabel={routeConnectionState}
1331 historyControls={historyControls}
1332 activeThreadBusy={composer.activeThreadBusy}
1333 canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null}
1334 queuedRunEdit={composer.queuedRunEdit}
1335 composerDraftKey={composer.composerDraftKey}
1336 followUpBehavior={composer.followUpBehavior}
1337 canSteerActiveTurn={composer.canSteerActiveTurn}
1338 isSavingQueuedEdit={composer.isSavingQueuedEdit}
1339 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
1340 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
1341 environmentId={selectedThread.environmentId}
1342 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1343 threadCwd={selectedThreadCwd}
1344 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1345 queuedMessages={
1346 selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"
1347 ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]
1348 : composer.selectedThreadQueuedMessages
1350 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1351 layoutVariant={layout.variant}
1352 usesAutomaticContentInsets={usesNativeHeaderGlass}
1353 onOpenConnectionEditor={handleOpenConnectionEditor}
1354 onChangeDraftMessage={composer.onChangeDraftMessage}
1355 onPickDraftMedia={composer.onPickDraftMedia}
1356 onPickDraftFiles={composer.onPickDraftFiles}
1357 onNativePasteImages={composer.onNativePasteImages}
1358 onNativePasteText={composer.onNativePasteText}
1359 onRemoveDraftImage={composer.onRemoveDraftImage}
1360 serverConfig={serverConfig}
1361 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1362 onResumeQueue={composer.canResume ? handleResumeQueue : null}
1363 onSendMessage={composer.onSendMessage}
1364 offersSideChat={composer.sideChatUnavailableReason === null}
1365 onSendCommand={composer.onSendCommand}
1366 onReconnectEnvironment={handleReconnectEnvironment}
1367 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1368 onRespondToApproval={requests.onRespondToApproval}
1369 onSelectUserInputOption={requests.onSelectUserInputOption}
1370 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1371 onSubmitUserInput={requests.onSubmitUserInput}
1372 onDismissUserInput={requests.onDismissUserInput}
1373 />
1374 </>
1375 );
1377​
1378export function FullscreenThreadRouteScreen(
1379 props: StaticScreenProps<{
1380 readonly environmentId: string;
1381 readonly threadId: string;
1382 }>,
1383) {
1384 const navigation = useNavigation();
1385 return (
1386 <InspectorContentScope>
1387 <ThreadRouteScreen
1388 route={props.route}
1389 inspectorPresentation={{ onClose: () => navigation.goBack() }}
1390 />
1391 </InspectorContentScope>
1392 );
1394​
1395/** Reads the pane state itself, so a sidebar toggle doesn't re-render the whole thread screen. */
1396function ThreadInspectorPreviewWhileVisible(props: Parameters<typeof ThreadInspectorPreview>[0]) {
1397 const { panes } = useWorkspacePaneState();
1398 return panes.auxiliaryPaneVisible ? <ThreadInspectorPreview {...props} /> : null;