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