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