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