Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { useRememberThreadProject } from "./useRememberThreadProject";
3import { useOpenPullRequest } from "../../native/useOpenPullRequest";
4import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
5import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
6import { useWorktreeSetup } from "./use-worktree-setup";
7import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
8import { AppBar } from "../../components/ui/AppBar";
9import {
10 StackActions,
11 useNavigation,
12 useRoute,
13 type StaticScreenProps,
14} from "@react-navigation/native";
15import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
16import * as Option from "effect/Option";
17import {
18 AuthOrchestrationOperateScope,
19 AuthTerminalOperateScope,
20 AuthTerminalReadScope,
21 DEFAULT_SERVER_SETTINGS,
22 EnvironmentId,
23 MessageId,
24 ThreadId,
25 type ProjectScript,
26} from "@t3tools/contracts";
27import {
28 projectScriptCwd,
29 projectScriptRuntimeEnv,
30 projectScriptTerminalInput,
31 resolveProjectScripts,
32} from "@t3tools/shared/projectScripts";
33import { Platform } from "react-native";
34import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
35import { useSafeAreaInsets } from "react-native-safe-area-context";
36import { useConnectionsReady } from "../../state/workspace";
37import { useEnvironmentShellReadiness } from "../../state/shell";
38import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
39import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
40import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
41import { useEnvironmentQuery } from "../../state/query";
42import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
43import { vcsEnvironment } from "../../state/vcs";
44import { EmptyState } from "../../components/ui/EmptyState";
45import { LoadingScreen } from "../../components/LoadingScreen";
46import { scopedThreadKey } from "../../lib/scopedEntities";
47import { scopeThreadRef } from "@t3tools/client-runtime/environment";
48import { useThreadShell } from "../../state/entities";
49import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
50import { connectionTone } from "../connection/connectionTone";
51import {
52 useRemoteConnections,
53 useRemoteConnectionStatus,
54 useRemoteEnvironmentRuntime,
55} from "../../state/use-remote-environment-registry";
56import { useKnownTerminalSessions } from "../../state/use-terminal-session";
57import { uuidv4 } from "../../lib/uuid";
58import {
59 isAtomCommandInterrupted,
60 squashAtomCommandFailure,
61} from "@t3tools/client-runtime/state/runtime";
62import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
63import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
64import { useThreadSelection } from "../../state/use-thread-selection";
65import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
66import {
67 buildTerminalMenuSessions,
68 nextOpenTerminalId,
69 resolveProjectScriptTerminalId,
70} from "../terminal/terminalMenu";
71import {
72 resolvePreferredThreadWorktreePath,
73 stagePendingTerminalLaunch,
74} from "../terminal/terminalLaunchContext";
75import type { ThreadDetailScreenProps } from "./ThreadDetailScreen";
76import { ThreadScreenBinding, ThreadScreenFallback, ThreadScreenHost } from "./ThreadScreenHost";
77import { draftRouteIdentity } from "./thread-route-state";
78import { NewTaskDraftRouteScreen, type NewTaskDraftRouteParams } from "./NewTaskDraftRouteScreen";
79import { GitOverviewSheet } from "./git/GitOverviewSheet";
80import { useAtomCommand } from "../../state/use-atom-command";
81import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
82import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
83import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
84import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
85import { useThreadComposerState } from "../../state/use-thread-composer-state";
86import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
87import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
88import { threadEnvironment } from "../../state/threads";
89import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/threads";
90import { useProjects } from "../../state/entities";
91import { projectThreadContentPresentation } from "./threadContentPresentation";
92import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
93import {
94 useAdaptiveWorkspaceLayout,
95 useAdaptiveWorkspacePaneRole,
96 useRegisterWorkspaceInspector,
97} from "../layout/AdaptiveWorkspaceLayout";
98import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
99import {
100 ThreadInspectorContentStack,
101 type ThreadInspectorMode,
102} from "./thread-inspector-content-stack";
103import {
104 threadDetailErrorIsCurrent,
105 threadRouteIsHydrating,
106 threadRouteOpensDraft,
107} from "./thread-route-hydration";
108import { ThreadHeader } from "./ThreadHeader";
109import { resumeThread } from "./resume-thread";
110import {
111 useAndroidWorkspaceBack,
112 useWorkspaceBackNavigation,
113} from "../workspace/useAndroidWorkspaceNavigation";
114import { openSettings } from "../settings/settings-navigation";
115import {
116 InspectorContentScope,
117 ThreadInspectorHeader,
118 ThreadInspectorPreview,
119 type ThreadInspectorPresentation,
120} from "./thread-inspector-preview";
121import type { ThreadInspectorTarget } from "./thread-inspector-navigation";
122import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
123
124function InspectorPaneRoleActivation() {
125 useAdaptiveWorkspacePaneRole("inspector");
126 return null;
127}
128
129function firstRouteParam(value: string | string[] | undefined): string | null {
130 const first = Array.isArray(value) ? value[0] : value;
131 return first === undefined || first.trim().length === 0 ? null : first;
132}
133
134function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) {
135 const goBack = useWorkspaceBackNavigation("threads");
136 const { layout } = useAdaptiveWorkspaceLayout();
137 const { themeVariables } = useAppearancePreferences();
138 if (Platform.OS !== "android")
139 return <ThreadScreenFallback>{props.children}</ThreadScreenFallback>;
140
141 return (
142 <>
143 <AppBar
144 title="Thread"
145 options={{ contentStyle: { backgroundColor: themeVariables["--color-header"] } }}
146 onBack={layout.usesSplitView ? undefined : goBack}
147 hideBottomBorder
148 />
149 <ThreadScreenFallback>{props.children}</ThreadScreenFallback>
150 </>
151 );
152}
153
154function OpeningThreadLoadingScreen() {
155 return (
156 <ThreadRouteFallbackLayout>
157 <LoadingScreen
158 message="Opening thread…"
159 messagePlacement="above-spinner"
160 embedded={Platform.OS === "android"}
161 />
162 </ThreadRouteFallbackLayout>
163 );
164}
165
166type ThreadRouteScreenRouteProps = StaticScreenProps<{
167 readonly environmentId?: string;
168 readonly threadId?: string;
169 readonly draft?: NewTaskDraftRouteParams;
170 readonly inspector?: ThreadInspectorTarget;
171 readonly prompt?: string | string[];
172}>;
173
174interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
175 readonly inspectorPresentation?: ThreadInspectorPresentation;
176 readonly onReturnToThread?: () => void;
177 readonly renderInspector?: (headerInset: number) => ReactNode;
178}
179
180function ThreadUnavailableScreen(props: {
181 readonly actionLabel: string;
182 readonly onAction: () => void;
183}) {
184 return (
185 <ThreadRouteFallbackLayout>
186 <ScrollView
187 contentInsetAdjustmentBehavior="automatic"
188 contentContainerStyle={{
189 flexGrow: 1,
190 justifyContent: "center",
191 paddingHorizontal: 24,
192 paddingVertical: 32,
193 }}
194 className="bg-screen flex-1 android:bg-transparent"
195 >
196 <EmptyState
197 title="Thread unavailable"
198 detail="This thread is not available in the current mobile snapshot."
199 actionLabel={props.actionLabel}
200 onAction={props.onAction}
201 />
202 </ScrollView>
203 </ThreadRouteFallbackLayout>
204 );
205}
206
207/** A thread that can't load opens a new task in its environment instead of a dead end. */
208function UnavailableThreadDraftRedirect(props: { readonly environmentId: EnvironmentId }) {
209 const navigation = useNavigation();
210 const projects = useProjects();
211 const openDraft = useEffectEvent(() => {
212 const project = projects.find((candidate) => candidate.environmentId === props.environmentId);
213 navigation.dispatch(
214 StackActions.replace("Thread", {
215 draft: project
216 ? {
217 requestId: uuidv4(),
218 environmentId: String(project.environmentId),
219 projectId: String(project.id),
220 }
221 : { requestId: uuidv4() },
222 }),
223 );
224 });
225 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- replaces this route with a new draft thread route for the environment's project on mount
226 useEffect(() => {
227 openDraft();
228 }, []);
229 return <OpeningThreadLoadingScreen />;
230}
231
232export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
233 return (
234 <ThreadScreenHost>
235 {props.route.params?.draft ? (
236 <NewTaskDraftRouteScreen
237 key={draftRouteIdentity(props.route.params.draft)}
238 route={{ ...props.route, params: props.route.params.draft }}
239 />
240 ) : (
241 <LiveThreadRouteController {...props} />
242 )}
243 </ThreadScreenHost>
244 );
245}
246
247function LiveThreadRouteController(props: ThreadRouteScreenProps) {
248 useAndroidWorkspaceBack("threads");
249 const connectionsReady = useConnectionsReady();
250 const { connectionState } = useRemoteConnectionStatus();
251 const { selectedThread } = useThreadSelection();
252 const params = props.route.params ?? {};
253 const environmentIdRaw = firstRouteParam(params.environmentId);
254 const threadIdRaw = firstRouteParam(params.threadId);
255 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
256 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
257 const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
258 const { onReconnectEnvironment } = useRemoteConnections();
259 const navigation = useNavigation();
260 const routeName = useRoute().name;
261 const routeConnectionState =
262 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
263 const routeThreadKey =
264 environmentId !== null && threadIdRaw !== null
265 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
266 : null;
267 const selectedThreadKey =
268 selectedThread === null
269 ? null
270 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
271 const selectedThreadDetailState = useSelectedThreadDetailState();
272 const detailError = selectedThreadDetailState.error;
273 const [errorBeforeConnected, setErrorBeforeConnected] = useState(() =>
274 routeConnectionState === "connected" ? Option.none<string>() : detailError,
275 );
276 if (routeConnectionState !== "connected" && errorBeforeConnected !== detailError) {
277 setErrorBeforeConnected(detailError);
278 }
279 const withInspectorHeader = (content: ReactNode) => (
280 <>
281 {props.inspectorPresentation ? (
282 <ThreadInspectorHeader
283 title={selectedThread?.title ?? "Thread"}
284 {...props.inspectorPresentation}
285 />
286 ) : null}
287 {content}
288 </>
289 );
290
291 if (environmentId === null || threadIdRaw === null) {
292 return withInspectorHeader(<OpeningThreadLoadingScreen />);
293 }
294
295 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
296 return withInspectorHeader(
297 <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />,
298 );
299 }
300
301 const stillHydrating = threadRouteIsHydrating({
302 isLoadingConnections: !connectionsReady,
303 environmentRegistered: routeEnvironmentRuntime !== null,
304 localCacheRead:
305 routeEnvironmentShellState.cacheRead &&
306 selectedThreadDetailState !== EMPTY_ENVIRONMENT_THREAD_STATE,
307 connectionState: routeConnectionState,
308 shellStatus: routeEnvironmentShellState.status,
309 shellHasError: routeEnvironmentShellState.hasError,
310 detailStatus: selectedThreadDetailState.status,
311 detailHasError: threadDetailErrorIsCurrent({
312 connectionState: routeConnectionState,
313 error: detailError,
314 errorBeforeConnected,
315 }),
316 });
317
318 if (stillHydrating) {
319 return withInspectorHeader(<OpeningThreadLoadingScreen />);
320 }
321
322 if (
323 routeName === "Thread" &&
324 !props.inspectorPresentation &&
325 threadRouteOpensDraft({
326 connectionState: routeConnectionState,
327 detailStatus: selectedThreadDetailState.status,
328 })
329 ) {
330 return <UnavailableThreadDraftRedirect environmentId={environmentId} />;
331 }
332
333 return withInspectorHeader(
334 <ThreadUnavailableScreen
335 actionLabel={
336 routeEnvironmentRuntime === null ? "Manage environments" : "Reconnect environment"
337 }
338 onAction={() => {
339 if (routeEnvironmentRuntime !== null) {
340 onReconnectEnvironment(environmentId);
341 return;
342 }
343 openSettings(navigation, "SettingsEnvironments");
344 }}
345 />,
346 );
347}
348
349function ThreadRouteContent(
350 props: ThreadRouteScreenProps & {
351 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
352 },
353) {
354 const { themeVariables } = useAppearancePreferences();
355 const headerColor = themeVariables["--color-header"];
356 const { fileInspector, layout, panes, showAuxiliaryPane, toggleAuxiliaryPane } =
357 useAdaptiveWorkspaceLayout();
358 const { connectionState } = useRemoteConnectionStatus();
359 const { onReconnectEnvironment } = useRemoteConnections();
360 const {
361 selectedThread,
362 selectedThreadCreation,
363 selectedThreadDetailRef,
364 selectedThreadProject,
365 selectedEnvironmentConnection,
366 } = useThreadSelection();
367 useRememberThreadProject(selectedThreadProject);
368 const canOperateThread = useEnvironmentScope(
369 selectedThread?.environmentId ?? null,
370 AuthOrchestrationOperateScope,
371 );
372 const canReadTerminal = useEnvironmentScope(
373 selectedThread?.environmentId ?? null,
374 AuthTerminalReadScope,
375 );
376 const canOperateTerminal = useEnvironmentScope(
377 selectedThread?.environmentId ?? null,
378 AuthTerminalOperateScope,
379 );
380 const selectedThreadDetailState = props.selectedThreadDetailState;
381 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
382 const { selectedThreadCwd } = useSelectedThreadWorktree();
383 const composer = useThreadComposerState();
384 const gitState = useSelectedThreadGitState();
385 const gitActions = useSelectedThreadGitActions();
386 const requests = useSelectedThreadRequests();
387 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
388 const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, {
389 label: "resume queue",
390 reportFailure: false,
391 });
392 const continueThreadRun = useAtomCommand(threadEnvironment.startTurn, {
393 label: "continue thread",
394 reportFailure: false,
395 });
396 const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
397 label: "set thread runtime mode",
398 reportFailure: false,
399 });
400 const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
401 label: "set thread interaction mode",
402 reportFailure: false,
403 });
404 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
405 label: "load earlier thread history",
406 reportFailure: false,
407 });
408 const historyControls = (() => {
409 const history = selectedThreadDetailState.history;
410 if (!selectedThread) {
411 return undefined;
412 }
413 if (!history.hasMoreHistory && history.error === null) {
414 return undefined;
415 }
416 return {
417 hasMoreHistory: history.hasMoreHistory,
418 loading: history.loading,
419 error: history.error,
420 onLoadEarlier: () => {
421 void loadEarlierHistory({
422 environmentId: selectedThread.environmentId,
423 input: { threadId: selectedThread.id },
424 });
425 },
426 onLoadThrough: (throughEntryId: string) => {
427 void loadEarlierHistory({
428 environmentId: selectedThread.environmentId,
429 input: { threadId: selectedThread.id, throughEntryId },
430 });
431 },
432 };
433 })();
434 const navigation = useNavigation();
435 const selectDetail = useSelectWorkspaceDetail();
436 const openPullRequest = useOpenPullRequest();
437 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
438 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
439 const mergeBackRun =
440 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
441 const mergeBackBusyRef = useRef(false);
442 const handleMergeBack = async () => {
443 if (
444 mergeBackBusyRef.current ||
445 !selectedThread ||
446 mergeBackTargetThreadId === null ||
447 mergeBackRun === null
448 ) {
449 return;
450 }
451 mergeBackBusyRef.current = true;
452 const result = await mergeBack({
453 environmentId: selectedThread.environmentId,
454 input: {
455 sourceThreadId: selectedThread.id,
456 targetThreadId: mergeBackTargetThreadId,
457 runId: mergeBackRun.id,
458 creationSource: "mobile",
459 },
460 });
461 mergeBackBusyRef.current = false;
462 if (result._tag !== "Success") return;
463 selectDetail({
464 name: "Thread",
465 params: { environmentId: selectedThread.environmentId, threadId: mergeBackTargetThreadId },
466 });
467 };
468 const params = props.route.params ?? {};
469 const environmentIdRaw = firstRouteParam(params.environmentId);
470 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
471 const threadId = firstRouteParam(params.threadId);
472 const routeThreadIdentity =
473 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
474 // The chosen mode survives thread switches; "route" only applies while the route
475 // supplies an inspector, which is also the default whenever it does.
476 const [chosenInspectorMode, setChosenInspectorMode] = useState<ThreadInspectorMode | null>(null);
477 const previewTarget = props.inspectorPresentation ? undefined : params.inspector;
478 const inspectorMode = (() => {
479 if (previewTarget) return "preview";
480 const mode =
481 props.renderInspector === undefined
482 ? chosenInspectorMode === "route"
483 ? null
484 : chosenInspectorMode
485 : chosenInspectorMode === null || chosenInspectorMode === "route"
486 ? "route"
487 : chosenInspectorMode;
488 return mode === "files" && selectedThreadCwd === null ? null : mode;
489 })();
490 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- closes the workspace navigator's auxiliary pane when the thread has no cwd for the file inspector
491 useEffect(() => {
492 if (
493 props.inspectorPresentation === undefined &&
494 fileInspector.supported &&
495 selectedThreadCwd === null &&
496 inspectorMode === null &&
497 panes.auxiliaryPaneVisible
498 ) {
499 toggleAuxiliaryPane();
500 }
501 }, [
502 fileInspector.supported,
503 inspectorMode,
504 panes.auxiliaryPaneVisible,
505 props.inspectorPresentation,
506 selectedThreadCwd,
507 toggleAuxiliaryPane,
508 ]);
509
510 const revealPreview = useEffectEvent(() => showAuxiliaryPane("inspector"));
511 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the workspace navigator's inspector pane when route params bring a preview target
512 useEffect(() => {
513 if (previewTarget) revealPreview();
514 }, [previewTarget]);
515 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
516 const routeConnectionState =
517 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
518 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
519 const selectedThreadWithDraftSettings = selectedThread
520 ? {
521 ...selectedThread,
522 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
523 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
524 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
525 }
526 : null;
527
528 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
529 const delegatedFrom = selectedThread?.delegatedFrom ?? null;
530 const delegatedFromRef =
531 delegatedFrom === null
532 ? null
533 : scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
534 // The title it had at delegation, until this client sees the parent itself.
535 const delegatedFromThread = useThreadShell(delegatedFromRef);
536 const headerSubtitle = [
537 selectedThreadProject?.title ?? null,
538 selectedEnvironmentConnection?.environmentLabel ?? null,
539 // A linked environment's delegated task names its parent; other linked work its origin.
540 delegatedFrom !== null
541 ? `Subagent of ${delegatedFromThread?.title ?? delegatedFrom.title}`
542 : selectedThread?.linkOrigin
543 ? `From ${selectedThread.linkOrigin.label}`
544 : null,
545 ]
546 .filter(Boolean)
547 .join(" · ");
548 const gitStatus = useEnvironmentQuery(
549 selectedThread !== null && selectedThreadCwd !== null
550 ? vcsEnvironment.status({
551 environmentId: selectedThread.environmentId,
552 input: { cwd: selectedThreadCwd },
553 })
554 : null,
555 );
556 const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
557 environmentId: selectedThread?.environmentId ?? null,
558 threadId: selectedThread?.id ?? null,
559 });
560 const terminalMenuSessions = buildTerminalMenuSessions({
561 knownSessions: knownTerminalSessions ?? [],
562 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
563 });
564 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
565 const handleReconnectEnvironment = () => {
566 if (!environmentId) {
567 return;
568 }
569 onReconnectEnvironment(environmentId);
570 };
571
572 const gitActionProgressTarget = {
573 environmentId: selectedThread?.environmentId ?? null,
574 cwd: selectedThreadCwd,
575 };
576 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
577
578 const handleOpenGitInspector = () => {
579 if (!fileInspector.supported) {
580 if (selectedThread === null) {
581 return;
582 }
583 navigation.navigate("GitOverview", {
584 environmentId: String(selectedThread.environmentId),
585 threadId: String(selectedThread.id),
586 });
587 return;
588 }
589 navigation.setParams({ inspector: undefined });
590 setChosenInspectorMode("git");
591 showAuxiliaryPane("inspector");
592 };
593 const handleOpenFilesInspector = () => {
594 if (selectedThread === null || selectedThreadCwd === null) {
595 return;
596 }
597 if (!fileInspector.supported) {
598 navigation.navigate("ThreadFiles", {
599 environmentId: String(selectedThread.environmentId),
600 threadId: String(selectedThread.id),
601 });
602 return;
603 }
604 navigation.setParams({ inspector: undefined });
605 setChosenInspectorMode(props.renderInspector === undefined ? "files" : "route");
606 showAuxiliaryPane("inspector");
607 };
608 const handleToggleInspector = () => {
609 if (inspectorMode === null) {
610 handleOpenFilesInspector();
611 return;
612 }
613 toggleAuxiliaryPane();
614 };
615 const handleSelectInspectorFile = (path: string) => {
616 if (selectedThread === null) {
617 return;
618 }
619 const params = {
620 environmentId: String(selectedThread.environmentId),
621 threadId: String(selectedThread.id),
622 path: path.split("/").filter((segment) => segment.length > 0),
623 };
624 if (fileInspector.supported) {
625 navigation.navigate("ThreadFile", params);
626 return;
627 }
628 navigation.navigate("ThreadFile", params);
629 };
630 const safeAreaInsets = useSafeAreaInsets();
631 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
632 const renderGitInspector = () => (
633 <GitOverviewSheet
634 headerInset={inspectorHeaderInset}
635 presentation="inspector"
636 route={{ params: { environmentId: environmentId!, threadId: threadId! } }}
637 />
638 );
639 const renderFilesInspector = () =>
640 selectedThread !== null && selectedThreadCwd !== null ? (
641 <ThreadFileNavigatorPane
642 cwd={selectedThreadCwd}
643 environmentId={selectedThread.environmentId}
644 headerInset={inspectorHeaderInset}
645 projectName={selectedThreadProject?.title ?? "Files"}
646 selectedPath={null}
647 onSelectFile={handleSelectInspectorFile}
648 />
649 ) : null;
650 const renderRouteInspector = () => props.renderInspector?.(inspectorHeaderInset);
651 const renderPreviewInspector = () =>
652 previewTarget && panes.auxiliaryPaneVisible ? (
653 <ThreadInspectorPreview
654 target={previewTarget}
655 renderThread={(screen) => <ThreadRouteScreen {...screen} />}
656 onClose={toggleAuxiliaryPane}
657 onOpen={(inspector) => {
658 if (
659 inspector.type === "thread" &&
660 inspector.environmentId === environmentId &&
661 inspector.threadId === threadId
662 ) {
663 toggleAuxiliaryPane();
664 return;
665 }
666 navigation.setParams({ inspector });
667 }}
668 />
669 ) : null;
670 const renderInspectorStack = () =>
671 inspectorMode === null ? null : (
672 <ThreadInspectorContentStack
673 renderPreview={renderPreviewInspector}
674 renderFiles={renderFilesInspector}
675 renderGit={renderGitInspector}
676 mode={inspectorMode}
677 resetKeys={[routeThreadIdentity, selectedThreadCwd]}
678 renderRoute={props.renderInspector ? renderRouteInspector : undefined}
679 />
680 );
681 const activeInspectorRenderer =
682 props.inspectorPresentation || inspectorMode === null ? undefined : renderInspectorStack;
683 useRegisterWorkspaceInspector(activeInspectorRenderer);
684
685 const handleOpenConnectionEditor = () => {
686 void navigation.navigate("Connections");
687 };
688 const handleStopThread = () => {
689 if (
690 !selectedThread ||
691 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
692 composer.interruptibleRunId === null
693 ) {
694 return;
695 }
696 return interruptThreadTurn({
697 environmentId: selectedThread.environmentId,
698 input: {
699 threadId: selectedThread.id,
700 runId: composer.interruptibleRunId,
701 },
702 });
703 };
704
705 const handleResumeQueue = async () => {
706 if (!selectedThread) return;
707 const result = await resumeThread({
708 thread: selectedThread,
709 resumableRunId: composer.resumableRunId,
710 queueHeld: composer.queueHeld,
711 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
712 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
713 modelSelection: composer.modelSelection,
714 messageId: MessageId.make(uuidv4()),
715 createdAt: new Date().toISOString(),
716 setRuntimeMode: setThreadRuntimeMode,
717 setInteractionMode: setThreadInteractionMode,
718 startTurn: continueThreadRun,
719 resumeQueue: resumeThreadQueue,
720 });
721 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
722 const error = squashAtomCommandFailure(result);
723 Dialog.alert(
724 "Could not resume thread",
725 error instanceof Error ? error.message : "Try again.",
726 );
727 }
728 };
729
730 const handleOpenTerminal = (nextTerminalId?: string | null) => {
731 if (
732 !selectedThread ||
733 !selectedThreadProject?.workspaceRoot ||
734 (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
735 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
736 ) {
737 return;
738 }
739
740 void navigation.navigate("ThreadTerminal", {
741 environmentId: String(selectedThread.environmentId),
742 threadId: String(selectedThread.id),
743 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
744 });
745 };
746
747 const handleOpenNewTerminal = () => {
748 if (
749 !selectedThread ||
750 !selectedThreadProject?.workspaceRoot ||
751 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
752 ) {
753 return;
754 }
755
756 const nextId = nextOpenTerminalId({
757 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
758 ...(knownTerminalSessions === null ||
759 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
760 ? { uniqueSuffix: uuidv4() }
761 : {}),
762 });
763 void navigation.navigate("ThreadTerminal", {
764 environmentId: String(selectedThread.environmentId),
765 threadId: String(selectedThread.id),
766 terminalId: nextId,
767 });
768 };
769
770 const handleRunProjectScript = async (script: ProjectScript) => {
771 if (
772 !selectedThread ||
773 !selectedThreadProject?.workspaceRoot ||
774 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
775 ) {
776 return;
777 }
778
779 const targetTerminalId = resolveProjectScriptTerminalId({
780 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
781 ...(knownTerminalSessions === null ||
782 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
783 ? { uniqueSuffix: uuidv4() }
784 : {}),
785 hasRunningTerminal: terminalMenuSessions.some(
786 (session) => session.status === "running" || session.status === "starting",
787 ),
788 });
789 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
790 threadShellWorktreePath: selectedThread.worktreePath ?? null,
791 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
792 });
793 const cwd = projectScriptCwd({
794 project: { cwd: selectedThreadProject.workspaceRoot },
795 worktreePath: preferredWorktreePath,
796 });
797 const env = projectScriptRuntimeEnv({
798 project: { cwd: selectedThreadProject.workspaceRoot },
799 worktreePath: preferredWorktreePath,
800 });
801 stagePendingTerminalLaunch({
802 target: {
803 environmentId: selectedThread.environmentId,
804 threadId: selectedThread.id,
805 terminalId: targetTerminalId,
806 },
807 launch: {
808 cwd,
809 worktreePath: preferredWorktreePath,
810 env,
811 initialInput: projectScriptTerminalInput(script.command),
812 },
813 });
814
815 void navigation.navigate("ThreadTerminal", {
816 environmentId: String(selectedThread.environmentId),
817 threadId: String(selectedThread.id),
818 terminalId: targetTerminalId,
819 });
820 };
821 const threadGitControlProps = {
822 environmentId: environmentIdRaw ?? "",
823 threadId: threadId ?? "",
824 auxiliaryPaneControl:
825 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
826 ? {
827 accessibilityLabel: "Toggle inspector",
828 onPress: handleToggleInspector,
829 }
830 : undefined,
831 onOpenFilesInspector:
832 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
833 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
834 onMergeBack:
835 mergeBackTargetThreadId !== null && mergeBackRun !== null
836 ? () => void handleMergeBack()
837 : undefined,
838 currentBranch: selectedThread?.branch ?? null,
839 gitStatus: gitStatus.data,
840 gitOperationLabel: gitState.gitOperationLabel,
841 canOpenTerminal:
842 Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
843 canOperateTerminal,
844 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
845 projectScripts: selectedThreadProject
846 ? resolveProjectScripts(
847 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
848 selectedThreadProject,
849 )
850 : [],
851 terminalSessions: terminalMenuSessions,
852 showDirectFileControl: layout.usesSplitView,
853 onOpenTerminal: handleOpenTerminal,
854 onOpenNewTerminal: handleOpenNewTerminal,
855 onRunProjectScript: handleRunProjectScript,
856 onPull: gitActions.onPullSelectedThreadBranch,
857 onRunAction: gitActions.onRunSelectedThreadGitAction,
858 };
859 const handleEditFailedCreation = async () => {
860 const creation = selectedThreadCreation?.message;
861 if (!creation?.creation || routeThreadIdentity === null) {
862 return;
863 }
864 // Open recovery by draft id or the sheet creates an empty draft and strands restored content.
865 try {
866 await recoverFailedThreadDraft(creation);
867 } catch (error) {
868 Dialog.alert(
869 "Could not restore draft",
870 error instanceof Error ? error.message : String(error),
871 );
872 return;
873 }
874 clearPendingThreadCreationOutcome(routeThreadIdentity);
875 navigation.dispatch(
876 StackActions.replace("Thread", {
877 draft: {
878 draftId: restoredNewTaskDraftKey(creation.messageId),
879 environmentId: String(creation.environmentId),
880 projectId: String(creation.creation.projectId),
881 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
882 },
883 }),
884 );
885 };
886 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
887 const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({
888 environmentId: selectedThread?.environmentId ?? null,
889 threadId: selectedThread?.id ?? null,
890 preparing:
891 composer.selectedThreadActivityRun?.status === "preparing" ||
892 selectedThread?.runtime?.status === "preparing" ||
893 selectedThread?.worktreePath != null ||
894 (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
895 selectedThreadCreation.outcome == null),
896 turnStarted: setupTurnStartedAt !== null,
897 followUpSent:
898 composer.selectedThreadFeed.filter(
899 (entry) => entry.type === "message" && entry.message.role === "user",
900 ).length +
901 composer.selectedThreadQueueCount >
902 1,
903 });
904 const awaitingBootstrapTurn =
905 worktreeSetup !== null
906 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
907 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
908 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
909 const handleCancelWorktreeSetup = () => {
910 if (!selectedThread) return;
911 void cancelWorktreeSetup({
912 environmentId: selectedThread.environmentId,
913 input: { threadId: selectedThread.id },
914 });
915 };
916 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
917 const localResendBusy = useRef(false);
918 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
919 const handleWorkLocally = async () => {
920 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
921 return;
922 localResendBusy.current = true;
923 const result = await cancelWorktreeSetup({
924 environmentId: selectedThread.environmentId,
925 input: { threadId: selectedThread.id },
926 });
927 if (result._tag !== "Success" || !result.value.cancelled) {
928 localResendBusy.current = false;
929 return;
930 }
931 // V2 accepts launch before setup; cancellation cannot reject that delivery, so reuse server-owned prompt and uploads.
932 const metadata = makeTurnCommandMetadata();
933 const launched = await startLocalThread({
934 environmentId: selectedThread.environmentId,
935 input: buildProjectThreadStartTurnInput({
936 ...metadata,
937 projectId: selectedThread.projectId,
938 projectCwd: selectedThreadProject.workspaceRoot,
939 text: setupMessage.text,
940 titleText: selectedThread.title,
941 ...(setupMessage.context ? { context: setupMessage.context } : {}),
942 uploadedAttachments: setupMessage.attachments,
943 modelSelection: selectedThread.modelSelection,
944 runtimeMode: selectedThread.runtimeMode,
945 interactionMode: selectedThread.interactionMode,
946 workspaceMode: "local",
947 branch: null,
948 worktreePath: null,
949 startFromOrigin: false,
950 worktreeBranchName: "",
951 }),
952 });
953 localResendBusy.current = false;
954 if (launched._tag !== "Success") return;
955 navigation.dispatch(
956 StackActions.replace("Thread", {
957 environmentId: String(selectedThread.environmentId),
958 threadId: metadata.threadId,
959 }),
960 );
961 };
962 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
963 if (selectedThreadCreation === null) {
964 return awaitingBootstrapTurn
965 ? { kind: "preparing", preparingWorktree: true, serverOwned: true }
966 : null;
967 }
968 if (selectedThreadCreation.outcome?.kind === "failed") {
969 return {
970 kind: "failed",
971 reason: selectedThreadCreation.outcome.reason,
972 onEditTask: handleEditFailedCreation,
973 };
974 }
975 return {
976 kind: "preparing",
977 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
978 serverOwned: false,
979 };
980 })();
981 if (!environmentId || !threadId) {
982 return <OpeningThreadLoadingScreen />;
983 }
984
985 if (!selectedThread) {
986 return <OpeningThreadLoadingScreen />;
987 }
988
989 // Queued creation displays its prompt before server creation; temporary not-found is expected.
990 const contentPresentation =
991 creationState !== null
992 ? { kind: "ready" as const }
993 : projectThreadContentPresentation({
994 hasDetail: selectedThreadDetail !== null,
995 detailError: Option.getOrNull(selectedThreadDetailState.error),
996 detailDeleted: selectedThreadDetailState.status === "deleted",
997 connectionState: routeConnectionState,
998 });
999 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
1000 const renderThreadRouteBody = () => (
1001 <>
1002 <GitActionProgressOverlay
1003 progress={gitActionProgress}
1004 onDismiss={dismissGitActionResult}
1005 onOpenPullRequest={openPullRequest}
1006 />
1007
1008 <>
1009 <ThreadScreenBinding
1010 header={
1011 props.inspectorPresentation ? null : (
1012 <ThreadHeader
1013 title={selectedThread.title}
1014 subtitle={headerSubtitle}
1015 headerColor={headerColor}
1016 usesNativeHeaderGlass={usesNativeHeaderGlass}
1017 gitControls={threadGitControlProps}
1018 hasThreadCwd={selectedThreadCwd !== null}
1019 hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
1020 fileInspectorSupported={fileInspector.supported}
1021 inspectorMode={inspectorMode}
1022 onToggleInspector={handleToggleInspector}
1023 onOpenGitInspector={handleOpenGitInspector}
1024 onOpenFilesInspector={handleOpenFilesInspector}
1025 onReturnToThread={props.onReturnToThread}
1026 />
1027 )
1028 }
1029 canOperateThread={canOperateThread}
1030 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
1031 selectedThreadDetailRef={selectedThreadDetailRef}
1032 contentPresentation={contentPresentation}
1033 screenTone={connectionTone(routeConnectionState)}
1034 connectionError={routeConnectionError}
1035 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
1036 feedbackSubmissions={composer.feedbackSubmissions}
1037 onDismissFeedback={composer.dismissFeedback}
1038 selectedThreadFeed={composer.selectedThreadFeed}
1039 pendingHandoff={composer.pendingHandoff}
1040 activityRun={composer.selectedThreadActivityRun}
1041 activeWorkStartedAt={
1042 creationState?.kind === "preparing" ||
1043 (worktreeSetup !== null && setupTurnStartedAt === null)
1044 ? null
1045 : composer.activeWorkStartedAt
1046 }
1047 isCompacting={composer.isCompacting}
1048 runlessWorkActive={composer.runlessWorkActive}
1049 providerSubagentStatus={composer.providerSubagentStatus}
1050 creationState={creationState}
1051 setupWorkingStartedAt={
1052 composer.activeWorkStartedAt !== null &&
1053 worktreeSetupSnapshot !== null &&
1054 composer.selectedThreadFeed.filter(
1055 (entry) => entry.type === "message" && entry.message.role === "user",
1056 ).length <= 1
1057 ? composer.activeWorkStartedAt
1058 : null
1059 }
1060 worktreeSetup={
1061 worktreeSetup
1062 ? {
1063 snapshot: worktreeSetup,
1064 turnStartedAt: setupTurnStartedAt,
1065 working: composer.activeWorkStartedAt !== null,
1066 turnStarted: setupTurnStartedAt !== null,
1067 onCancel: handleCancelWorktreeSetup,
1068 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
1069 }
1070 : null
1071 }
1072 activePendingApproval={requests.activePendingApproval}
1073 activePendingApprovals={requests.activePendingApprovals}
1074 respondingApprovalId={requests.respondingApprovalId}
1075 activePendingUserInput={requests.activePendingUserInput}
1076 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1077 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1078 respondingUserInputId={requests.respondingUserInputId}
1079 connectionStateLabel={routeConnectionState}
1080 threadSyncStatus={selectedThreadDetailState.status}
1081 historyControls={historyControls}
1082 activeThreadBusy={composer.activeThreadBusy}
1083 canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null}
1084 queuedRunEdit={composer.queuedRunEdit}
1085 composerDraftKey={composer.composerDraftKey}
1086 followUpBehavior={composer.followUpBehavior}
1087 canSteerActiveTurn={composer.canSteerActiveTurn}
1088 isSavingQueuedEdit={composer.isSavingQueuedEdit}
1089 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
1090 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
1091 environmentId={selectedThread.environmentId}
1092 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1093 threadCwd={selectedThreadCwd}
1094 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1095 queuedMessages={
1096 selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"
1097 ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]
1098 : composer.selectedThreadQueuedMessages
1099 }
1100 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1101 layoutVariant={layout.variant}
1102 usesAutomaticContentInsets={usesNativeHeaderGlass}
1103 onOpenConnectionEditor={handleOpenConnectionEditor}
1104 onChangeDraftMessage={composer.onChangeDraftMessage}
1105 onPickDraftMedia={composer.onPickDraftMedia}
1106 onPickDraftFiles={composer.onPickDraftFiles}
1107 onNativePasteImages={composer.onNativePasteImages}
1108 onNativePasteText={composer.onNativePasteText}
1109 onRemoveDraftImage={composer.onRemoveDraftImage}
1110 serverConfig={serverConfig}
1111 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1112 onResumeQueue={
1113 composer.queueHeld || composer.resumableRunId !== null ? handleResumeQueue : null
1114 }
1115 onSendMessage={composer.onSendMessage}
1116 onReconnectEnvironment={handleReconnectEnvironment}
1117 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1118 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1119 onRespondToApproval={requests.onRespondToApproval}
1120 onSelectUserInputOption={requests.onSelectUserInputOption}
1121 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1122 onSubmitUserInput={requests.onSubmitUserInput}
1123 onDismissUserInput={requests.onDismissUserInput}
1124 />
1125 </>
1126 </>
1127 );
1128
1129 return (
1130 <>
1131 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1132
1133 {renderThreadRouteBody()}
1134 </>
1135 );
1136}
1137
1138export function FullscreenThreadRouteScreen(
1139 props: StaticScreenProps<{
1140 readonly environmentId: string;
1141 readonly threadId: string;
1142 }>,
1143) {
1144 const navigation = useNavigation();
1145 return (
1146 <InspectorContentScope>
1147 <ThreadRouteScreen
1148 route={props.route}
1149 inspectorPresentation={{ onClose: () => navigation.goBack() }}
1150 />
1151 </InspectorContentScope>
1152 );
1153}