Open History to see the last commit
1import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
2import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
3import { useWorktreeSetup } from "./use-worktree-setup";
4import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
5import { ScreenHeader } from "../../components/ScreenHeader";
6import { ScreenHeaderButton } from "../../components/ScreenHeaderButton";
7import type { ScreenHeaderAction } from "../../components/ScreenHeader.types";
8import { useThreadHeaderOptions } from "./useThreadHeaderOptions";
9import {
10 StackActions,
11 useFocusEffect,
12 useNavigation,
13 type StaticScreenProps,
14} from "@react-navigation/native";
15import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
16import * as Option from "effect/Option";
17import {
18 DEFAULT_SERVER_SETTINGS,
19 EnvironmentId,
20 ThreadId,
21 type ProjectScript,
22} from "@t3tools/contracts";
23import {
24 projectScriptCwd,
25 projectScriptRuntimeEnv,
26 resolveProjectScripts,
27} from "@t3tools/shared/projectScripts";
28import { Alert, Platform, ScrollView, View } from "react-native";
29import { useSafeAreaInsets } from "react-native-safe-area-context";
30import { useConnectionsReady } from "../../state/workspace";
31import { useEnvironmentShellReadiness } from "../../state/shell";
32import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
33import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
34import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
35import { useEnvironmentQuery } from "../../state/query";
36import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
37import { vcsEnvironment } from "../../state/vcs";
38import { EmptyState } from "../../components/EmptyState";
39import { LoadingScreen } from "../../components/LoadingScreen";
40import { scopedThreadKey } from "../../lib/scopedEntities";
41import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
42import { connectionTone } from "../connection/connectionTone";
43import {
44 useRemoteConnections,
45 useRemoteConnectionStatus,
46 useRemoteEnvironmentRuntime,
47} from "../../state/use-remote-environment-registry";
48import { useKnownTerminalSessions } from "../../state/use-terminal-session";
49import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
50import { useThreadSelection } from "../../state/use-thread-selection";
51import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
52import {
53 buildTerminalMenuSessions,
54 nextOpenTerminalId,
55 resolveProjectScriptTerminalId,
56} from "../terminal/terminalMenu";
57import {
58 resolvePreferredThreadWorktreePath,
59 stagePendingTerminalLaunch,
60} from "../terminal/terminalLaunchContext";
61import { terminalDebugLog } from "../terminal/terminalDebugLog";
62import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
63import { GitOverviewSheet } from "./git/GitOverviewSheet";
64import { useAtomCommand } from "../../state/use-atom-command";
65import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
66import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
67import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
68import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
69import { useThreadComposerState } from "../../state/use-thread-composer-state";
70import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
71import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
72import { threadEnvironment } from "../../state/threads";
73import { projectThreadContentPresentation } from "./threadContentPresentation";
74import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
75import {
76 useAdaptiveWorkspaceLayout,
77 useAdaptiveWorkspacePaneRole,
78 useRegisterWorkspaceInspector,
79} from "../layout/AdaptiveWorkspaceLayout";
80import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
81import {
82 ThreadInspectorContentStack,
83 type ThreadInspectorMode,
84} from "./thread-inspector-content-stack";
85import { threadRouteIsHydrating } from "./thread-route-hydration";
86
87function ThreadHeader(
88 props: Parameters<typeof useThreadHeaderOptions>[0] & {
89 readonly hasThreadCwd: boolean;
90 readonly hasWorkspaceRoot: boolean;
91 readonly fileInspectorSupported: boolean;
92 readonly inspectorMode: ThreadInspectorMode | null;
93 readonly onToggleInspector: () => void;
94 readonly onOpenGitInspector: () => void;
95 readonly onOpenFilesInspector: () => void;
96 },
97) {
98 const navigation = useNavigation();
99 const { layout, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
100 const { onOpenTerminal, onMergeBack } = props.gitControls;
101 const native = useThreadHeaderOptions(props);
102 const androidHeaderActions = useMemo<ReadonlyArray<ScreenHeaderAction>>(() => {
103 const actions: ScreenHeaderAction[] = [];
104 if (props.onReturnToThread) {
105 actions.push({
106 accessibilityLabel: "Return to chat",
107 icon: "chevron.left",
108 onPress: props.onReturnToThread,
109 });
110 }
111 if (props.hasThreadCwd) {
112 const filesVisible = props.inspectorMode === "files" && panes.auxiliaryPaneVisible;
113 actions.push({
114 accessibilityLabel: filesVisible ? "Close files" : "Open files",
115 selected: filesVisible,
116 icon: "folder",
117 onPress: filesVisible ? toggleAuxiliaryPane : props.onOpenFilesInspector,
118 });
119 }
120 if (props.hasWorkspaceRoot) {
121 actions.push({
122 accessibilityLabel: "Open terminal",
123 icon: "terminal",
124 onPress: () => onOpenTerminal(null),
125 });
126 }
127 actions.push({
128 accessibilityLabel: "Open git controls",
129 icon: "point.topleft.down.curvedto.point.bottomright.up",
130 onPress: props.onOpenGitInspector,
131 });
132 if (onMergeBack) {
133 actions.push({
134 accessibilityLabel: "Merge back to source",
135 icon: "arrow.triangle.merge",
136 onPress: onMergeBack,
137 });
138 }
139 return actions;
140 }, [
141 props.inspectorMode,
142 panes.auxiliaryPaneVisible,
143 props.onOpenFilesInspector,
144 onOpenTerminal,
145 onMergeBack,
146 props.onOpenGitInspector,
147 toggleAuxiliaryPane,
148 props.onReturnToThread,
149 props.hasThreadCwd,
150 props.hasWorkspaceRoot,
151 ]);
152
153 return (
154 <>
155 <ScreenHeader
156 title={props.title}
157 subtitle={props.subtitle}
158 sidebar={native.sidebar}
159 options={native.options}
160 optionsVersion={props.gitControls.projectScripts}
161 trailing={
162 props.fileInspectorSupported && props.hasThreadCwd ? (
163 <ScreenHeaderButton
164 accessibilityLabel={
165 props.inspectorMode !== null && panes.auxiliaryPaneVisible
166 ? "Hide inspector"
167 : "Show inspector"
168 }
169 icon="sidebar.right"
170 selected={props.inspectorMode !== null && panes.auxiliaryPaneVisible}
171 onPress={props.onToggleInspector}
172 />
173 ) : null
174 }
175 onBack={
176 layout.usesSplitView
177 ? undefined
178 : () => {
179 // A deep link or cold start has no previous route; Home is the way out.
180 // Read the history at press time: it changes without re-rendering this screen.
181 if (navigation.canGoBack()) navigation.goBack();
182 else navigation.dispatch(StackActions.replace("Home"));
183 }
184 }
185 actions={androidHeaderActions}
186 hideBottomBorder
187 />
188 {native.fallback}
189 </>
190 );
191}
192
193interface ThreadInspectorSelection {
194 readonly routeThreadIdentity: string | null;
195 readonly mode: ThreadInspectorMode;
196}
197
198function InspectorPaneRoleActivation() {
199 useAdaptiveWorkspacePaneRole("inspector");
200 return null;
201}
202
203function firstRouteParam(value: string | string[] | undefined): string | null {
204 if (Array.isArray(value)) {
205 return value[0] ?? null;
206 }
207
208 return value ?? null;
209}
210
211function OpeningThreadLoadingScreen() {
212 return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
213}
214
215type ThreadRouteScreenRouteProps = StaticScreenProps<{
216 readonly environmentId: string;
217 readonly threadId: string;
218}>;
219
220interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
221 readonly onReturnToThread?: () => void;
222 readonly renderInspector?: (headerInset: number) => ReactNode;
223}
224
225/** Shows recovery only after the target route has reached a terminal unavailable state. */
226function ThreadUnavailableScreen(props: {
227 readonly actionLabel: string;
228 readonly onAction: () => void;
229}) {
230 return (
231 <ScrollView
232 contentInsetAdjustmentBehavior="automatic"
233 contentContainerStyle={{
234 flexGrow: 1,
235 justifyContent: "center",
236 paddingHorizontal: 24,
237 paddingVertical: 32,
238 }}
239 className="bg-screen flex-1"
240 >
241 <EmptyState
242 title="Thread unavailable"
243 detail="This thread is not available in the current mobile snapshot."
244 actionLabel={props.actionLabel}
245 onAction={props.onAction}
246 />
247 </ScrollView>
248 );
249}
250
251export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
252 const connectionsReady = useConnectionsReady();
253 const { connectionState } = useRemoteConnectionStatus();
254 const { selectedThread } = useThreadSelection();
255 const params = props.route.params;
256 const environmentIdRaw = firstRouteParam(params.environmentId);
257 const threadIdRaw = firstRouteParam(params.threadId);
258 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
259 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
260 const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
261 const { onReconnectEnvironment } = useRemoteConnections();
262 const navigation = useNavigation();
263 const routeConnectionState =
264 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
265 const routeThreadKey =
266 environmentId !== null && threadIdRaw !== null
267 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
268 : null;
269 const selectedThreadKey =
270 selectedThread === null
271 ? null
272 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
273 const selectedThreadDetailState = useSelectedThreadDetailState();
274
275 if (environmentId === null || threadIdRaw === null) {
276 return <OpeningThreadLoadingScreen />;
277 }
278
279 // Render the full thread chrome (header, feed, composer) as soon as the
280 // thread SHELL is known — no blocking on message detail. The feed shows a
281 // loading placeholder while messages fetch, the floating pill above the
282 // composer reports loading/syncing, and the composer's connection pill
283 // reports connecting/reconnecting status.
284 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
285 return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
286 }
287
288 const stillHydrating = threadRouteIsHydrating({
289 isLoadingConnections: !connectionsReady,
290 connectionState: routeConnectionState,
291 shellStatus: routeEnvironmentShellState.status,
292 shellHasError: routeEnvironmentShellState.hasError,
293 detailStatus: selectedThreadDetailState.status,
294 detailHasError: Option.isSome(selectedThreadDetailState.error),
295 });
296
297 if (stillHydrating) {
298 return <OpeningThreadLoadingScreen />;
299 }
300
301 return (
302 <ThreadUnavailableScreen
303 actionLabel={
304 routeEnvironmentRuntime === null ? "Manage environments" : "Reconnect environment"
305 }
306 onAction={() => {
307 if (routeEnvironmentRuntime !== null) {
308 onReconnectEnvironment(environmentId);
309 return;
310 }
311 navigation.navigate("SettingsSheet", {
312 screen: "SettingsContent",
313 params: { screen: "SettingsEnvironments" },
314 });
315 }}
316 />
317 );
318}
319
320function ThreadRouteContent(
321 props: ThreadRouteScreenProps & {
322 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
323 },
324) {
325 const { themeVariables } = useAppearancePreferences();
326 const headerColor = themeVariables["--color-header"];
327 const { fileInspector, layout, panes, showAuxiliaryPane, toggleAuxiliaryPane } =
328 useAdaptiveWorkspaceLayout();
329 const { connectionState } = useRemoteConnectionStatus();
330 const { onReconnectEnvironment } = useRemoteConnections();
331 const {
332 selectedThread,
333 selectedThreadCreation,
334 selectedThreadProject,
335 selectedEnvironmentConnection,
336 } = useThreadSelection();
337 const selectedThreadDetailState = props.selectedThreadDetailState;
338 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
339 const { selectedThreadCwd } = useSelectedThreadWorktree();
340 const composer = useThreadComposerState();
341 const gitState = useSelectedThreadGitState();
342 const gitActions = useSelectedThreadGitActions();
343 const requests = useSelectedThreadRequests();
344 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
345 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
346 label: "load earlier thread history",
347 reportFailure: false,
348 });
349 const historyControls = useMemo(() => {
350 const history = selectedThreadDetailState.history;
351 if (!selectedThread) {
352 return undefined;
353 }
354 if (!history.hasMoreHistory && history.error === null) {
355 return undefined;
356 }
357 return {
358 hasMoreHistory: history.hasMoreHistory,
359 loading: history.loading,
360 error: history.error,
361 onLoadEarlier: () => {
362 void loadEarlierHistory({
363 environmentId: selectedThread.environmentId,
364 input: { threadId: selectedThread.id },
365 });
366 },
367 };
368 }, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]);
369 const navigation = useNavigation();
370 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
371 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
372 const mergeBackRun =
373 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
374 const mergeBackBusyRef = useRef(false);
375 const handleMergeBack = useCallback(async () => {
376 if (
377 mergeBackBusyRef.current ||
378 !selectedThread ||
379 mergeBackTargetThreadId === null ||
380 mergeBackRun === null
381 ) {
382 return;
383 }
384 mergeBackBusyRef.current = true;
385 try {
386 const result = await mergeBack({
387 environmentId: selectedThread.environmentId,
388 input: {
389 sourceThreadId: selectedThread.id,
390 targetThreadId: mergeBackTargetThreadId,
391 runId: mergeBackRun.id,
392 creationSource: "mobile",
393 },
394 });
395 if (result._tag !== "Success") return;
396 navigation.navigate("Thread", {
397 environmentId: selectedThread.environmentId,
398 threadId: mergeBackTargetThreadId,
399 });
400 } finally {
401 mergeBackBusyRef.current = false;
402 }
403 }, [mergeBack, mergeBackRun, mergeBackTargetThreadId, navigation, selectedThread]);
404 const params = props.route.params;
405 const environmentIdRaw = firstRouteParam(params.environmentId);
406 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
407 const threadId = firstRouteParam(params.threadId);
408 const routeThreadIdentity =
409 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
410 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
411 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
412 );
413 const inspectorMode = (() => {
414 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
415 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
416 return null;
417 }
418 return inspectorSelection.mode;
419 }
420 return null;
421 })();
422 useEffect(() => {
423 if (
424 fileInspector.supported &&
425 selectedThreadCwd === null &&
426 inspectorMode === null &&
427 panes.auxiliaryPaneVisible
428 ) {
429 toggleAuxiliaryPane();
430 }
431 }, [
432 fileInspector.supported,
433 inspectorMode,
434 panes.auxiliaryPaneVisible,
435 selectedThreadCwd,
436 toggleAuxiliaryPane,
437 ]);
438
439 useEffect(() => {
440 setInspectorSelection((current) => {
441 if (props.renderInspector === undefined) {
442 if (current === null || current.mode === "route") {
443 return null;
444 }
445 return { ...current, routeThreadIdentity };
446 }
447
448 if (current === null || current.mode === "route") {
449 return { routeThreadIdentity, mode: "route" };
450 }
451
452 return { ...current, routeThreadIdentity };
453 });
454 }, [props.renderInspector, routeThreadIdentity]);
455
456 useFocusEffect(
457 useCallback(() => {
458 return () => {
459 if (props.renderInspector === undefined) {
460 // Inspectors are contextual to this chat destination. Clear the
461 // hidden chat copy after a native push so returning from Files,
462 // Review, or Terminal cannot reserve an empty trailing pane.
463 setInspectorSelection(null);
464 }
465 };
466 }, [props.renderInspector]),
467 );
468 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
469 const routeConnectionState =
470 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
471 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
472 const selectedThreadWithDraftSettings = useMemo(
473 () =>
474 selectedThread
475 ? {
476 ...selectedThread,
477 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
478 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
479 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
480 }
481 : null,
482 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
483 );
484
485 /* ─── Native header theming ──────────────────────────────────────── */
486 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
487 const headerSubtitle = [
488 selectedThreadProject?.title ?? null,
489 selectedEnvironmentConnection?.environmentLabel ?? null,
490 ]
491 .filter(Boolean)
492 .join(" · ");
493 /* ─── Git status for native header trigger ───────────────────────── */
494 const gitStatus = useEnvironmentQuery(
495 selectedThread !== null && selectedThreadCwd !== null
496 ? vcsEnvironment.status({
497 environmentId: selectedThread.environmentId,
498 input: { cwd: selectedThreadCwd },
499 })
500 : null,
501 );
502 const knownTerminalSessions = useKnownTerminalSessions({
503 environmentId: selectedThread?.environmentId ?? null,
504 threadId: selectedThread?.id ?? null,
505 });
506 const terminalMenuSessions = useMemo(
507 () =>
508 buildTerminalMenuSessions({
509 knownSessions: knownTerminalSessions,
510 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
511 }),
512 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
513 );
514 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
515 const handleReconnectEnvironment = useCallback(() => {
516 if (!environmentId) {
517 return;
518 }
519 onReconnectEnvironment(environmentId);
520 }, [environmentId, onReconnectEnvironment]);
521
522 /* ─── Git action progress (for overlay banner) ──────────────────── */
523 const gitActionProgressTarget = useMemo(
524 () => ({
525 environmentId: selectedThread?.environmentId ?? null,
526 cwd: selectedThreadCwd,
527 }),
528 [selectedThread?.environmentId, selectedThreadCwd],
529 );
530 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
531
532 const handleOpenGitInspector = useCallback(() => {
533 if (!fileInspector.supported) {
534 if (selectedThread === null) {
535 return;
536 }
537 navigation.navigate("GitOverview", {
538 environmentId: String(selectedThread.environmentId),
539 threadId: String(selectedThread.id),
540 });
541 return;
542 }
543 setInspectorSelection({ routeThreadIdentity, mode: "git" });
544 showAuxiliaryPane("inspector");
545 }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
546 const handleOpenFilesInspector = useCallback(() => {
547 if (selectedThread === null || selectedThreadCwd === null) {
548 return;
549 }
550 if (!fileInspector.supported) {
551 navigation.navigate("ThreadFiles", {
552 environmentId: String(selectedThread.environmentId),
553 threadId: String(selectedThread.id),
554 });
555 return;
556 }
557 setInspectorSelection({
558 routeThreadIdentity,
559 mode: props.renderInspector === undefined ? "files" : "route",
560 });
561 showAuxiliaryPane("inspector");
562 }, [
563 fileInspector.supported,
564 navigation,
565 props.renderInspector,
566 routeThreadIdentity,
567 selectedThread,
568 selectedThreadCwd,
569 showAuxiliaryPane,
570 ]);
571 const inspectorToggleActionRef = useRef({
572 inspectorMode,
573 openFilesInspector: handleOpenFilesInspector,
574 toggleAuxiliaryPane,
575 });
576 inspectorToggleActionRef.current = {
577 inspectorMode,
578 openFilesInspector: handleOpenFilesInspector,
579 toggleAuxiliaryPane,
580 };
581 const handleToggleInspector = useCallback(() => {
582 const action = inspectorToggleActionRef.current;
583 if (action.inspectorMode === null) {
584 action.openFilesInspector();
585 return;
586 }
587 action.toggleAuxiliaryPane();
588 }, []);
589 const handleSelectInspectorFile = useCallback(
590 (path: string) => {
591 if (selectedThread === null) {
592 return;
593 }
594 const params = {
595 environmentId: String(selectedThread.environmentId),
596 threadId: String(selectedThread.id),
597 path: path.split("/").filter((segment) => segment.length > 0),
598 };
599 if (fileInspector.supported) {
600 navigation.navigate("ThreadFile", params);
601 return;
602 }
603 navigation.navigate("ThreadFile", params);
604 },
605 [fileInspector.supported, navigation, selectedThread],
606 );
607 // The workspace inspector column spans the full window height. On iOS the
608 // panes bring their own nested native headers (which underlap the status
609 // bar); elsewhere the pane content pads itself below the top inset.
610 const safeAreaInsets = useSafeAreaInsets();
611 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
612 const GitInspector = useCallback(
613 () => (
614 <GitOverviewSheet
615 headerInset={inspectorHeaderInset}
616 presentation="inspector"
617 route={{ params: props.route.params }}
618 />
619 ),
620 [inspectorHeaderInset, props.route.params],
621 );
622 const FilesInspector = useCallback(
623 () =>
624 selectedThread !== null && selectedThreadCwd !== null ? (
625 <ThreadFileNavigatorPane
626 cwd={selectedThreadCwd}
627 environmentId={selectedThread.environmentId}
628 headerInset={inspectorHeaderInset}
629 projectName={selectedThreadProject?.title ?? "Files"}
630 selectedPath={null}
631 onSelectFile={handleSelectInspectorFile}
632 />
633 ) : null,
634 [
635 handleSelectInspectorFile,
636 inspectorHeaderInset,
637 selectedThread,
638 selectedThreadCwd,
639 selectedThreadProject?.title,
640 ],
641 );
642 const RouteInspector = useCallback(
643 () => props.renderInspector?.(inspectorHeaderInset),
644 [inspectorHeaderInset, props.renderInspector],
645 );
646 const renderInspectorStack = useCallback(
647 () =>
648 inspectorMode === null ? null : (
649 <ThreadInspectorContentStack
650 Files={FilesInspector}
651 Git={GitInspector}
652 mode={inspectorMode}
653 Route={props.renderInspector ? RouteInspector : undefined}
654 />
655 ),
656 [FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector],
657 );
658 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
659 // Hand the inspector to the workspace so it renders beside the navigator,
660 // outside this screen's native header — the terminal/git/files toolbar
661 // stays anchored to the chat pane instead of floating above the inspector.
662 useRegisterWorkspaceInspector(activeInspectorRenderer);
663
664 const handleOpenConnectionEditor = useCallback(() => {
665 void navigation.navigate("Connections");
666 }, [navigation]);
667 const handleStopThread = useCallback(() => {
668 if (!selectedThread || composer.interruptibleRunId === null) {
669 return;
670 }
671 return interruptThreadTurn({
672 environmentId: selectedThread.environmentId,
673 input: {
674 threadId: selectedThread.id,
675 runId: composer.interruptibleRunId,
676 },
677 });
678 }, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
679
680 const handleOpenTerminal = useCallback(
681 (nextTerminalId?: string | null) => {
682 terminalDebugLog("terminal-menu:open-existing", {
683 terminalId: nextTerminalId ?? null,
684 hasThread: Boolean(selectedThread),
685 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
686 });
687
688 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
689 return;
690 }
691
692 void navigation.navigate("ThreadTerminal", {
693 environmentId: String(selectedThread.environmentId),
694 threadId: String(selectedThread.id),
695 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
696 });
697 },
698 [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
699 );
700
701 const handleOpenNewTerminal = useCallback(() => {
702 terminalDebugLog("terminal-menu:open-new", {
703 hasThread: Boolean(selectedThread),
704 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
705 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
706 });
707
708 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
709 return;
710 }
711
712 const nextId = nextOpenTerminalId({
713 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
714 });
715 void navigation.navigate("ThreadTerminal", {
716 environmentId: String(selectedThread.environmentId),
717 threadId: String(selectedThread.id),
718 terminalId: nextId,
719 });
720 }, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
721
722 const handleRunProjectScript = useCallback(
723 async (script: ProjectScript) => {
724 terminalDebugLog("project-script:press", {
725 scriptId: script.id,
726 command: script.command,
727 hasThread: Boolean(selectedThread),
728 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
729 });
730
731 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
732 terminalDebugLog("project-script:abort", {
733 scriptId: script.id,
734 reason: "no-thread-or-workspace",
735 });
736 return;
737 }
738
739 const targetTerminalId = resolveProjectScriptTerminalId({
740 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
741 hasRunningTerminal: terminalMenuSessions.some(
742 (session) => session.status === "running" || session.status === "starting",
743 ),
744 });
745 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
746 threadShellWorktreePath: selectedThread.worktreePath ?? null,
747 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
748 });
749 const cwd = projectScriptCwd({
750 project: { cwd: selectedThreadProject.workspaceRoot },
751 worktreePath: preferredWorktreePath,
752 });
753 const env = projectScriptRuntimeEnv({
754 project: { cwd: selectedThreadProject.workspaceRoot },
755 worktreePath: preferredWorktreePath,
756 });
757 stagePendingTerminalLaunch({
758 target: {
759 environmentId: selectedThread.environmentId,
760 threadId: selectedThread.id,
761 terminalId: targetTerminalId,
762 },
763 launch: {
764 cwd,
765 worktreePath: preferredWorktreePath,
766 env,
767 initialInput: `${script.command}\r`,
768 },
769 });
770 terminalDebugLog("project-script:staged", {
771 scriptId: script.id,
772 terminalId: targetTerminalId,
773 cwd,
774 worktreePath: preferredWorktreePath,
775 });
776
777 void navigation.navigate("ThreadTerminal", {
778 environmentId: String(selectedThread.environmentId),
779 threadId: String(selectedThread.id),
780 terminalId: targetTerminalId,
781 });
782 },
783 [
784 navigation,
785 selectedThread,
786 selectedThreadDetailWorktreePath,
787 selectedThreadProject,
788 terminalMenuSessions,
789 ],
790 );
791 const threadGitControlProps = {
792 environmentId: environmentIdRaw ?? "",
793 threadId: threadId ?? "",
794 auxiliaryPaneControl:
795 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
796 ? {
797 accessibilityLabel: "Toggle inspector",
798 onPress: handleToggleInspector,
799 }
800 : undefined,
801 onOpenFilesInspector:
802 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
803 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
804 onMergeBack:
805 mergeBackTargetThreadId !== null && mergeBackRun !== null
806 ? () => void handleMergeBack()
807 : undefined,
808 currentBranch: selectedThread?.branch ?? null,
809 gitStatus: gitStatus.data,
810 gitOperationLabel: gitState.gitOperationLabel,
811 canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
812 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
813 projectScripts: selectedThreadProject
814 ? resolveProjectScripts(
815 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
816 selectedThreadProject,
817 )
818 : [],
819 terminalSessions: terminalMenuSessions,
820 showDirectFileControl: layout.usesSplitView,
821 onOpenTerminal: handleOpenTerminal,
822 onOpenNewTerminal: handleOpenNewTerminal,
823 onRunProjectScript: handleRunProjectScript,
824 onPull: gitActions.onPullSelectedThreadBranch,
825 onRunAction: gitActions.onRunSelectedThreadGitAction,
826 };
827 const handleEditFailedCreation = useCallback(async () => {
828 const creation = selectedThreadCreation?.message;
829 if (!creation?.creation || routeThreadIdentity === null) {
830 return;
831 }
832 // The drain restored the prompt and attachments into the recovery draft
833 // the rejected creation owns. Open that draft by id: without it the sheet
834 // mints a fresh empty one and the restored content is unreachable.
835 try {
836 await recoverFailedThreadDraft(creation);
837 } catch (error) {
838 Alert.alert(
839 "Could not restore draft",
840 error instanceof Error ? error.message : String(error),
841 );
842 return;
843 }
844 clearPendingThreadCreationOutcome(routeThreadIdentity);
845 navigation.dispatch(
846 StackActions.replace("NewTaskSheet", {
847 screen: "NewTaskDraft",
848 params: {
849 draftId: restoredNewTaskDraftKey(creation.messageId),
850 environmentId: String(creation.environmentId),
851 projectId: String(creation.creation.projectId),
852 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
853 },
854 }),
855 );
856 }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
857 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
858 const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({
859 environmentId: selectedThread?.environmentId ?? null,
860 threadId: selectedThread?.id ?? null,
861 preparing:
862 composer.selectedThreadActivityRun?.status === "preparing" ||
863 selectedThread?.runtime?.status === "preparing" ||
864 selectedThread?.worktreePath != null ||
865 (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
866 selectedThreadCreation.outcome == null),
867 turnStarted: setupTurnStartedAt !== null,
868 followUpSent:
869 composer.selectedThreadFeed.filter(
870 (entry) => entry.type === "message" && entry.message.role === "user",
871 ).length +
872 composer.selectedThreadQueueCount >
873 1,
874 });
875 const awaitingBootstrapTurn =
876 worktreeSetup !== null
877 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
878 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
879 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
880 const handleCancelWorktreeSetup = useCallback(() => {
881 if (!selectedThread) return;
882 void cancelWorktreeSetup({
883 environmentId: selectedThread.environmentId,
884 input: { threadId: selectedThread.id },
885 });
886 }, [cancelWorktreeSetup, selectedThread]);
887 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
888 const localResendBusy = useRef(false);
889 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
890 const handleWorkLocally = useCallback(async () => {
891 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
892 return;
893 localResendBusy.current = true;
894 try {
895 const result = await cancelWorktreeSetup({
896 environmentId: selectedThread.environmentId,
897 input: { threadId: selectedThread.id },
898 });
899 if (result._tag !== "Success" || !result.value.cancelled) return;
900 // V2 accepts the launch before setup runs, so cancellation never rejects
901 // the original outbox delivery. Reuse the server-owned prompt and uploads.
902 const metadata = makeTurnCommandMetadata();
903 const launched = await startLocalThread({
904 environmentId: selectedThread.environmentId,
905 input: buildProjectThreadStartTurnInput({
906 ...metadata,
907 projectId: selectedThread.projectId,
908 projectCwd: selectedThreadProject.workspaceRoot,
909 text: setupMessage.text,
910 ...(setupMessage.context ? { context: setupMessage.context } : {}),
911 uploadedAttachments: setupMessage.attachments,
912 modelSelection: selectedThread.modelSelection,
913 runtimeMode: selectedThread.runtimeMode,
914 interactionMode: selectedThread.interactionMode,
915 workspaceMode: "local",
916 branch: null,
917 worktreePath: null,
918 startFromOrigin: false,
919 worktreeBranchName: "",
920 }),
921 });
922 if (launched._tag !== "Success") return;
923 navigation.dispatch(
924 StackActions.replace("Thread", {
925 environmentId: String(selectedThread.environmentId),
926 threadId: metadata.threadId,
927 }),
928 );
929 } finally {
930 localResendBusy.current = false;
931 }
932 }, [
933 cancelWorktreeSetup,
934 navigation,
935 selectedThread,
936 selectedThreadProject,
937 setupMessage,
938 startLocalThread,
939 ]);
940 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
941 if (selectedThreadCreation === null) {
942 return awaitingBootstrapTurn ? { kind: "preparing", preparingWorktree: true } : null;
943 }
944 if (selectedThreadCreation.outcome?.kind === "failed") {
945 return {
946 kind: "failed",
947 reason: selectedThreadCreation.outcome.reason,
948 onEditTask: handleEditFailedCreation,
949 };
950 }
951 return {
952 kind: "preparing",
953 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
954 };
955 })();
956 if (!environmentId || !threadId) {
957 return <OpeningThreadLoadingScreen />;
958 }
959
960 if (!selectedThread) {
961 return <OpeningThreadLoadingScreen />;
962 }
963
964 // A queued creation renders as ready content: its prompt is the whole
965 // conversation until the server creates the thread. The subscription's
966 // not-found error for that window is expected, not a load failure.
967 const contentPresentation =
968 creationState !== null
969 ? { kind: "ready" as const }
970 : projectThreadContentPresentation({
971 hasDetail: selectedThreadDetail !== null,
972 detailError: Option.getOrNull(selectedThreadDetailState.error),
973 detailDeleted: selectedThreadDetailState.status === "deleted",
974 connectionState: routeConnectionState,
975 });
976 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
977 const renderThreadRouteBody = () => (
978 <>
979 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
980
981 <View
982 className={Platform.OS === "android" ? "flex-1 bg-thread-canvas" : "flex-1 bg-screen"}
983 style={
984 Platform.OS === "android"
985 ? {
986 borderTopLeftRadius: 28,
987 borderTopRightRadius: 28,
988 overflow: "hidden",
989 }
990 : undefined
991 }
992 >
993 <ThreadDetailScreen
994 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
995 contentPresentation={contentPresentation}
996 screenTone={connectionTone(routeConnectionState)}
997 connectionError={routeConnectionError}
998 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
999 feedbackSubmissions={composer.feedbackSubmissions}
1000 onDismissFeedback={composer.dismissFeedback}
1001 selectedThreadFeed={composer.selectedThreadFeed}
1002 activityRun={composer.selectedThreadActivityRun}
1003 activeWorkStartedAt={
1004 creationState?.kind === "preparing" ||
1005 (worktreeSetup !== null && setupTurnStartedAt === null)
1006 ? null
1007 : composer.activeWorkStartedAt
1008 }
1009 isCompacting={composer.isCompacting}
1010 creationState={creationState}
1011 setupWorkingStartedAt={
1012 composer.activeWorkStartedAt !== null &&
1013 worktreeSetupSnapshot !== null &&
1014 composer.selectedThreadFeed.filter(
1015 (entry) => entry.type === "message" && entry.message.role === "user",
1016 ).length <= 1
1017 ? composer.activeWorkStartedAt
1018 : null
1019 }
1020 worktreeSetup={
1021 worktreeSetup
1022 ? {
1023 snapshot: worktreeSetup,
1024 turnStartedAt: setupTurnStartedAt,
1025 working: composer.activeWorkStartedAt !== null,
1026 turnStarted: setupTurnStartedAt !== null,
1027 onCancel: handleCancelWorktreeSetup,
1028 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
1029 }
1030 : null
1031 }
1032 activePendingApproval={requests.activePendingApproval}
1033 respondingApprovalId={requests.respondingApprovalId}
1034 activePendingUserInput={requests.activePendingUserInput}
1035 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1036 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1037 respondingUserInputId={requests.respondingUserInputId}
1038 draftMessage={composer.draftMessage}
1039 draftAttachments={composer.draftAttachments}
1040 connectionStateLabel={routeConnectionState}
1041 threadSyncStatus={selectedThreadDetailState.status}
1042 historyControls={historyControls}
1043 activeThreadBusy={composer.activeThreadBusy}
1044 canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null}
1045 queuedRunEdit={composer.queuedRunEdit}
1046 composerDraftKey={composer.composerDraftKey}
1047 followUpBehavior={composer.followUpBehavior}
1048 canSteerActiveTurn={composer.canSteerActiveTurn}
1049 isSavingQueuedEdit={composer.isSavingQueuedEdit}
1050 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
1051 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
1052 environmentId={selectedThread.environmentId}
1053 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1054 threadCwd={selectedThreadCwd}
1055 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1056 queuedMessages={composer.selectedThreadQueuedMessages}
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 onSendMessage={composer.onSendMessage}
1070 onReconnectEnvironment={handleReconnectEnvironment}
1071 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1072 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
1073 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
1074 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1075 onRespondToApproval={requests.onRespondToApproval}
1076 onSelectUserInputOption={requests.onSelectUserInputOption}
1077 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1078 onSubmitUserInput={requests.onSubmitUserInput}
1079 onDismissUserInput={requests.onDismissUserInput}
1080 />
1081 </View>
1082 </>
1083 );
1084
1085 return (
1086 <>
1087 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1088 <ThreadHeader
1089 title={selectedThread.title}
1090 subtitle={headerSubtitle}
1091 headerColor={headerColor}
1092 usesNativeHeaderGlass={usesNativeHeaderGlass}
1093 gitControls={threadGitControlProps}
1094 hasThreadCwd={selectedThreadCwd !== null}
1095 hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
1096 fileInspectorSupported={fileInspector.supported}
1097 inspectorMode={inspectorMode}
1098 onToggleInspector={handleToggleInspector}
1099 onOpenGitInspector={handleOpenGitInspector}
1100 onOpenFilesInspector={handleOpenFilesInspector}
1101 onReturnToThread={props.onReturnToThread}
1102 />
1103
1104 {renderThreadRouteBody()}
1105 </>
1106 );
1107}