Open History to see the last commit
1import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
2import { enqueueThreadOutboxMessage } from "../../state/thread-outbox";
3import {
4 getComposerDraftSnapshot,
5 clearComposerDraftContent,
6} from "../../state/use-composer-drafts";
7import { useWorktreeSetup } from "./use-worktree-setup";
8import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
9import { ScreenHeader } from "../../components/ScreenHeader";
10import { ScreenHeaderButton } from "../../components/ScreenHeaderButton";
11import type { ScreenHeaderAction } from "../../components/ScreenHeader.types";
12import { useThreadHeaderOptions } from "./useThreadHeaderOptions";
13import {
14 StackActions,
15 useFocusEffect,
16 useNavigation,
17 type StaticScreenProps,
18} from "@react-navigation/native";
19import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
20import * as Option from "effect/Option";
21import {
22 CommandId,
23 MessageId,
24 DEFAULT_SERVER_SETTINGS,
25 EnvironmentId,
26 ThreadId,
27 type ProjectScript,
28} from "@t3tools/contracts";
29import {
30 requestOlderThreadTurns,
31 threadHasOlderTurns,
32} from "@t3tools/client-runtime/state/threads";
33import {
34 projectScriptCwd,
35 projectScriptRuntimeEnv,
36 resolveProjectScripts,
37} from "@t3tools/shared/projectScripts";
38import { Alert, Platform, ScrollView, View } from "react-native";
39import { useSafeAreaInsets } from "react-native-safe-area-context";
40import { useWorkspaceState } from "../../state/workspace";
41import { useEnvironmentShellState } from "../../state/shell";
42import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
43import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
44import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
45import { useEnvironmentQuery } from "../../state/query";
46import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
47import { vcsEnvironment } from "../../state/vcs";
48import { EmptyState } from "../../components/EmptyState";
49import { LoadingScreen } from "../../components/LoadingScreen";
50import { scopedThreadKey } from "../../lib/scopedEntities";
51import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
52import { connectionTone } from "../connection/connectionTone";
53import {
54 useRemoteConnections,
55 useRemoteConnectionStatus,
56 useRemoteEnvironmentRuntime,
57} from "../../state/use-remote-environment-registry";
58import { useKnownTerminalSessions } from "../../state/use-terminal-session";
59import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
60import { useThreadSelection } from "../../state/use-thread-selection";
61import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
62import {
63 buildTerminalMenuSessions,
64 nextOpenTerminalId,
65 resolveProjectScriptTerminalId,
66} from "../terminal/terminalMenu";
67import {
68 resolvePreferredThreadWorktreePath,
69 stagePendingTerminalLaunch,
70} from "../terminal/terminalLaunchContext";
71import { terminalDebugLog } from "../terminal/terminalDebugLog";
72import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
73import { GitOverviewSheet } from "./git/GitOverviewSheet";
74import { useAtomCommand } from "../../state/use-atom-command";
75import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
76import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
77import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
78import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
79import { useThreadComposerState } from "../../state/use-thread-composer-state";
80import { threadEnvironment } from "../../state/threads";
81import { projectThreadContentPresentation } from "./threadContentPresentation";
82import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
83import {
84 useAdaptiveWorkspaceLayout,
85 useAdaptiveWorkspacePaneRole,
86 useRegisterWorkspaceInspector,
87} from "../layout/AdaptiveWorkspaceLayout";
88import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
89import {
90 ThreadInspectorContentStack,
91 type ThreadInspectorMode,
92} from "./thread-inspector-content-stack";
93import { threadRouteIsHydrating } from "./thread-route-hydration";
94
95function ThreadHeader(
96 props: Parameters<typeof useThreadHeaderOptions>[0] & {
97 readonly hasThreadCwd: boolean;
98 readonly hasWorkspaceRoot: boolean;
99 readonly fileInspectorSupported: boolean;
100 readonly inspectorMode: ThreadInspectorMode | null;
101 readonly onToggleInspector: () => void;
102 readonly onOpenGitInspector: () => void;
103 readonly onOpenFilesInspector: () => void;
104 },
105) {
106 const navigation = useNavigation();
107 const { layout, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
108 const { onOpenTerminal } = props.gitControls;
109 const native = useThreadHeaderOptions(props);
110 const androidHeaderActions = useMemo<ReadonlyArray<ScreenHeaderAction>>(() => {
111 const actions: ScreenHeaderAction[] = [];
112 if (props.onReturnToThread) {
113 actions.push({
114 accessibilityLabel: "Return to chat",
115 icon: "chevron.left",
116 onPress: props.onReturnToThread,
117 });
118 }
119 if (props.hasThreadCwd) {
120 const filesVisible = props.inspectorMode === "files" && panes.auxiliaryPaneVisible;
121 actions.push({
122 accessibilityLabel: filesVisible ? "Close files" : "Open files",
123 selected: filesVisible,
124 icon: "folder",
125 onPress: filesVisible ? toggleAuxiliaryPane : props.onOpenFilesInspector,
126 });
127 }
128 if (props.hasWorkspaceRoot) {
129 actions.push({
130 accessibilityLabel: "Open terminal",
131 icon: "terminal",
132 onPress: () => onOpenTerminal(null),
133 });
134 }
135 actions.push({
136 accessibilityLabel: "Open git controls",
137 icon: "point.topleft.down.curvedto.point.bottomright.up",
138 onPress: props.onOpenGitInspector,
139 });
140 return actions;
141 }, [
142 props.inspectorMode,
143 panes.auxiliaryPaneVisible,
144 props.onOpenFilesInspector,
145 onOpenTerminal,
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 { state: workspaceState } = useWorkspaceState();
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 = useEnvironmentShellState(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: workspaceState.isLoadingConnections,
290 connectionState: routeConnectionState,
291 shellStatus: routeEnvironmentShellState.status,
292 shellHasError: Option.isSome(routeEnvironmentShellState.error),
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 // "Load earlier turns" header state for windowed (paginated) thread loads.
340 const loadEarlierTurns = useMemo(() => {
341 if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
342 return null;
343 }
344 return {
345 loading:
346 selectedThreadDetailState.page._tag === "Some" &&
347 selectedThreadDetailState.page.value.loadingOlder,
348 onLoadEarlier: () => {
349 requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
350 },
351 };
352 }, [selectedThread, selectedThreadDetailState]);
353 const { selectedThreadCwd } = useSelectedThreadWorktree();
354 const composer = useThreadComposerState();
355 const gitState = useSelectedThreadGitState();
356 const gitActions = useSelectedThreadGitActions();
357 const requests = useSelectedThreadRequests();
358 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
359 const navigation = useNavigation();
360 const params = props.route.params;
361 const environmentIdRaw = firstRouteParam(params.environmentId);
362 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
363 const threadId = firstRouteParam(params.threadId);
364 const routeThreadIdentity =
365 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
366 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
367 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
368 );
369 const inspectorMode = (() => {
370 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
371 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
372 return null;
373 }
374 return inspectorSelection.mode;
375 }
376 return null;
377 })();
378 useEffect(() => {
379 if (
380 fileInspector.supported &&
381 selectedThreadCwd === null &&
382 inspectorMode === null &&
383 panes.auxiliaryPaneVisible
384 ) {
385 toggleAuxiliaryPane();
386 }
387 }, [
388 fileInspector.supported,
389 inspectorMode,
390 panes.auxiliaryPaneVisible,
391 selectedThreadCwd,
392 toggleAuxiliaryPane,
393 ]);
394
395 useEffect(() => {
396 setInspectorSelection((current) => {
397 if (props.renderInspector === undefined) {
398 if (current === null || current.mode === "route") {
399 return null;
400 }
401 return { ...current, routeThreadIdentity };
402 }
403
404 if (current === null || current.mode === "route") {
405 return { routeThreadIdentity, mode: "route" };
406 }
407
408 return { ...current, routeThreadIdentity };
409 });
410 }, [props.renderInspector, routeThreadIdentity]);
411
412 useFocusEffect(
413 useCallback(() => {
414 return () => {
415 if (props.renderInspector === undefined) {
416 // Inspectors are contextual to this chat destination. Clear the
417 // hidden chat copy after a native push so returning from Files,
418 // Review, or Terminal cannot reserve an empty trailing pane.
419 setInspectorSelection(null);
420 }
421 };
422 }, [props.renderInspector]),
423 );
424 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
425 const routeConnectionState =
426 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
427 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
428 const selectedThreadWithDraftSettings = useMemo(
429 () =>
430 selectedThread
431 ? {
432 ...selectedThread,
433 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
434 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
435 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
436 }
437 : null,
438 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
439 );
440
441 /* ─── Native header theming ──────────────────────────────────────── */
442 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
443 const headerSubtitle = [
444 selectedThreadProject?.title ?? null,
445 selectedEnvironmentConnection?.environmentLabel ?? null,
446 ]
447 .filter(Boolean)
448 .join(" · ");
449 /* ─── Git status for native header trigger ───────────────────────── */
450 const gitStatus = useEnvironmentQuery(
451 selectedThread !== null && selectedThreadCwd !== null
452 ? vcsEnvironment.status({
453 environmentId: selectedThread.environmentId,
454 input: { cwd: selectedThreadCwd },
455 })
456 : null,
457 );
458 const knownTerminalSessions = useKnownTerminalSessions({
459 environmentId: selectedThread?.environmentId ?? null,
460 threadId: selectedThread?.id ?? null,
461 });
462 const terminalMenuSessions = useMemo(
463 () =>
464 buildTerminalMenuSessions({
465 knownSessions: knownTerminalSessions,
466 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
467 }),
468 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
469 );
470 const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
471 const handleReconnectEnvironment = useCallback(() => {
472 if (!environmentId) {
473 return;
474 }
475 onReconnectEnvironment(environmentId);
476 }, [environmentId, onReconnectEnvironment]);
477
478 /* ─── Git action progress (for overlay banner) ──────────────────── */
479 const gitActionProgressTarget = useMemo(
480 () => ({
481 environmentId: selectedThread?.environmentId ?? null,
482 cwd: selectedThreadCwd,
483 }),
484 [selectedThread?.environmentId, selectedThreadCwd],
485 );
486 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
487
488 const handleOpenGitInspector = useCallback(() => {
489 if (!fileInspector.supported) {
490 if (selectedThread === null) {
491 return;
492 }
493 navigation.navigate("GitOverview", {
494 environmentId: String(selectedThread.environmentId),
495 threadId: String(selectedThread.id),
496 });
497 return;
498 }
499 setInspectorSelection({ routeThreadIdentity, mode: "git" });
500 showAuxiliaryPane("inspector");
501 }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
502 const handleOpenFilesInspector = useCallback(() => {
503 if (selectedThread === null || selectedThreadCwd === null) {
504 return;
505 }
506 if (!fileInspector.supported) {
507 navigation.navigate("ThreadFiles", {
508 environmentId: String(selectedThread.environmentId),
509 threadId: String(selectedThread.id),
510 });
511 return;
512 }
513 setInspectorSelection({
514 routeThreadIdentity,
515 mode: props.renderInspector === undefined ? "files" : "route",
516 });
517 showAuxiliaryPane("inspector");
518 }, [
519 fileInspector.supported,
520 navigation,
521 props.renderInspector,
522 routeThreadIdentity,
523 selectedThread,
524 selectedThreadCwd,
525 showAuxiliaryPane,
526 ]);
527 const inspectorToggleActionRef = useRef({
528 inspectorMode,
529 openFilesInspector: handleOpenFilesInspector,
530 toggleAuxiliaryPane,
531 });
532 inspectorToggleActionRef.current = {
533 inspectorMode,
534 openFilesInspector: handleOpenFilesInspector,
535 toggleAuxiliaryPane,
536 };
537 const handleToggleInspector = useCallback(() => {
538 const action = inspectorToggleActionRef.current;
539 if (action.inspectorMode === null) {
540 action.openFilesInspector();
541 return;
542 }
543 action.toggleAuxiliaryPane();
544 }, []);
545 const handleSelectInspectorFile = useCallback(
546 (path: string) => {
547 if (selectedThread === null) {
548 return;
549 }
550 const params = {
551 environmentId: String(selectedThread.environmentId),
552 threadId: String(selectedThread.id),
553 path: path.split("/").filter((segment) => segment.length > 0),
554 };
555 if (fileInspector.supported) {
556 navigation.navigate("ThreadFile", params);
557 return;
558 }
559 navigation.navigate("ThreadFile", params);
560 },
561 [fileInspector.supported, navigation, selectedThread],
562 );
563 // The workspace inspector column spans the full window height. On iOS the
564 // panes bring their own nested native headers (which underlap the status
565 // bar); elsewhere the pane content pads itself below the top inset.
566 const safeAreaInsets = useSafeAreaInsets();
567 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
568 const GitInspector = useCallback(
569 () => (
570 <GitOverviewSheet
571 headerInset={inspectorHeaderInset}
572 presentation="inspector"
573 route={{ params: props.route.params }}
574 />
575 ),
576 [inspectorHeaderInset, props.route.params],
577 );
578 const FilesInspector = useCallback(
579 () =>
580 selectedThread !== null && selectedThreadCwd !== null ? (
581 <ThreadFileNavigatorPane
582 cwd={selectedThreadCwd}
583 environmentId={selectedThread.environmentId}
584 headerInset={inspectorHeaderInset}
585 projectName={selectedThreadProject?.title ?? "Files"}
586 selectedPath={null}
587 onSelectFile={handleSelectInspectorFile}
588 />
589 ) : null,
590 [
591 handleSelectInspectorFile,
592 inspectorHeaderInset,
593 selectedThread,
594 selectedThreadCwd,
595 selectedThreadProject?.title,
596 ],
597 );
598 const RouteInspector = useCallback(
599 () => props.renderInspector?.(inspectorHeaderInset),
600 [inspectorHeaderInset, props.renderInspector],
601 );
602 const renderInspectorStack = useCallback(
603 () =>
604 inspectorMode === null ? null : (
605 <ThreadInspectorContentStack
606 Files={FilesInspector}
607 Git={GitInspector}
608 mode={inspectorMode}
609 Route={props.renderInspector ? RouteInspector : undefined}
610 />
611 ),
612 [FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector],
613 );
614 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
615 // Hand the inspector to the workspace so it renders beside the navigator,
616 // outside this screen's native header — the terminal/git/files toolbar
617 // stays anchored to the chat pane instead of floating above the inspector.
618 useRegisterWorkspaceInspector(activeInspectorRenderer);
619
620 const handleOpenConnectionEditor = useCallback(() => {
621 void navigation.navigate("Connections");
622 }, [navigation]);
623 const handleStopThread = useCallback(() => {
624 if (
625 !selectedThread ||
626 (selectedThread.session?.status !== "running" &&
627 selectedThread.session?.status !== "starting")
628 ) {
629 return;
630 }
631 return interruptThreadTurn({
632 environmentId: selectedThread.environmentId,
633 input: {
634 threadId: selectedThread.id,
635 ...(selectedThread.session.activeTurnId
636 ? { turnId: selectedThread.session.activeTurnId }
637 : {}),
638 },
639 });
640 }, [interruptThreadTurn, selectedThread]);
641
642 const handleOpenTerminal = useCallback(
643 (nextTerminalId?: string | null) => {
644 terminalDebugLog("terminal-menu:open-existing", {
645 terminalId: nextTerminalId ?? null,
646 hasThread: Boolean(selectedThread),
647 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
648 });
649
650 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
651 return;
652 }
653
654 void navigation.navigate("ThreadTerminal", {
655 environmentId: String(selectedThread.environmentId),
656 threadId: String(selectedThread.id),
657 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
658 });
659 },
660 [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
661 );
662
663 const handleOpenNewTerminal = useCallback(() => {
664 terminalDebugLog("terminal-menu:open-new", {
665 hasThread: Boolean(selectedThread),
666 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
667 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
668 });
669
670 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
671 return;
672 }
673
674 const nextId = nextOpenTerminalId({
675 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
676 });
677 void navigation.navigate("ThreadTerminal", {
678 environmentId: String(selectedThread.environmentId),
679 threadId: String(selectedThread.id),
680 terminalId: nextId,
681 });
682 }, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
683
684 const handleRunProjectScript = useCallback(
685 async (script: ProjectScript) => {
686 terminalDebugLog("project-script:press", {
687 scriptId: script.id,
688 command: script.command,
689 hasThread: Boolean(selectedThread),
690 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
691 });
692
693 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
694 terminalDebugLog("project-script:abort", {
695 scriptId: script.id,
696 reason: "no-thread-or-workspace",
697 });
698 return;
699 }
700
701 const targetTerminalId = resolveProjectScriptTerminalId({
702 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
703 hasRunningTerminal: terminalMenuSessions.some(
704 (session) => session.status === "running" || session.status === "starting",
705 ),
706 });
707 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
708 threadShellWorktreePath: selectedThread.worktreePath ?? null,
709 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
710 });
711 const cwd = projectScriptCwd({
712 project: { cwd: selectedThreadProject.workspaceRoot },
713 worktreePath: preferredWorktreePath,
714 });
715 const env = projectScriptRuntimeEnv({
716 project: { cwd: selectedThreadProject.workspaceRoot },
717 worktreePath: preferredWorktreePath,
718 });
719 stagePendingTerminalLaunch({
720 target: {
721 environmentId: selectedThread.environmentId,
722 threadId: selectedThread.id,
723 terminalId: targetTerminalId,
724 },
725 launch: {
726 cwd,
727 worktreePath: preferredWorktreePath,
728 env,
729 initialInput: `${script.command}\r`,
730 },
731 });
732 terminalDebugLog("project-script:staged", {
733 scriptId: script.id,
734 terminalId: targetTerminalId,
735 cwd,
736 worktreePath: preferredWorktreePath,
737 });
738
739 void navigation.navigate("ThreadTerminal", {
740 environmentId: String(selectedThread.environmentId),
741 threadId: String(selectedThread.id),
742 terminalId: targetTerminalId,
743 });
744 },
745 [
746 navigation,
747 selectedThread,
748 selectedThreadDetailWorktreePath,
749 selectedThreadProject,
750 terminalMenuSessions,
751 ],
752 );
753 const threadGitControlProps = {
754 environmentId: environmentIdRaw ?? "",
755 threadId: threadId ?? "",
756 auxiliaryPaneControl:
757 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
758 ? {
759 accessibilityLabel: "Toggle inspector",
760 onPress: handleToggleInspector,
761 }
762 : undefined,
763 onOpenFilesInspector:
764 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
765 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
766 currentBranch: selectedThread?.branch ?? null,
767 gitStatus: gitStatus.data,
768 gitOperationLabel: gitState.gitOperationLabel,
769 canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
770 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
771 projectScripts: selectedThreadProject
772 ? resolveProjectScripts(
773 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
774 selectedThreadProject,
775 )
776 : [],
777 terminalSessions: terminalMenuSessions,
778 showDirectFileControl: layout.usesSplitView,
779 onOpenTerminal: handleOpenTerminal,
780 onOpenNewTerminal: handleOpenNewTerminal,
781 onRunProjectScript: handleRunProjectScript,
782 onPull: gitActions.onPullSelectedThreadBranch,
783 onRunAction: gitActions.onRunSelectedThreadGitAction,
784 };
785 const handleEditFailedCreation = useCallback(async () => {
786 const creation = selectedThreadCreation?.message;
787 if (!creation?.creation || routeThreadIdentity === null) {
788 return;
789 }
790 // The drain restored the prompt and attachments into the recovery draft
791 // the rejected creation owns. Open that draft by id: without it the sheet
792 // mints a fresh empty one and the restored content is unreachable.
793 try {
794 await recoverFailedThreadDraft(creation);
795 } catch (error) {
796 Alert.alert(
797 "Could not restore draft",
798 error instanceof Error ? error.message : String(error),
799 );
800 return;
801 }
802 clearPendingThreadCreationOutcome(routeThreadIdentity);
803 navigation.dispatch(
804 StackActions.replace("NewTaskSheet", {
805 screen: "NewTaskDraft",
806 params: {
807 draftId: restoredNewTaskDraftKey(creation.messageId),
808 environmentId: String(creation.environmentId),
809 projectId: String(creation.creation.projectId),
810 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
811 },
812 }),
813 );
814 }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
815 const worktreeSetup = useWorktreeSetup({
816 environmentId: selectedThread?.environmentId ?? null,
817 threadId: selectedThread?.id ?? null,
818 activities: selectedThreadDetail?.activities ?? [],
819 preparing:
820 selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
821 selectedThreadCreation.outcome == null,
822 turnStarted: selectedThreadDetail?.latestTurn?.startedAt != null,
823 followUpSent:
824 composer.selectedThreadFeed.filter(
825 (entry) => entry.type === "message" && entry.message.role === "user",
826 ).length +
827 composer.selectedThreadQueuedMessages.length >
828 1,
829 });
830 const awaitingBootstrapTurn =
831 worktreeSetup?.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup);
832 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
833 const handleCancelWorktreeSetup = useCallback(() => {
834 if (!selectedThread) return;
835 void cancelWorktreeSetup({
836 environmentId: selectedThread.environmentId,
837 input: { threadId: selectedThread.id },
838 });
839 }, [cancelWorktreeSetup, selectedThread]);
840 const [localResendMessageId, setLocalResendMessageId] = useState<string | null>(null);
841 const handleWorkLocally = useCallback(async () => {
842 if (!selectedThread || !selectedThreadCreation) return;
843 const result = await cancelWorktreeSetup({
844 environmentId: selectedThread.environmentId,
845 input: { threadId: selectedThread.id },
846 });
847 if (result._tag === "Success" && result.value.cancelled) {
848 setLocalResendMessageId(selectedThreadCreation.message.messageId);
849 }
850 }, [cancelWorktreeSetup, selectedThread, selectedThreadCreation]);
851 // Wait for the outbox to restore the cancelled send before queuing its replacement.
852 useEffect(() => {
853 const pending = selectedThreadCreation;
854 if (
855 !localResendMessageId ||
856 pending?.message.messageId !== localResendMessageId ||
857 pending.outcome?.kind !== "failed"
858 )
859 return;
860 setLocalResendMessageId(null);
861 const original = pending.message;
862 if (!original.creation) return;
863 const metadata = makeTurnCommandMetadata();
864 const replacement = {
865 ...original,
866 commandId: CommandId.make(metadata.commandId),
867 messageId: MessageId.make(metadata.messageId),
868 threadId: ThreadId.make(metadata.threadId),
869 createdAt: metadata.createdAt,
870 creation: {
871 ...original.creation,
872 workspaceMode: "local" as const,
873 branch: null,
874 worktreePath: null,
875 },
876 };
877 void enqueueThreadOutboxMessage(replacement)
878 .then(() => {
879 const draftKey = restoredNewTaskDraftKey(original.messageId);
880 const restored = getComposerDraftSnapshot(draftKey);
881 // Leave any edits made during cancellation in their recovery draft.
882 if (
883 restored.text === original.text &&
884 JSON.stringify(restored.context) === JSON.stringify(original.context) &&
885 restored.attachments.length === original.attachments.length &&
886 restored.attachments.every(
887 (attachment, index) => attachment.id === original.attachments[index]?.id,
888 )
889 ) {
890 clearComposerDraftContent(draftKey, { deferAttachmentCleanup: true });
891 }
892 clearPendingThreadCreationOutcome(
893 scopedThreadKey(original.environmentId, original.threadId),
894 );
895 navigation.dispatch(
896 StackActions.replace("Thread", {
897 environmentId: String(replacement.environmentId),
898 threadId: String(replacement.threadId),
899 }),
900 );
901 })
902 .catch((error) =>
903 Alert.alert(
904 "Could not work locally",
905 error instanceof Error ? error.message : String(error),
906 ),
907 );
908 }, [localResendMessageId, navigation, selectedThreadCreation]);
909 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
910 if (selectedThreadCreation === null) {
911 return awaitingBootstrapTurn ? { kind: "preparing", preparingWorktree: true } : null;
912 }
913 if (selectedThreadCreation.outcome?.kind === "failed") {
914 return {
915 kind: "failed",
916 reason: selectedThreadCreation.outcome.reason,
917 onEditTask: handleEditFailedCreation,
918 };
919 }
920 return {
921 kind: "preparing",
922 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
923 };
924 })();
925 if (!environmentId || !threadId) {
926 return <OpeningThreadLoadingScreen />;
927 }
928
929 if (!selectedThread) {
930 return <OpeningThreadLoadingScreen />;
931 }
932
933 // A queued creation renders as ready content: its prompt is the whole
934 // conversation until the server creates the thread. The subscription's
935 // not-found error for that window is expected, not a load failure.
936 const contentPresentation =
937 creationState !== null
938 ? { kind: "ready" as const }
939 : projectThreadContentPresentation({
940 hasDetail: selectedThreadDetail !== null,
941 detailError: Option.getOrNull(selectedThreadDetailState.error),
942 detailDeleted: selectedThreadDetailState.status === "deleted",
943 connectionState: routeConnectionState,
944 });
945 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
946 const renderThreadRouteBody = () => (
947 <>
948 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
949
950 <View
951 className={Platform.OS === "android" ? "flex-1 bg-thread-canvas" : "flex-1 bg-screen"}
952 style={
953 Platform.OS === "android"
954 ? {
955 borderTopLeftRadius: 28,
956 borderTopRightRadius: 28,
957 overflow: "hidden",
958 }
959 : undefined
960 }
961 >
962 <ThreadDetailScreen
963 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
964 contentPresentation={contentPresentation}
965 screenTone={connectionTone(routeConnectionState)}
966 connectionError={routeConnectionError}
967 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
968 feedbackSubmissions={composer.feedbackSubmissions}
969 onDismissFeedback={composer.dismissFeedback}
970 selectedThreadFeed={composer.selectedThreadFeed}
971 activeWorkStartedAt={composer.activeWorkStartedAt}
972 isCompacting={composer.isCompacting}
973 creationState={creationState}
974 setupWorkingStartedAt={
975 composer.activeWorkStartedAt !== null &&
976 selectedThreadDetail?.activities.some(
977 (activity) => activity.kind === "worktree-setup",
978 ) &&
979 composer.selectedThreadFeed.filter(
980 (entry) => entry.type === "message" && entry.message.role === "user",
981 ).length <= 1
982 ? composer.activeWorkStartedAt
983 : null
984 }
985 worktreeSetup={
986 worktreeSetup
987 ? {
988 snapshot: worktreeSetup,
989 turnStartedAt: selectedThreadDetail?.latestTurn?.startedAt ?? null,
990 working: composer.activeWorkStartedAt !== null,
991 turnStarted: selectedThreadDetail?.latestTurn?.startedAt != null,
992 onCancel: handleCancelWorktreeSetup,
993 onWorkLocally:
994 selectedThreadCreation?.outcome == null && selectedThreadCreation
995 ? handleWorkLocally
996 : null,
997 }
998 : null
999 }
1000 activePendingApproval={requests.activePendingApproval}
1001 respondingApprovalId={requests.respondingApprovalId}
1002 activePendingUserInput={requests.activePendingUserInput}
1003 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1004 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1005 respondingUserInputId={requests.respondingUserInputId}
1006 draftMessage={composer.draftMessage}
1007 draftAttachments={composer.draftAttachments}
1008 connectionStateLabel={routeConnectionState}
1009 threadSyncStatus={selectedThreadDetailState.status}
1010 loadEarlier={loadEarlierTurns}
1011 environmentId={selectedThread.environmentId}
1012 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1013 threadCwd={selectedThreadCwd}
1014 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1015 queuedMessages={composer.selectedThreadQueuedMessages}
1016 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1017 layoutVariant={layout.variant}
1018 usesAutomaticContentInsets={usesNativeHeaderGlass}
1019 onOpenConnectionEditor={handleOpenConnectionEditor}
1020 onChangeDraftMessage={composer.onChangeDraftMessage}
1021 onPickDraftMedia={composer.onPickDraftMedia}
1022 onPickDraftFiles={composer.onPickDraftFiles}
1023 onNativePasteImages={composer.onNativePasteImages}
1024 onNativePasteText={composer.onNativePasteText}
1025 onRemoveDraftImage={composer.onRemoveDraftImage}
1026 serverConfig={serverConfig}
1027 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1028 onSendMessage={composer.onSendMessage}
1029 onReconnectEnvironment={handleReconnectEnvironment}
1030 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
1031 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
1032 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1033 onRespondToApproval={requests.onRespondToApproval}
1034 onSelectUserInputOption={requests.onSelectUserInputOption}
1035 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1036 onSubmitUserInput={requests.onSubmitUserInput}
1037 onDismissUserInput={requests.onDismissUserInput}
1038 />
1039 </View>
1040 </>
1041 );
1042
1043 return (
1044 <>
1045 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1046 <ThreadHeader
1047 title={selectedThread.title}
1048 subtitle={headerSubtitle}
1049 headerColor={headerColor}
1050 usesNativeHeaderGlass={usesNativeHeaderGlass}
1051 gitControls={threadGitControlProps}
1052 hasThreadCwd={selectedThreadCwd !== null}
1053 hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
1054 fileInspectorSupported={fileInspector.supported}
1055 inspectorMode={inspectorMode}
1056 onToggleInspector={handleToggleInspector}
1057 onOpenGitInspector={handleOpenGitInspector}
1058 onOpenFilesInspector={handleOpenFilesInspector}
1059 onReturnToThread={props.onReturnToThread}
1060 />
1061
1062 {renderThreadRouteBody()}
1063 </>
1064 );
1065}