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

ThreadRouteScreen.tsx

1,466 lines56.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 type RunId,
37 ThreadId,
38 type ProjectScript,
39} from "@t3tools/contracts";
40import {
41 projectScriptCwd,
42 projectScriptRuntimeEnv,
43 projectScriptTerminalInput,
44 resolveProjectScripts,
45} from "@t3tools/shared/projectScripts";
46import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
47import { useConnectionsReady } from "../../state/workspace";
48import { useEnvironmentShellReadiness } from "../../state/shell";
49import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
50import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
51import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
52import { useEnvironmentQuery } from "../../state/query";
53import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
54import { vcsEnvironment } from "../../state/vcs";
55import { LoadingScreen } from "../../components/LoadingScreen";
56import { Platform, Pressable, View } from "react-native";
57import { HeaderHeightContext } from "@react-navigation/elements";
58import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
59import { AppText as Text } from "../../components/ui/AppText";
60import { cn } from "../../lib/cn";
61import { scopedThreadKey } from "../../lib/scopedEntities";
62import { useDelayedStatus } from "../../lib/useDelayedStatus";
63import { useStableCallback } from "../../lib/useStableCallback";
64import { connectionRetryLabel } from "./floating-working-status";
65import { scopeThreadRef } from "@t3tools/client-runtime/environment";
66import { useThreadShell } from "../../state/entities";
67import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
68import { connectionTone } from "../connection/connectionTone";
69import { runtimeConnectionErrorText } from "../connection/environmentStatusText";
70import {
71 useRemoteConnections,
72 useRemoteConnectionStatus,
73 useRemoteEnvironmentRuntime,
74} from "../../state/use-remote-environment-registry";
75import { useKnownTerminalSessions } from "../../state/use-terminal-session";
76import { uuidv4 } from "../../lib/uuid";
77import {
78 isAtomCommandInterrupted,
79 squashAtomCommandFailure,
80} from "@t3tools/client-runtime/state/runtime";
81import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
82import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
83import { useThreadSelection } from "../../state/use-thread-selection";
84import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
85import {
86 buildTerminalMenuSessions,
87 nextOpenTerminalId,
88 resolveProjectScriptTerminalId,
89} from "../terminal/terminalMenu";
90import {
91 resolvePreferredThreadWorktreePath,
92 stagePendingTerminalLaunch,
93} from "../terminal/terminalLaunchContext";
94import type { ThreadDetailScreenProps } from "./ThreadDetailScreen";
95import { ThreadScreenBinding, ThreadScreenFallback, ThreadScreenHost } from "./ThreadScreenHost";
96import { draftRouteIdentity } from "./thread-route-state";
97import { NewTaskDraftRouteScreen, type NewTaskDraftRouteParams } from "./NewTaskDraftRouteScreen";
98import { GitOverviewSheet } from "./git/GitOverviewSheet";
99import { useAtomCommand } from "../../state/use-atom-command";
100import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
101import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
102import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
103import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
104import { useMissingWorkspace } from "./useThreadWorkspace";
105import { useThreadComposerState } from "../../state/use-thread-composer-state";
106import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
107import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
108import { threadEnvironment } from "../../state/threads";
109import { threadErrorText } from "@t3tools/client-runtime/state/threads";
110import { workspacePreparationRetryRunIds } from "@t3tools/client-runtime/state/turn-item-presentation";
111import { useProjects } from "../../state/entities";
112import {
113 projectThreadContentPresentation,
114 THREAD_CONTENT_READY,
115 threadSyncStatusLabel,
116} from "./threadContentPresentation";
117import {
118 Inspector,
119 useAdaptiveWorkspaceLayout,
120 useWorkspacePaneState,
121} from "../layout/AdaptiveWorkspaceLayout";
122import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
123import { InspectorSheetContext } from "../layout/workspace-inspector-sheet";
124import type { InspectorContent } from "../layout/inspector-panes";
125import {
126 threadDetailErrorIsCurrent,
127 threadRouteConnectionWait,
128 threadRouteIsHydrating,
129 threadRouteOpensDraft,
130 threadUnavailableReason,
131 type ThreadUnavailableReason,
132} from "./thread-route-hydration";
133import { ThreadHeader } from "./ThreadHeader";
134import { resumeThread } from "./resume-thread";
135import {
136 useAndroidWorkspaceBack,
137 useWorkspaceBackNavigation,
138} from "../layout/workspace/useAndroidWorkspaceNavigation";
139import { ThreadInspectorHeader, type ThreadInspectorPresentation } from "./thread-inspector-header";
140import { InspectorContentScope, ThreadInspectorPreview } from "./thread-inspector-preview";
141import { useStartSideChat } from "./useStartSideChat";
142import { useThreadStatusAnnouncements } from "./useThreadStatusAnnouncements";
143import type { ThreadInspectorMode, ThreadInspectorTarget } from "./thread-inspector-navigation";
144import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
145​
146function firstRouteParam(value: string | string[] | undefined): string | null {
147 const first = Array.isArray(value) ? value[0] : value;
148 return first === undefined || first.trim().length === 0 ? null : first;
150​
151const RECONNECT_ERROR_DELAY_MS = 5_000;
152const UNREACHABLE_WAIT_SETTLE_MS = 1_000;
153​
154// The inspector pane's bar belongs to ThreadInspectorHeader; the fallback must not draw its own.
155const InspectorHeaderShownContext = createContext(false);
156​
157function ThreadRouteFallbackLayout(props: {
158 readonly children: ReactNode;
159 readonly subtitle?: string;
160}) {
161 const gt = useGT();
162 const goBack = useWorkspaceBackNavigation();
163 const inspectorHeaderShown = use(InspectorHeaderShownContext);
164 return (
165 <ThreadScreenFallback
166 header={
167 inspectorHeaderShown ? undefined : (
168 <AppBar
169 title={gt`Thread`}
170 {...(props.subtitle === undefined ? {} : { subtitle: props.subtitle })}
171 onBackToList={goBack}
172 hideBottomBorder
173 />
174 )
175 }
176 >
177 {props.children}
178 </ThreadScreenFallback>
179 );
181​
182function OpeningThreadLoadingScreen() {
183 const gt = useGT();
184 return (
185 <ThreadRouteFallbackLayout>
186 <LoadingScreen message={gt`Opening thread…`} messagePlacement="above-spinner" embedded />
187 </ThreadRouteFallbackLayout>
188 );
190​
191type ThreadRouteScreenRouteProps = StaticScreenProps<{
192 readonly environmentId?: string;
193 readonly threadId?: string;
194 readonly draft?: NewTaskDraftRouteParams;
195 readonly inspector?: ThreadInspectorTarget;
196 readonly prompt?: string | string[];
197}>;
198​
199interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
200 readonly inspectorPresentation?: ThreadInspectorPresentation;
201 readonly onReturnToThread?: () => void;
202 readonly renderInspector?: () => ReactNode;
204​
205/** A centered message column for the thread route, the same width on every screen. */
206function ThreadRouteMessage(props: {
207 readonly title: string;
208 readonly detail: string;
209 readonly subtitle?: string;
210 readonly children: ReactNode;
211}) {
212 // iOS draws the header over this view. Even padding keeps the block centered on the whole screen
213 // while text too large to fit still starts below the header and scrolls.
214 const headerInset = use(HeaderHeightContext) ?? 0;
215 const inset = Platform.OS === "ios" ? headerInset : 0;
216 return (
217 <ThreadRouteFallbackLayout
218 {...(props.subtitle === undefined ? {} : { subtitle: props.subtitle })}
219 >
220 <ScreenScrollView
221 className="flex-1"
222 contentInsetAdjustmentBehavior="never"
223 contentContainerClassName="flex-grow items-center justify-center px-8"
224 contentContainerStyle={{ paddingTop: inset, paddingBottom: inset }}
225 >
226 {/* One fixed width for every message, so the buttons are the same size on each screen. The
227 bottom margin lifts the block a little above center, where it reads as centered. */}
228 <View className="mb-24 w-[256px] max-w-full items-center">
229 <Text textRole="title" className="text-center font-t3-bold text-foreground">
230 {props.title}
231 </Text>
232 <Text
233 textRole="body"
234 className="mt-1.5 text-center font-sans leading-normal text-foreground-muted"
235 >
236 {props.detail}
237 </Text>
238 <View className="mt-6 flex-row justify-center gap-2 self-stretch">{props.children}</View>
239 </View>
240 </ScreenScrollView>
241 </ThreadRouteFallbackLayout>
242 );
244​
245/** One of the thread route's pill buttons; they split the message column's width evenly. */
246function ThreadRouteButton(props: {
247 readonly label: string;
248 readonly onPress: () => void;
249 readonly tone: "primary" | "secondary";
250 readonly busy?: boolean;
251}) {
252 const busy = props.busy === true;
253 return (
254 <Pressable
255 accessibilityRole="button"
256 accessibilityState={{ disabled: busy, busy }}
257 disabled={busy}
258 onPress={props.onPress}
259 className={cn(
260 "min-h-[44px] flex-1 flex-row items-center justify-center gap-2 rounded-full px-3 active:opacity-70 android:min-h-[48px]",
261 props.tone === "primary" ? "bg-primary" : "border border-foreground/15",
262 busy && "opacity-55",
263 )}
264 >
265 {busy ? <AppActivityIndicator size={14} colorClassName="accent-primary-foreground" /> : null}
266 {/* Large text sizes shrink the label rather than clip it, so both buttons keep their width. */}
267 <Text
268 textRole="footnote"
269 numberOfLines={1}
270 adjustsFontSizeToFit
271 minimumFontScale={0.7}
272 className={cn(
273 "shrink font-t3-bold",
274 props.tone === "primary" ? "text-primary-foreground" : "text-foreground",
275 )}
276 >
277 {props.label}
278 </Text>
279 </Pressable>
280 );
282​
283function ThreadUnavailableScreen(props: {
284 readonly reason: ThreadUnavailableReason;
285 readonly environment: string;
286 readonly onReconnect: () => void;
287 readonly onOpenConnections: () => void;
288 readonly onAddEnvironment: () => void;
289}) {
290 const gt = useGT();
291 const { environment } = props;
292 if (props.reason === "unknown-environment") {
293 return (
294 <ThreadRouteMessage
295 title={gt`Environment not added`}
296 detail={gt`Add it to open this thread.`}
297 >
298 <ThreadRouteButton
299 tone="primary"
300 label={gt`Add environment`}
301 onPress={props.onAddEnvironment}
302 />
303 </ThreadRouteMessage>
304 );
305 }
306 if (props.reason === "unsupported") {
307 // The supervisor pauses an incompatible environment, so Reconnect could not help here.
308 return (
309 <ThreadRouteMessage
310 title={gt`Client not supported`}
311 detail={gt`Use compatible versions of the app and server to connect.`}
312 subtitle={environment}
313 >
314 <ThreadRouteButton
315 tone="primary"
316 label={gt`Connections`}
317 onPress={props.onOpenConnections}
318 />
319 </ThreadRouteMessage>
320 );
321 }
322 const switchedOff = props.reason === "switched-off";
323 return (
324 <ThreadRouteMessage
325 title={switchedOff ? gt`${{ environment }} is switched off` : gt`Thread not found`}
326 detail={
327 switchedOff
328 ? gt`Turn it on to open this thread.`
329 : gt`It may be deleted or not on ${{ environment }}.`
330 }
331 subtitle={environment}
332 >
333 <ThreadRouteButton
334 tone="primary"
335 label={switchedOff ? gt({ context: "switch an environment on" })`Turn on` : gt`Reconnect`}
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: props.environment }}`
359 : gt`Can't reach ${{ 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, selectedThreadWorktreePath } = useSelectedThreadWorktree();
616 const startSideChat = useStartSideChat();
617 const missingWorkspace = useMissingWorkspace(selectedThread);
618 const composer = useThreadComposerState({
619 startSideChat,
620 workspaceMissing: missingWorkspace !== null,
621 });
622 const gitState = useSelectedThreadGitState();
623 const gitActions = useSelectedThreadGitActions();
624 const requests = useSelectedThreadRequests();
625 useThreadStatusAnnouncements({
626 threadKey:
627 selectedThread === null || isProviderNativeSubagentThread(selectedThread.source)
628 ? null
629 : scopedThreadKey(selectedThread.environmentId, selectedThread.id),
630 // A preview beside its host names its thread, so the two threads' statuses can't be confused.
631 subject:
632 props.inspectorPresentation !== undefined && "onMaximize" in props.inspectorPresentation
633 ? (selectedThread?.title ?? null)
634 : null,
635 approvalRequestId: requests.activePendingApproval?.requestId ?? null,
636 userInputRequestId: requests.activePendingUserInput?.requestId ?? null,
637 shellRequestId: selectedThread?.source.pendingRuntimeRequest?.id ?? null,
638 shellPendingUserInput: selectedThread?.hasPendingUserInput === true,
639 working: composer.activeWorkStartedAt !== null || composer.isCompacting,
640 run: composer.selectedThreadAnnouncedRun,
641 detailBehind: composer.selectedThreadDetailBehindShell,
642 });
643 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
644 const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, {
645 label: "resume queue",
646 reportFailure: false,
647 });
648 const continueThreadRun = useAtomCommand(threadEnvironment.startTurn, {
649 label: "continue thread",
650 reportFailure: false,
651 });
652 const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
653 label: "set thread runtime mode",
654 reportFailure: false,
655 });
656 const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
657 label: "set thread interaction mode",
658 reportFailure: false,
659 });
660 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
661 label: "load earlier thread history",
662 reportFailure: false,
663 });
664 const historyControls = (() => {
665 const history = selectedThreadDetailState.history;
666 if (!selectedThread) {
667 return undefined;
668 }
669 const gaps = history.gaps ?? [];
670 if (!history.hasMoreHistory && history.error === null && gaps.length === 0) {
671 return undefined;
672 }
673 return {
674 hasMoreHistory: history.hasMoreHistory,
675 loading: history.loading,
676 error: history.error === null ? null : threadErrorText(history.error, m),
677 gaps,
678 onLoadGap: (gapSeamItemId: string) =>
679 loadEarlierHistory({
680 environmentId: selectedThread.environmentId,
681 input: { threadId: selectedThread.id, gapSeamItemId },
682 }),
683 onLoadEarlier: () => {
684 void loadEarlierHistory({
685 environmentId: selectedThread.environmentId,
686 input: { threadId: selectedThread.id },
687 });
688 },
689 onLoadThrough: (throughEntryId: string) => {
690 void loadEarlierHistory({
691 environmentId: selectedThread.environmentId,
692 // The feed draws gaps, so a message far back loads as the page around it.
693 input: { threadId: selectedThread.id, throughEntryId, detach: true },
694 });
695 },
696 };
697 })();
698 const navigation = useNavigation();
699 const selectDetail = useSelectWorkspaceDetail();
700 const openPullRequest = useOpenPullRequest();
701 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
702 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
703 const mergeBackRun =
704 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
705 const mergeBackBusyRef = useRef(false);
706 const handleMergeBack = async () => {
707 if (
708 mergeBackBusyRef.current ||
709 !selectedThread ||
710 mergeBackTargetThreadId === null ||
711 mergeBackRun === null
712 ) {
713 return;
714 }
715 mergeBackBusyRef.current = true;
716 const result = await mergeBack({
717 environmentId: selectedThread.environmentId,
718 input: {
719 sourceThreadId: selectedThread.id,
720 targetThreadId: mergeBackTargetThreadId,
721 runId: mergeBackRun.id,
722 creationSource: "mobile",
723 },
724 });
725 mergeBackBusyRef.current = false;
726 if (result._tag !== "Success") return;
727 selectDetail({
728 name: "Thread",
729 params: { environmentId: selectedThread.environmentId, threadId: mergeBackTargetThreadId },
730 });
731 };
732 const params = props.route.params ?? {};
733 const environmentIdRaw = firstRouteParam(params.environmentId);
734 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
735 const threadId = firstRouteParam(params.threadId);
736 const routeThreadIdentity =
737 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
738 // The chosen mode survives thread switches; "route" only applies while the route
739 // supplies an inspector, which is also the default whenever it does.
740 const [chosenInspectorMode, setChosenInspectorMode] = useState<ThreadInspectorMode | null>(null);
741 const previewTarget = props.inspectorPresentation ? undefined : params.inspector;
742 const inspectorMode = (() => {
743 if (previewTarget) return "preview";
744 const mode =
745 props.renderInspector === undefined
746 ? chosenInspectorMode === "route"
747 ? null
748 : chosenInspectorMode
749 : chosenInspectorMode === null || chosenInspectorMode === "route"
750 ? "route"
751 : chosenInspectorMode;
752 return mode === "files" && selectedThreadCwd === null ? null : mode;
753 })();
754 const revealPreview = useEffectEvent(() => showInspector());
755 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the workspace navigator's inspector pane when route params bring a preview target
756 useEffect(() => {
757 if (previewTarget) revealPreview();
758 }, [previewTarget]);
759 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
760 const routeConnectionState =
761 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
762 const routeConnectionError = routeEnvironmentRuntime
763 ? runtimeConnectionErrorText(routeEnvironmentRuntime, m)
764 : null;
765 const selectedThreadWithDraftSettings = selectedThread
766 ? {
767 ...selectedThread,
768 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
769 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
770 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
771 }
772 : null;
773​
774 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
775 const delegatedFrom = selectedThread?.delegatedFrom ?? null;
776 const delegatedFromRef =
777 delegatedFrom === null
778 ? null
779 : scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
780 // The title it had at delegation, until this client sees the parent itself.
781 const delegatedFromThread = useThreadShell(delegatedFromRef);
782 const headerSubtitle = [
783 selectedThreadProject?.title ?? null,
784 selectedEnvironmentConnection?.environmentLabel ?? null,
785 // A linked environment's delegated task names its parent; other linked work its origin.
786 delegatedFrom !== null
787 ? gt`Subagent of ${{ title: delegatedFromThread?.title ?? delegatedFrom.title }}`
788 : selectedThread?.linkOrigin
789 ? gt`From ${{ origin: selectedThread.linkOrigin.label }}`
790 : null,
791 ]
792 .filter(Boolean)
793 .join(" · ");
794 const gitStatus = useEnvironmentQuery(
795 selectedThread !== null && selectedThreadCwd !== null
796 ? vcsEnvironment.status({
797 environmentId: selectedThread.environmentId,
798 input: { cwd: selectedThreadCwd },
799 })
800 : null,
801 );
802 const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
803 environmentId: selectedThread?.environmentId ?? null,
804 threadId: selectedThread?.id ?? null,
805 });
806 const terminalMenuSessions = buildTerminalMenuSessions(
807 {
808 knownSessions: knownTerminalSessions ?? [],
809 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
810 },
811 m,
812 );
813 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
814 const handleReconnectEnvironment = () => {
815 if (!environmentId) {
816 return;
817 }
818 onReconnectEnvironment(environmentId);
819 };
820​
821 const gitActionProgressTarget = {
822 environmentId: selectedThread?.environmentId ?? null,
823 cwd: selectedThreadCwd,
824 };
825 const gitActionThreadRef =
826 selectedThread === null
827 ? null
828 : { environmentId: selectedThread.environmentId, threadId: selectedThread.id };
829 const gitActionProgress = useGitActionProgress(gitActionProgressTarget, gitActionThreadRef);
830​
831 const handleOpenGitInspector = () => {
832 navigation.setParams({ inspector: undefined });
833 setChosenInspectorMode("git");
834 showInspector();
835 };
836 const handleOpenFilesInspector = () => {
837 if (selectedThread === null || selectedThreadCwd === null) {
838 return;
839 }
840 navigation.setParams({ inspector: undefined });
841 setChosenInspectorMode(props.renderInspector === undefined ? "files" : "route");
842 showInspector();
843 };
844 const handleSelectInspectorFile = (path: string) => {
845 if (selectedThread === null) {
846 return;
847 }
848 const params = {
849 environmentId: String(selectedThread.environmentId),
850 threadId: String(selectedThread.id),
851 path: path.split("/").filter((segment) => segment.length > 0),
852 };
853 navigation.navigate("ThreadFile", params);
854 };
855 const renderGitInspector = () => (
856 <GitOverviewSheet
857 presentation="inspector"
858 route={{ params: { environmentId: environmentId!, threadId: threadId! } }}
859 />
860 );
861 const renderFilesInspector = () =>
862 selectedThread !== null && selectedThreadCwd !== null ? (
863 <InspectorSheetContext.Consumer>
864 {(closeInspectorSheet) => (
865 <ThreadFileNavigatorPane
866 cwd={selectedThreadCwd}
867 environmentId={selectedThread.environmentId}
868 projectName={selectedThreadProject?.title ?? gt`Files`}
869 selectedPath={null}
870 onSelectFile={(path) =>
871 closeInspectorSheet
872 ? closeInspectorSheet(() => handleSelectInspectorFile(path))
873 : handleSelectInspectorFile(path)
874 }
875 />
876 )}
877 </InspectorSheetContext.Consumer>
878 ) : null;
879 const renderPreviewInspector = () =>
880 previewTarget ? (
881 <ThreadInspectorPreviewWhileVisible
882 target={previewTarget}
883 renderThread={(screen) => <ThreadRouteScreen {...screen} />}
884 onClose={toggleAuxiliaryPane}
885 onOpen={(inspector) => {
886 if (
887 inspector.type === "thread" &&
888 inspector.environmentId === environmentId &&
889 inspector.threadId === threadId
890 ) {
891 toggleAuxiliaryPane();
892 return;
893 }
894 navigation.setParams({ inspector });
895 }}
896 />
897 ) : null;
898 const inspectorContent: InspectorContent | null =
899 inspectorMode === null
900 ? null
901 : {
902 active: inspectorMode,
903 resetKeys: [routeThreadIdentity, selectedThreadCwd],
904 panes: [
905 ...(inspectorMode === "preview"
906 ? [
907 {
908 key: "preview",
909 render: renderPreviewInspector,
910 },
911 ]
912 : []),
913 { key: "files", render: renderFilesInspector, prewarm: true },
914 { key: "git", render: renderGitInspector, prewarm: true },
915 ...(props.renderInspector ? [{ key: "route", render: props.renderInspector }] : []),
916 ],
917 };
918​
919 const handleOpenConnectionEditor = () => {
920 void navigation.navigate("Connections");
921 };
922 const confirmedStopTargetsRef = useRef(new Set<string>());
923 const handleStopThread = useStableCallback((threadKey: string, confirmedRunId: RunId | null) => {
924 if (
925 !selectedThread ||
926 scopedThreadKey(selectedThread.environmentId, selectedThread.id) !== threadKey ||
927 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
928 composer.interruptibleRunId === null ||
929 (confirmedRunId !== null && confirmedRunId !== composer.interruptibleRunId)
930 ) {
931 return;
932 }
933 confirmedStopTargetsRef.current.add(
934 JSON.stringify([
935 selectedThread.environmentId,
936 selectedThread.id,
937 composer.interruptibleRunId,
938 ]),
939 );
940 return interruptThreadTurn({
941 environmentId: selectedThread.environmentId,
942 input: {
943 threadId: selectedThread.id,
944 runId: composer.interruptibleRunId,
945 },
946 });
947 });
948​
949 const handleResumeQueue = async () => {
950 if (!selectedThread || missingWorkspace) return;
951 const result = await resumeThread({
952 thread: selectedThread,
953 resumableRunId: composer.resumableRunId,
954 queueHeld: composer.queueHeld,
955 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
956 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
957 modelSelection: composer.modelSelection,
958 messageId: MessageId.make(uuidv4()),
959 createdAt: new Date().toISOString(),
960 setRuntimeMode: setThreadRuntimeMode,
961 setInteractionMode: setThreadInteractionMode,
962 startTurn: continueThreadRun,
963 resumeQueue: resumeThreadQueue,
964 });
965 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
966 const error = squashAtomCommandFailure(result);
967 Dialog.alert(gt`Could not resume thread`, errorDisplayMessage(error, m) ?? gt`Try again.`);
968 }
969 };
970​
971 const handleOpenTerminal = (nextTerminalId?: string | null) => {
972 if (
973 !selectedThread ||
974 !selectedThreadProject?.workspaceRoot ||
975 (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
976 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
977 ) {
978 return;
979 }
980​
981 void navigation.navigate("ThreadTerminal", {
982 environmentId: String(selectedThread.environmentId),
983 threadId: String(selectedThread.id),
984 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
985 });
986 };
987​
988 const handleOpenNewTerminal = () => {
989 if (
990 !selectedThread ||
991 !selectedThreadProject?.workspaceRoot ||
992 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
993 ) {
994 return;
995 }
996​
997 const nextId = nextOpenTerminalId({
998 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
999 ...(knownTerminalSessions === null ||
1000 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
1001 ? { uniqueSuffix: uuidv4() }
1002 : {}),
1003 });
1004 void navigation.navigate("ThreadTerminal", {
1005 environmentId: String(selectedThread.environmentId),
1006 threadId: String(selectedThread.id),
1007 terminalId: nextId,
1008 });
1009 };
1010​
1011 const handleRunProjectScript = async (script: ProjectScript) => {
1012 if (
1013 !selectedThread ||
1014 !selectedThreadProject?.workspaceRoot ||
1015 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
1016 ) {
1017 return;
1019​
1020 const targetTerminalId = resolveProjectScriptTerminalId({
1021 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
1022 ...(knownTerminalSessions === null ||
1023 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
1024 ? { uniqueSuffix: uuidv4() }
1025 : {}),
1026 hasRunningTerminal: terminalMenuSessions.some(
1027 (session) => session.status === "running" || session.status === "starting",
1028 ),
1029 });
1030 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
1031 threadShellWorktreePath: selectedThread.worktreePath ?? null,
1032 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
1033 });
1034 const cwd = projectScriptCwd({
1035 project: { cwd: selectedThreadProject.workspaceRoot },
1036 worktreePath: preferredWorktreePath,
1037 });
1038 const env = projectScriptRuntimeEnv({
1039 project: { cwd: selectedThreadProject.workspaceRoot },
1040 worktreePath: preferredWorktreePath,
1041 });
1042 stagePendingTerminalLaunch({
1043 target: {
1044 environmentId: selectedThread.environmentId,
1045 threadId: selectedThread.id,
1046 terminalId: targetTerminalId,
1047 },
1048 launch: {
1049 cwd,
1050 worktreePath: preferredWorktreePath,
1051 env,
1052 initialInput: projectScriptTerminalInput(script.command),
1053 stopOnSettle: script.stopOnSettle ?? false,
1054 },
1055 });
1056​
1057 void navigation.navigate("ThreadTerminal", {
1058 environmentId: String(selectedThread.environmentId),
1059 threadId: String(selectedThread.id),
1060 terminalId: targetTerminalId,
1061 });
1062 };
1063 const threadGitControlProps = {
1064 environmentId: environmentIdRaw ?? "",
1065 threadId: threadId ?? "",
1066 onOpenFilesInspector: selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
1067 onOpenGitInspector: handleOpenGitInspector,
1068 onMergeBack:
1069 mergeBackTargetThreadId !== null && mergeBackRun !== null
1070 ? () => void handleMergeBack()
1071 : undefined,
1072 currentBranch: selectedThread?.branch ?? null,
1073 tracksRepositories: (selectedThreadProject?.trackedFolders?.length ?? 0) > 0,
1074 gitStatus: gitStatus.data,
1075 gitOperationLabel: gitState.gitOperationLabel,
1076 canOpenTerminal:
1077 Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
1078 canOperateTerminal,
1079 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
1080 projectScripts: selectedThreadProject
1081 ? resolveProjectScripts(
1082 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
1083 selectedThreadProject,
1085 : [],
1086 terminalSessions: terminalMenuSessions,
1087 onOpenTerminal: handleOpenTerminal,
1088 onOpenNewTerminal: handleOpenNewTerminal,
1089 onRunProjectScript: handleRunProjectScript,
1090 onPull: gitActions.onPullSelectedThreadBranch,
1091 onRunAction: gitActions.onRunSelectedThreadGitAction,
1092 };
1093 const handleEditFailedCreation = async () => {
1094 const creation = selectedThreadCreation?.message;
1095 if (!creation?.creation || routeThreadIdentity === null) {
1096 return;
1098 // Open recovery by draft id or the sheet creates an empty draft and strands restored content.
1099 try {
1100 await recoverFailedThreadDraft(creation);
1101 } catch (error) {
1102 Dialog.alert(gt`Could not restore draft`, errorDisplayMessage(error, m) ?? String(error));
1103 return;
1105 clearPendingThreadCreationOutcome(routeThreadIdentity);
1106 navigation.dispatch(
1107 StackActions.replace("Thread", {
1108 draft: {
1109 draftId: restoredNewTaskDraftKey(creation.messageId),
1110 environmentId: String(creation.environmentId),
1111 projectId: String(creation.creation.projectId),
1112 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
1113 },
1114 }),
1115 );
1116 };
1117 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
1118 const { visible: worktreeSetup } = useWorktreeSetup({
1119 environmentId: selectedThread?.environmentId ?? null,
1120 threadId: selectedThread?.id ?? null,
1121 preparing:
1122 composer.selectedThreadActivityRun?.status === "preparing" ||
1123 selectedThread?.runtime?.status === "preparing" ||
1124 (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
1125 selectedThreadCreation.outcome == null),
1126 hasWorktree: selectedThread?.worktreePath != null,
1127 retryablePreparation:
1128 selectedThreadDetail !== null &&
1129 workspacePreparationRetryRunIds(selectedThreadDetail.runs, selectedThreadDetail.turnItems)
1130 .size > 0,
1131 runs: selectedThreadDetail?.runs ?? [],
1132 userMessages: [
1133 ...composer.selectedThreadFeed.flatMap((entry) =>
1134 entry.type === "message" && entry.message.role === "user" ? [entry.message] : [],
1135 ),
1136 ...composer.selectedThreadQueuedMessages.map((message) => ({
1137 id: message.messageId,
1138 createdAt: message.createdAt,
1139 })),
1140 ],
1141 });
1142 const awaitingBootstrapTurn =
1143 worktreeSetup !== null
1144 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
1145 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
1146 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
1147 const handleCancelWorktreeSetup = () => {
1148 if (!selectedThread) return;
1149 return cancelWorktreeSetup({
1150 environmentId: selectedThread.environmentId,
1151 input: { threadId: selectedThread.id },
1152 });
1153 };
1154 const stopTarget =
1155 selectedThread && (awaitingBootstrapTurn || composer.interruptibleRunId !== null)
1156 ? JSON.stringify([
1157 selectedThread.environmentId,
1158 selectedThread.id,
1159 composer.interruptibleRunId ?? worktreeSetup?.startedAt,
1160 ])
1161 : null;
1162 const stopConfirmedRun = useStableCallback(async (target: string) => {
1163 if (!selectedThread || target !== stopTarget) return;
1164 confirmedStopTargetsRef.current.add(target);
1165 if (awaitingBootstrapTurn) {
1166 const result = await handleCancelWorktreeSetup();
1167 if (result?._tag !== "Success" || result.value.cancelled) return;
1169 void handleStopThread(
1170 scopedThreadKey(selectedThread.environmentId, selectedThread.id),
1171 composer.interruptibleRunId,
1172 );
1173 });
1174 const handleRequestStopThread = () => {
1175 if (!selectedThread || stopTarget === null) return;
1176 if (confirmedStopTargetsRef.current.has(stopTarget)) {
1177 void stopConfirmedRun(stopTarget);
1178 return;
1180 Dialog.confirm({
1181 title: gt`Stop agent?`,
1182 message: gt`Stop ${{ label: selectedThread.title }}?`,
1183 confirmText: gt({ context: "verb, confirm button" })`Stop`,
1184 destructive: true,
1185 onConfirm: () => void stopConfirmedRun(stopTarget),
1186 });
1187 };
1188 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
1189 const localResendBusy = useRef(false);
1190 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
1191 const handleWorkLocally = async () => {
1192 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
1193 return;
1194 localResendBusy.current = true;
1195 const result = await cancelWorktreeSetup({
1196 environmentId: selectedThread.environmentId,
1197 input: { threadId: selectedThread.id },
1198 });
1199 if (result._tag !== "Success" || !result.value.cancelled) {
1200 localResendBusy.current = false;
1201 return;
1203 // V2 accepts launch before setup; cancellation cannot reject that delivery, so reuse server-owned prompt and uploads.
1204 const metadata = makeTurnCommandMetadata();
1205 const launched = await startLocalThread({
1206 environmentId: selectedThread.environmentId,
1207 input: buildProjectThreadStartTurnInput({
1208 ...metadata,
1209 projectId: selectedThread.projectId,
1210 projectCwd: selectedThreadProject.workspaceRoot,
1211 text: setupMessage.text,
1212 titleText: selectedThread.title,
1213 ...(setupMessage.context ? { context: setupMessage.context } : {}),
1214 uploadedAttachments: setupMessage.attachments,
1215 modelSelection: selectedThread.modelSelection,
1216 runtimeMode: selectedThread.runtimeMode,
1217 interactionMode: selectedThread.interactionMode,
1218 workspaceMode: "local",
1219 branch: null,
1220 worktreePath: null,
1221 startFromOrigin: false,
1222 worktreeBranchName: "",
1223 }),
1224 });
1225 localResendBusy.current = false;
1226 if (launched._tag !== "Success") return;
1227 navigation.dispatch(
1228 StackActions.replace("Thread", {
1229 environmentId: String(selectedThread.environmentId),
1230 threadId: metadata.threadId,
1231 }),
1232 );
1233 };
1234 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
1235 if (selectedThreadCreation === null) {
1236 return awaitingBootstrapTurn
1237 ? { kind: "preparing", preparingWorktree: true, serverOwned: true }
1238 : null;
1240 if (selectedThreadCreation.outcome?.kind === "failed") {
1241 return {
1242 kind: "failed",
1243 reason: selectedThreadCreation.outcome.reason,
1244 onEditTask: handleEditFailedCreation,
1245 };
1247 return {
1248 kind: "preparing",
1249 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
1250 serverOwned: false,
1251 };
1252 })();
1253 // Queued creation displays its prompt before server creation; temporary not-found is expected.
1254 const contentPresentation =
1255 creationState !== null
1256 ? THREAD_CONTENT_READY
1257 : projectThreadContentPresentation({
1258 hasDetail: selectedThreadDetail !== null,
1259 detailError: Option.getOrNull(selectedThreadDetailState.error),
1260 detailDeleted: selectedThreadDetailState.status === "deleted",
1261 connectionState: routeConnectionState,
1262 resolve: m,
1263 });
1264 const connectionRetrying =
1265 routeConnectionState === "connecting" || routeConnectionState === "reconnecting";
1266 // Connection failures survive retries and app suspension.
1267 const retryConnectionError = useDelayedStatus(
1268 `${environmentId}:${connectionRetrying && routeConnectionError !== null}`,
1269 connectionRetrying ? routeConnectionError : null,
1270 RECONNECT_ERROR_DELAY_MS,
1271 );
1272 const connectionStatusLabel = connectionRetryLabel(
1274 connectionError: retryConnectionError,
1275 connectionState: routeConnectionState,
1276 connectionAwaitingApproval: routeEnvironmentRuntime?.connectionAwaitingApproval === true,
1277 },
1278 m,
1279 );
1280 // A thread this client is creating has nothing older to sync.
1281 const threadSyncLabel =
1282 creationState === null
1283 ? threadSyncStatusLabel(
1284 selectedThreadDetailState.status,
1285 contentPresentation.kind,
1286 Option.isSome(selectedThreadDetailState.error),
1287 m,
1289 : null;
1290 // Transient states go in the header subtitle so the composer's status slot doesn't jump.
1291 const threadStatusLabel = useDelayedStatus(
1292 selectedThread === null ? "" : scopedThreadKey(selectedThread.environmentId, selectedThread.id),
1293 connectionStatusLabel !== null ? connectionStatusLabel : threadSyncLabel,
1294 );
1295 const inspectorHeader = props.inspectorPresentation ? (
1296 <ThreadInspectorHeader
1297 title={selectedThread?.title ?? gt`Thread`}
1298 subtitle={threadStatusLabel ?? undefined}
1299 {...props.inspectorPresentation}
1300 />
1301 ) : null;
1302 if (!environmentId || !threadId || !selectedThread) {
1303 return (
1304 <>
1305 {inspectorHeader}
1306 <OpeningThreadLoadingScreen />
1307 </>
1308 );
1310​
1311 const requiresWorktreePath =
1312 selectedThreadDetail === null ||
1313 selectedThreadCreation?.message.creation?.workspaceMode === "worktree" ||
1314 selectedThreadDetail.runs.findLast((run) => run.workspacePreparation !== undefined)
1315 ?.workspacePreparation?.type === "worktree";
1316 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
1317 return (
1318 <>
1319 {inspectorHeader}
1320 {!props.inspectorPresentation && inspectorContent ? (
1321 <Inspector
1322 // A route's own inspector (files) opens once per thread; going back keeps the user's choice.
1323 revealKey={
1324 props.renderInspector !== undefined && selectedThreadCwd !== null
1325 ? (routeThreadIdentity ?? undefined)
1326 : undefined
1328 content={inspectorContent}
1329 />
1330 ) : null}
1331 <GitActionProgressOverlay
1332 progress={gitActionProgress}
1333 onDismiss={() => dismissGitActionResult(gitActionThreadRef)}
1334 onOpenPullRequest={openPullRequest}
1335 />
1336 <ThreadScreenBinding
1337 header={
1338 props.inspectorPresentation ? null : (
1339 <ThreadHeader
1340 title={selectedThread.title}
1341 subtitle={threadStatusLabel ?? headerSubtitle}
1342 gitControls={threadGitControlProps}
1343 hasThreadCwd={selectedThreadCwd !== null}
1344 cwd={requiresWorktreePath ? selectedThreadWorktreePath : selectedThreadCwd}
1345 inspectorMode={inspectorMode}
1346 onOpenFilesInspector={handleOpenFilesInspector}
1347 onReturnToThread={props.onReturnToThread}
1348 />
1351 canOperateThread={canOperateThread}
1352 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
1353 selectedThreadDetailRef={selectedThreadDetailRef}
1354 contentPresentation={contentPresentation}
1355 screenTone={connectionTone(
1356 routeConnectionState,
1357 routeEnvironmentRuntime?.connectionAwaitingApproval === true,
1358 m,
1359 )}
1360 connectionError={routeConnectionError}
1361 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
1362 feedbackSubmissions={composer.feedbackSubmissions}
1363 onDismissFeedback={composer.dismissFeedback}
1364 selectedThreadFeed={composer.selectedThreadFeed}
1365 pendingHandoff={composer.pendingHandoff}
1366 activityRun={composer.selectedThreadActivityRun}
1367 activeWorkStartedAt={
1368 creationState?.kind === "preparing" ||
1369 (worktreeSetup !== null && setupTurnStartedAt === null)
1370 ? null
1371 : composer.activeWorkStartedAt
1373 isCompacting={composer.isCompacting}
1374 compactBeforeSend={composer.compactBeforeSend}
1375 runlessWorkActive={composer.runlessWorkActive}
1376 extensionStatuses={composer.extensionStatuses}
1377 providerSubagentStatus={composer.providerSubagentStatus}
1378 creationState={creationState}
1379 worktreeSetup={
1380 worktreeSetup
1381 ? {
1382 snapshot: worktreeSetup,
1383 turnStarted: setupTurnStartedAt !== null,
1384 onCancel: () => void handleCancelWorktreeSetup(),
1385 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
1387 : null
1389 activePendingApproval={requests.activePendingApproval}
1390 activePendingApprovals={requests.activePendingApprovals}
1391 respondingApprovalId={requests.respondingApprovalId}
1392 activePendingUserInput={requests.activePendingUserInput}
1393 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1394 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1395 respondingUserInputId={requests.respondingUserInputId}
1396 connectionStateLabel={routeConnectionState}
1397 historyControls={historyControls}
1398 activeThreadBusy={composer.activeThreadBusy}
1399 canStopThread={stopTarget !== null}
1400 queuedRunEdit={composer.queuedRunEdit}
1401 composerDraftKey={composer.composerDraftKey}
1402 followUpBehavior={composer.followUpBehavior}
1403 canSteerActiveTurn={composer.canSteerActiveTurn}
1404 isSavingQueuedEdit={composer.isSavingQueuedEdit}
1405 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
1406 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
1407 environmentId={selectedThread.environmentId}
1408 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1409 threadCwd={selectedThreadCwd}
1410 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1411 queuedMessages={
1412 selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"
1413 ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]
1414 : composer.selectedThreadQueuedMessages
1416 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1417 layoutVariant={layout.variant}
1418 usesAutomaticContentInsets={usesNativeHeaderGlass}
1419 onOpenConnectionEditor={handleOpenConnectionEditor}
1420 onChangeDraftMessage={composer.onChangeDraftMessage}
1421 onPickDraftMedia={composer.onPickDraftMedia}
1422 onPickDraftFiles={composer.onPickDraftFiles}
1423 onNativePasteImages={composer.onNativePasteImages}
1424 onNativePasteText={composer.onNativePasteText}
1425 onRemoveDraftImage={composer.onRemoveDraftImage}
1426 serverConfig={serverConfig}
1427 onStopThread={handleRequestStopThread}
1428 missingWorkspace={missingWorkspace}
1429 onResumeQueue={composer.canResume && missingWorkspace === null ? handleResumeQueue : null}
1430 onSendMessage={composer.onSendMessage}
1431 offersSideChat={composer.sideChatUnavailableReason === null}
1432 onSendCommand={composer.onSendCommand}
1433 onReconnectEnvironment={handleReconnectEnvironment}
1434 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1435 onRespondToApproval={requests.onRespondToApproval}
1436 onSelectUserInputOption={requests.onSelectUserInputOption}
1437 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1438 onSubmitUserInput={requests.onSubmitUserInput}
1439 onDismissUserInput={requests.onDismissUserInput}
1440 />
1441 </>
1442 );
1444​
1445export function FullscreenThreadRouteScreen(
1446 props: StaticScreenProps<{
1447 readonly environmentId: string;
1448 readonly threadId: string;
1449 }>,
1450) {
1451 const navigation = useNavigation();
1452 return (
1453 <InspectorContentScope>
1454 <ThreadRouteScreen
1455 route={props.route}
1456 inspectorPresentation={{ onClose: () => navigation.goBack() }}
1457 />
1458 </InspectorContentScope>
1459 );
1461​
1462/** Reads the pane state itself, so a sidebar toggle doesn't re-render the whole thread screen. */
1463function ThreadInspectorPreviewWhileVisible(props: Parameters<typeof ThreadInspectorPreview>[0]) {
1464 const { panes } = useWorkspacePaneState();
1465 return panes.auxiliaryPaneVisible ? <ThreadInspectorPreview {...props} /> : null;