Open History to see the last commit
1import { NativeStackScreenOptions } from "../../native/StackHeader";
2import {
3 StackActions,
4 useFocusEffect,
5 useNavigation,
6 type StaticScreenProps,
7} from "@react-navigation/native";
8import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
9import * as Option from "effect/Option";
10import {
11 DEFAULT_SERVER_SETTINGS,
12 EnvironmentId,
13 ThreadId,
14 type ProjectScript,
15} from "@t3tools/contracts";
16import {
17 requestOlderThreadTurns,
18 threadHasOlderTurns,
19} from "@t3tools/client-runtime/state/threads";
20import {
21 projectScriptCwd,
22 projectScriptRuntimeEnv,
23 resolveProjectScripts,
24} from "@t3tools/shared/projectScripts";
25import { Alert, Platform, ScrollView, View } from "react-native";
26import { useSafeAreaInsets } from "react-native-safe-area-context";
27import { useWorkspaceState } from "../../state/workspace";
28import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
29import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
30import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
31import { useEnvironmentQuery } from "../../state/query";
32import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
33import { vcsEnvironment } from "../../state/vcs";
34
35import { EmptyState } from "../../components/EmptyState";
36import {
37 AndroidScreenHeader,
38 type AndroidHeaderAction,
39} from "../../components/AndroidScreenHeader";
40import { LoadingScreen } from "../../components/LoadingScreen";
41import { scopedThreadKey } from "../../lib/scopedEntities";
42import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
43import { connectionTone } from "../connection/connectionTone";
44
45import {
46 useRemoteConnections,
47 useRemoteConnectionStatus,
48 useRemoteEnvironmentRuntime,
49} from "../../state/use-remote-environment-registry";
50import { useKnownTerminalSessions } from "../../state/use-terminal-session";
51import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
52import { useThreadSelection } from "../../state/use-thread-selection";
53import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
54import {
55 buildTerminalMenuSessions,
56 nextOpenTerminalId,
57 resolveProjectScriptTerminalId,
58} from "../terminal/terminalMenu";
59import {
60 resolvePreferredThreadWorktreePath,
61 stagePendingTerminalLaunch,
62} from "../terminal/terminalLaunchContext";
63import { terminalDebugLog } from "../terminal/terminalDebugLog";
64import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
65import {
66 ThreadGitControls,
67 useThreadGitCenterHeaderItems,
68 useThreadGitRightHeaderItems,
69} from "./ThreadGitControls";
70import { GitOverviewSheet } from "./git/GitOverviewSheet";
71import { useAtomCommand } from "../../state/use-atom-command";
72import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
73import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
74import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
75import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
76import { useThreadComposerState } from "../../state/use-thread-composer-state";
77import { threadEnvironment } from "../../state/threads";
78import { projectThreadContentPresentation } from "./threadContentPresentation";
79import {
80 useAdaptiveWorkspaceLayout,
81 useAdaptiveWorkspacePaneRole,
82 useRegisterWorkspaceInspector,
83} from "../layout/AdaptiveWorkspaceLayout";
84import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
85import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
86import {
87 ThreadInspectorContentStack,
88 type ThreadInspectorMode,
89} from "./thread-inspector-content-stack";
90
91interface ThreadInspectorSelection {
92 readonly routeThreadIdentity: string | null;
93 readonly mode: ThreadInspectorMode;
94}
95
96type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;
97
98function InspectorPaneRoleActivation() {
99 useAdaptiveWorkspacePaneRole("inspector");
100 return null;
101}
102
103function firstRouteParam(value: string | string[] | undefined): string | null {
104 if (Array.isArray(value)) {
105 return value[0] ?? null;
106 }
107
108 return value ?? null;
109}
110
111function OpeningThreadLoadingScreen() {
112 return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
113}
114
115type ThreadRouteScreenRouteProps = StaticScreenProps<{
116 readonly environmentId: string;
117 readonly threadId: string;
118}>;
119
120interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
121 readonly onReturnToThread?: () => void;
122 readonly renderInspector?: (headerInset: number) => ReactNode;
123}
124
125function ThreadUnavailableScreen() {
126 return (
127 <ScrollView
128 contentInsetAdjustmentBehavior="automatic"
129 contentContainerStyle={{
130 flexGrow: 1,
131 justifyContent: "center",
132 paddingHorizontal: 24,
133 paddingVertical: 32,
134 }}
135 className="bg-screen flex-1"
136 >
137 <EmptyState
138 title="Thread unavailable"
139 detail="This thread is not available in the current mobile snapshot."
140 />
141 </ScrollView>
142 );
143}
144
145export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
146 const { state: workspaceState } = useWorkspaceState();
147 const { connectionState } = useRemoteConnectionStatus();
148 const { selectedThread } = useThreadSelection();
149 const params = props.route.params;
150 const environmentIdRaw = firstRouteParam(params.environmentId);
151 const threadIdRaw = firstRouteParam(params.threadId);
152 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
153 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
154 const routeConnectionState =
155 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
156 const routeThreadKey =
157 environmentId !== null && threadIdRaw !== null
158 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
159 : null;
160 const selectedThreadKey =
161 selectedThread === null
162 ? null
163 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
164 const selectedThreadDetailState = useSelectedThreadDetailState();
165
166 if (environmentId === null || threadIdRaw === null) {
167 return <OpeningThreadLoadingScreen />;
168 }
169
170 // Render the full thread chrome (header, feed, composer) as soon as the
171 // thread SHELL is known — no blocking on message detail. The feed shows a
172 // loading placeholder while messages fetch, the floating pill above the
173 // composer reports loading/syncing, and the composer's connection pill
174 // reports connecting/reconnecting status.
175 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
176 return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
177 }
178
179 const stillHydrating =
180 workspaceState.isLoadingConnections ||
181 routeConnectionState === "connecting" ||
182 routeConnectionState === "reconnecting";
183
184 if (stillHydrating) {
185 return <OpeningThreadLoadingScreen />;
186 }
187
188 return <ThreadUnavailableScreen />;
189}
190
191function ThreadRouteContent(
192 props: ThreadRouteScreenProps & {
193 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
194 },
195) {
196 const {
197 fileInspector,
198 layout,
199 panes,
200 showAuxiliaryPane,
201 toggleAuxiliaryPane,
202 togglePrimarySidebar,
203 } = useAdaptiveWorkspaceLayout();
204 const { connectionState } = useRemoteConnectionStatus();
205 const { onReconnectEnvironment } = useRemoteConnections();
206 const {
207 selectedThread,
208 selectedThreadCreation,
209 selectedThreadProject,
210 selectedEnvironmentConnection,
211 } = useThreadSelection();
212 const selectedThreadDetailState = props.selectedThreadDetailState;
213 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
214 // "Load earlier turns" header state for windowed (paginated) thread loads.
215 const loadEarlierTurns = useMemo(() => {
216 if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
217 return null;
218 }
219 return {
220 loading:
221 selectedThreadDetailState.page._tag === "Some" &&
222 selectedThreadDetailState.page.value.loadingOlder,
223 onLoadEarlier: () => {
224 requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
225 },
226 };
227 }, [selectedThread, selectedThreadDetailState]);
228 const { selectedThreadCwd } = useSelectedThreadWorktree();
229 const composer = useThreadComposerState();
230 const gitState = useSelectedThreadGitState();
231 const gitActions = useSelectedThreadGitActions();
232 const requests = useSelectedThreadRequests();
233 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
234 const navigation = useNavigation();
235 const params = props.route.params;
236 const environmentIdRaw = firstRouteParam(params.environmentId);
237 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
238 const threadId = firstRouteParam(params.threadId);
239 const routeThreadIdentity =
240 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
241 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
242 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
243 );
244 const inspectorMode = (() => {
245 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
246 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
247 return null;
248 }
249 return inspectorSelection.mode;
250 }
251 return null;
252 })();
253 useEffect(() => {
254 if (
255 fileInspector.supported &&
256 selectedThreadCwd === null &&
257 inspectorMode === null &&
258 panes.auxiliaryPaneVisible
259 ) {
260 toggleAuxiliaryPane();
261 }
262 }, [
263 fileInspector.supported,
264 inspectorMode,
265 panes.auxiliaryPaneVisible,
266 selectedThreadCwd,
267 toggleAuxiliaryPane,
268 ]);
269
270 useEffect(() => {
271 setInspectorSelection((current) => {
272 if (props.renderInspector === undefined) {
273 if (current === null || current.mode === "route") {
274 return null;
275 }
276 return { ...current, routeThreadIdentity };
277 }
278
279 if (current === null || current.mode === "route") {
280 return { routeThreadIdentity, mode: "route" };
281 }
282
283 return { ...current, routeThreadIdentity };
284 });
285 }, [props.renderInspector, routeThreadIdentity]);
286
287 useFocusEffect(
288 useCallback(() => {
289 return () => {
290 if (props.renderInspector === undefined) {
291 // Inspectors are contextual to this chat destination. Clear the
292 // hidden chat copy after a native push so returning from Files,
293 // Review, or Terminal cannot reserve an empty trailing pane.
294 setInspectorSelection(null);
295 }
296 };
297 }, [props.renderInspector]),
298 );
299 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
300 const routeConnectionState =
301 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
302 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
303 const selectedThreadWithDraftSettings = useMemo(
304 () =>
305 selectedThread
306 ? {
307 ...selectedThread,
308 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
309 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
310 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
311 }
312 : null,
313 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
314 );
315
316 /* ─── Native header theming ──────────────────────────────────────── */
317 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
318 const headerSubtitle = [
319 selectedThreadProject?.title ?? null,
320 selectedEnvironmentConnection?.environmentLabel ?? null,
321 ]
322 .filter(Boolean)
323 .join(" · ");
324 /* ─── Git status for native header trigger ───────────────────────── */
325 const gitStatus = useEnvironmentQuery(
326 selectedThread !== null && selectedThreadCwd !== null
327 ? vcsEnvironment.status({
328 environmentId: selectedThread.environmentId,
329 input: { cwd: selectedThreadCwd },
330 })
331 : null,
332 );
333 const knownTerminalSessions = useKnownTerminalSessions({
334 environmentId: selectedThread?.environmentId ?? null,
335 threadId: selectedThread?.id ?? null,
336 });
337 const terminalMenuSessions = useMemo(
338 () =>
339 buildTerminalMenuSessions({
340 knownSessions: knownTerminalSessions,
341 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
342 }),
343 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
344 );
345 const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
346 const handleReconnectEnvironment = useCallback(() => {
347 if (!environmentId) {
348 return;
349 }
350 onReconnectEnvironment(environmentId);
351 }, [environmentId, onReconnectEnvironment]);
352
353 /* ─── Git action progress (for overlay banner) ──────────────────── */
354 const gitActionProgressTarget = useMemo(
355 () => ({
356 environmentId: selectedThread?.environmentId ?? null,
357 cwd: selectedThreadCwd,
358 }),
359 [selectedThread?.environmentId, selectedThreadCwd],
360 );
361 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
362
363 const handleOpenGitInspector = useCallback(() => {
364 if (!fileInspector.supported) {
365 if (selectedThread === null) {
366 return;
367 }
368 navigation.navigate("GitOverview", {
369 environmentId: String(selectedThread.environmentId),
370 threadId: String(selectedThread.id),
371 });
372 return;
373 }
374 setInspectorSelection({ routeThreadIdentity, mode: "git" });
375 showAuxiliaryPane("inspector");
376 }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
377 const handleOpenFilesInspector = useCallback(() => {
378 if (selectedThread === null || selectedThreadCwd === null) {
379 return;
380 }
381 if (!fileInspector.supported) {
382 navigation.navigate("ThreadFiles", {
383 environmentId: String(selectedThread.environmentId),
384 threadId: String(selectedThread.id),
385 });
386 return;
387 }
388 setInspectorSelection({
389 routeThreadIdentity,
390 mode: props.renderInspector === undefined ? "files" : "route",
391 });
392 showAuxiliaryPane("inspector");
393 }, [
394 fileInspector.supported,
395 navigation,
396 props.renderInspector,
397 routeThreadIdentity,
398 selectedThread,
399 selectedThreadCwd,
400 showAuxiliaryPane,
401 ]);
402 const inspectorToggleActionRef = useRef({
403 inspectorMode,
404 openFilesInspector: handleOpenFilesInspector,
405 toggleAuxiliaryPane,
406 });
407 inspectorToggleActionRef.current = {
408 inspectorMode,
409 openFilesInspector: handleOpenFilesInspector,
410 toggleAuxiliaryPane,
411 };
412 const handleToggleInspector = useCallback(() => {
413 const action = inspectorToggleActionRef.current;
414 if (action.inspectorMode === null) {
415 action.openFilesInspector();
416 return;
417 }
418 action.toggleAuxiliaryPane();
419 }, []);
420 const handleSelectInspectorFile = useCallback(
421 (path: string) => {
422 if (selectedThread === null) {
423 return;
424 }
425 const params = {
426 environmentId: String(selectedThread.environmentId),
427 threadId: String(selectedThread.id),
428 path: path.split("/").filter((segment) => segment.length > 0),
429 };
430 if (fileInspector.supported) {
431 navigation.navigate("ThreadFile", params);
432 return;
433 }
434 navigation.navigate("ThreadFile", params);
435 },
436 [fileInspector.supported, navigation, selectedThread],
437 );
438 // The workspace inspector column spans the full window height. On iOS the
439 // panes bring their own nested native headers (which underlap the status
440 // bar); elsewhere the pane content pads itself below the top inset.
441 const safeAreaInsets = useSafeAreaInsets();
442 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
443 const GitInspector = useCallback(
444 () => (
445 <GitOverviewSheet
446 headerInset={inspectorHeaderInset}
447 presentation="inspector"
448 route={{ params: props.route.params }}
449 />
450 ),
451 [inspectorHeaderInset, props.route.params],
452 );
453 const FilesInspector = useCallback(
454 () =>
455 selectedThread !== null && selectedThreadCwd !== null ? (
456 <ThreadFileNavigatorPane
457 cwd={selectedThreadCwd}
458 environmentId={selectedThread.environmentId}
459 headerInset={inspectorHeaderInset}
460 projectName={selectedThreadProject?.title ?? "Files"}
461 selectedPath={null}
462 onSelectFile={handleSelectInspectorFile}
463 />
464 ) : null,
465 [
466 handleSelectInspectorFile,
467 inspectorHeaderInset,
468 selectedThread,
469 selectedThreadCwd,
470 selectedThreadProject?.title,
471 ],
472 );
473 const RouteInspector = useCallback(
474 () => props.renderInspector?.(inspectorHeaderInset),
475 [inspectorHeaderInset, props.renderInspector],
476 );
477 const renderInspectorStack = useCallback(
478 () =>
479 inspectorMode === null ? null : (
480 <ThreadInspectorContentStack
481 Files={FilesInspector}
482 Git={GitInspector}
483 mode={inspectorMode}
484 Route={props.renderInspector ? RouteInspector : undefined}
485 />
486 ),
487 [FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector],
488 );
489 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
490 // Hand the inspector to the workspace so it renders beside the navigator,
491 // outside this screen's native header — the terminal/git/files toolbar
492 // stays anchored to the chat pane instead of floating above the inspector.
493 useRegisterWorkspaceInspector(activeInspectorRenderer);
494
495 const handleOpenConnectionEditor = useCallback(() => {
496 void navigation.navigate("Connections");
497 }, [navigation]);
498 const handleStopThread = useCallback(() => {
499 if (
500 !selectedThread ||
501 (selectedThread.session?.status !== "running" &&
502 selectedThread.session?.status !== "starting")
503 ) {
504 return;
505 }
506 return interruptThreadTurn({
507 environmentId: selectedThread.environmentId,
508 input: {
509 threadId: selectedThread.id,
510 ...(selectedThread.session.activeTurnId
511 ? { turnId: selectedThread.session.activeTurnId }
512 : {}),
513 },
514 });
515 }, [interruptThreadTurn, selectedThread]);
516
517 const handleOpenTerminal = useCallback(
518 (nextTerminalId?: string | null) => {
519 terminalDebugLog("terminal-menu:open-existing", {
520 terminalId: nextTerminalId ?? null,
521 hasThread: Boolean(selectedThread),
522 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
523 });
524
525 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
526 return;
527 }
528
529 void navigation.navigate("ThreadTerminal", {
530 environmentId: String(selectedThread.environmentId),
531 threadId: String(selectedThread.id),
532 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
533 });
534 },
535 [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
536 );
537
538 const handleOpenNewTerminal = useCallback(() => {
539 terminalDebugLog("terminal-menu:open-new", {
540 hasThread: Boolean(selectedThread),
541 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
542 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
543 });
544
545 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
546 return;
547 }
548
549 const nextId = nextOpenTerminalId({
550 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
551 });
552 void navigation.navigate("ThreadTerminal", {
553 environmentId: String(selectedThread.environmentId),
554 threadId: String(selectedThread.id),
555 terminalId: nextId,
556 });
557 }, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
558
559 const handleRunProjectScript = useCallback(
560 async (script: ProjectScript) => {
561 terminalDebugLog("project-script:press", {
562 scriptId: script.id,
563 command: script.command,
564 hasThread: Boolean(selectedThread),
565 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
566 });
567
568 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
569 terminalDebugLog("project-script:abort", {
570 scriptId: script.id,
571 reason: "no-thread-or-workspace",
572 });
573 return;
574 }
575
576 const targetTerminalId = resolveProjectScriptTerminalId({
577 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
578 hasRunningTerminal: terminalMenuSessions.some(
579 (session) => session.status === "running" || session.status === "starting",
580 ),
581 });
582 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
583 threadShellWorktreePath: selectedThread.worktreePath ?? null,
584 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
585 });
586 const cwd = projectScriptCwd({
587 project: { cwd: selectedThreadProject.workspaceRoot },
588 worktreePath: preferredWorktreePath,
589 });
590 const env = projectScriptRuntimeEnv({
591 project: { cwd: selectedThreadProject.workspaceRoot },
592 worktreePath: preferredWorktreePath,
593 });
594 stagePendingTerminalLaunch({
595 target: {
596 environmentId: selectedThread.environmentId,
597 threadId: selectedThread.id,
598 terminalId: targetTerminalId,
599 },
600 launch: {
601 cwd,
602 worktreePath: preferredWorktreePath,
603 env,
604 initialInput: `${script.command}\r`,
605 },
606 });
607 terminalDebugLog("project-script:staged", {
608 scriptId: script.id,
609 terminalId: targetTerminalId,
610 cwd,
611 worktreePath: preferredWorktreePath,
612 });
613
614 void navigation.navigate("ThreadTerminal", {
615 environmentId: String(selectedThread.environmentId),
616 threadId: String(selectedThread.id),
617 terminalId: targetTerminalId,
618 });
619 },
620 [
621 navigation,
622 selectedThread,
623 selectedThreadDetailWorktreePath,
624 selectedThreadProject,
625 terminalMenuSessions,
626 ],
627 );
628 const threadGitControlProps = {
629 environmentId: environmentIdRaw ?? "",
630 threadId: threadId ?? "",
631 auxiliaryPaneControl:
632 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
633 ? {
634 accessibilityLabel: "Toggle inspector",
635 onPress: handleToggleInspector,
636 }
637 : undefined,
638 onOpenFilesInspector:
639 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
640 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
641 currentBranch: selectedThread?.branch ?? null,
642 gitStatus: gitStatus.data,
643 gitOperationLabel: gitState.gitOperationLabel,
644 canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
645 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
646 projectScripts: selectedThreadProject
647 ? resolveProjectScripts(
648 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
649 selectedThreadProject,
650 )
651 : [],
652 terminalSessions: terminalMenuSessions,
653 showDirectFileControl: layout.usesSplitView,
654 onOpenTerminal: handleOpenTerminal,
655 onOpenNewTerminal: handleOpenNewTerminal,
656 onRunProjectScript: handleRunProjectScript,
657 onPull: gitActions.onPullSelectedThreadBranch,
658 onRunAction: gitActions.onRunSelectedThreadGitAction,
659 };
660 const threadCenterHeaderItems = useThreadGitCenterHeaderItems(threadGitControlProps);
661 const compactRightHeaderItems = useThreadGitRightHeaderItems(threadGitControlProps);
662 const splitLeftHeaderItems = useMemo<NativeHeaderItems>(
663 () => [
664 {
665 // Match Mail's split-view detail toolbar: the first detail action sits
666 // inside the content pane, not flush against the sidebar divider.
667 spacing: 18,
668 type: "spacing" as const,
669 },
670 ...(props.onReturnToThread
671 ? [
672 withNativeGlassHeaderItem({
673 accessibilityLabel: "Return to chat",
674 icon: { name: "chevron.left", type: "sfSymbol" as const },
675 identifier: "thread-left-return",
676 onPress: props.onReturnToThread,
677 type: "button" as const,
678 }),
679 ]
680 : []),
681 withNativeGlassHeaderItem({
682 accessibilityLabel: panes.primarySidebarVisible
683 ? "Maximize content"
684 : "Show thread sidebar",
685 icon: {
686 name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",
687 type: "sfSymbol" as const,
688 },
689 identifier: "thread-left-sidebar",
690 onPress: togglePrimarySidebar,
691 type: "button" as const,
692 }),
693 withNativeGlassHeaderItem({
694 accessibilityLabel: "New task",
695 icon: { name: "square.and.pencil", type: "sfSymbol" as const },
696 identifier: "thread-left-new-task",
697 onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),
698 type: "button" as const,
699 }),
700 ],
701 [panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
702 );
703 const androidHeaderActions = useMemo<ReadonlyArray<AndroidHeaderAction>>(() => {
704 if (Platform.OS !== "android") return [];
705
706 const actions: AndroidHeaderAction[] = [];
707 if (props.onReturnToThread) {
708 actions.push({
709 accessibilityLabel: "Return to chat",
710 icon: "chevron.left",
711 onPress: props.onReturnToThread,
712 });
713 }
714 if (selectedThreadCwd !== null) {
715 actions.push({
716 accessibilityLabel: "Open files",
717 icon: "folder",
718 onPress: handleOpenFilesInspector,
719 });
720 }
721 if (selectedThreadProject?.workspaceRoot) {
722 actions.push({
723 accessibilityLabel: "Open terminal",
724 icon: "terminal",
725 onPress: () => handleOpenTerminal(null),
726 });
727 }
728 actions.push({
729 accessibilityLabel: "Open git controls",
730 icon: "point.topleft.down.curvedto.point.bottomright.up",
731 onPress: handleOpenGitInspector,
732 });
733 if (fileInspector.supported && selectedThreadCwd !== null) {
734 actions.push({
735 accessibilityLabel: "Toggle inspector",
736 icon: "sidebar.right",
737 onPress: handleToggleInspector,
738 });
739 }
740 return actions;
741 }, [
742 fileInspector.supported,
743 handleOpenFilesInspector,
744 handleOpenTerminal,
745 handleOpenGitInspector,
746 handleToggleInspector,
747 props.onReturnToThread,
748 selectedThreadCwd,
749 selectedThreadProject?.workspaceRoot,
750 ]);
751
752 const handleEditFailedCreation = useCallback(async () => {
753 const creation = selectedThreadCreation?.message;
754 if (!creation?.creation || routeThreadIdentity === null) {
755 return;
756 }
757 // The drain restored the prompt and attachments into the recovery draft
758 // the rejected creation owns. Open that draft by id: without it the sheet
759 // mints a fresh empty one and the restored content is unreachable.
760 try {
761 await recoverFailedThreadDraft(creation);
762 } catch (error) {
763 Alert.alert(
764 "Could not restore draft",
765 error instanceof Error ? error.message : String(error),
766 );
767 return;
768 }
769 clearPendingThreadCreationOutcome(routeThreadIdentity);
770 navigation.dispatch(
771 StackActions.replace("NewTaskSheet", {
772 screen: "NewTaskDraft",
773 params: {
774 draftId: restoredNewTaskDraftKey(creation.messageId),
775 environmentId: String(creation.environmentId),
776 projectId: String(creation.creation.projectId),
777 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
778 },
779 }),
780 );
781 }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
782 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
783 if (selectedThreadCreation === null) {
784 return null;
785 }
786 if (selectedThreadCreation.outcome?.kind === "failed") {
787 return {
788 kind: "failed",
789 reason: selectedThreadCreation.outcome.reason,
790 onEditTask: handleEditFailedCreation,
791 };
792 }
793 return {
794 kind: "preparing",
795 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
796 };
797 })();
798 // Deep links / cold starts land with Thread as the ONLY route, where the
799 // native back button does not render. Provide an explicit Home escape for
800 // that case; when history exists the native back button is used instead.
801 const canGoBack = navigation.canGoBack();
802 const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
803 () => [
804 withNativeGlassHeaderItem({
805 accessibilityLabel: "Go to threads list",
806 icon: { name: "list.bullet", type: "sfSymbol" as const },
807 identifier: "thread-left-home",
808 onPress: () => navigation.dispatch(StackActions.replace("Home")),
809 type: "button" as const,
810 }),
811 ],
812 [navigation],
813 );
814
815 if (!environmentId || !threadId) {
816 return <OpeningThreadLoadingScreen />;
817 }
818
819 if (!selectedThread) {
820 return <OpeningThreadLoadingScreen />;
821 }
822
823 // A queued creation renders as ready content: its prompt is the whole
824 // conversation until the server creates the thread. The subscription's
825 // not-found error for that window is expected, not a load failure.
826 const contentPresentation =
827 creationState !== null
828 ? { kind: "ready" as const }
829 : projectThreadContentPresentation({
830 hasDetail: selectedThreadDetail !== null,
831 detailError: Option.getOrNull(selectedThreadDetailState.error),
832 detailDeleted: selectedThreadDetailState.status === "deleted",
833 connectionState: routeConnectionState,
834 });
835 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
836 const renderThreadRouteBody = (showActionControls: boolean) => (
837 <>
838 <ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
839
840 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
841
842 <View className="flex-1 bg-screen">
843 <ThreadDetailScreen
844 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
845 contentPresentation={contentPresentation}
846 screenTone={connectionTone(routeConnectionState)}
847 connectionError={routeConnectionError}
848 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
849 feedbackSubmissions={composer.feedbackSubmissions}
850 onDismissFeedback={composer.dismissFeedback}
851 selectedThreadFeed={composer.selectedThreadFeed}
852 activeWorkStartedAt={composer.activeWorkStartedAt}
853 isCompacting={composer.isCompacting}
854 creationState={creationState}
855 activePendingApproval={requests.activePendingApproval}
856 respondingApprovalId={requests.respondingApprovalId}
857 activePendingUserInput={requests.activePendingUserInput}
858 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
859 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
860 respondingUserInputId={requests.respondingUserInputId}
861 draftMessage={composer.draftMessage}
862 draftAttachments={composer.draftAttachments}
863 connectionStateLabel={routeConnectionState}
864 threadSyncStatus={selectedThreadDetailState.status}
865 loadEarlier={loadEarlierTurns}
866 environmentId={selectedThread.environmentId}
867 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
868 threadCwd={selectedThreadCwd}
869 selectedThreadQueueCount={composer.selectedThreadQueueCount}
870 queuedMessages={composer.selectedThreadQueuedMessages}
871 dispatchingMessageId={composer.dispatchingQueuedMessageId}
872 layoutVariant={layout.variant}
873 usesAutomaticContentInsets={usesNativeHeaderGlass}
874 onOpenConnectionEditor={handleOpenConnectionEditor}
875 onChangeDraftMessage={composer.onChangeDraftMessage}
876 onPickDraftMedia={composer.onPickDraftMedia}
877 onPickDraftFiles={composer.onPickDraftFiles}
878 onNativePasteImages={composer.onNativePasteImages}
879 onRemoveDraftImage={composer.onRemoveDraftImage}
880 serverConfig={serverConfig}
881 onStopThread={handleStopThread}
882 onSendMessage={composer.onSendMessage}
883 onReconnectEnvironment={handleReconnectEnvironment}
884 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
885 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
886 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
887 onRespondToApproval={requests.onRespondToApproval}
888 onSelectUserInputOption={requests.onSelectUserInputOption}
889 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
890 onSubmitUserInput={requests.onSubmitUserInput}
891 onDismissUserInput={requests.onDismissUserInput}
892 />
893 </View>
894 </>
895 );
896
897 return (
898 <>
899 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
900 <NativeStackScreenOptions
901 optionsVersion={threadGitControlProps.projectScripts}
902 options={{
903 // Android draws its own in-flow header (AndroidScreenHeader below);
904 // the native stack header stays iOS-only.
905 headerShown: Platform.OS !== "android",
906 headerTitle: selectedThread.title,
907 headerTitleStyle: usesNativeHeaderGlass
908 ? {
909 fontSize: 17,
910 fontWeight: "800",
911 }
912 : undefined,
913 title: selectedThread.title,
914 headerBackVisible: !layout.usesSplitView,
915 // Compact uses the NATIVE back button when a previous route exists;
916 // deep links / cold starts get an explicit Home button instead.
917 // Split view always uses its custom left items.
918 unstable_headerLeftItems:
919 Platform.OS === "ios"
920 ? layout.usesSplitView
921 ? () => splitLeftHeaderItems
922 : canGoBack
923 ? undefined
924 : () => compactHomeHeaderItems
925 : undefined,
926 // Search lives in the persistent sidebar, so the split header keeps
927 // the git controls on the RIGHT (no center items — center space is
928 // reserved for future breadcrumbs/status).
929 unstable_headerRightItems:
930 Platform.OS === "ios"
931 ? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
932 : undefined,
933 unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
934 }}
935 />
936
937 {Platform.OS === "android" ? (
938 <AndroidScreenHeader
939 title={selectedThread.title}
940 subtitle={headerSubtitle}
941 onBack={layout.usesSplitView ? undefined : () => navigation.goBack()}
942 actions={androidHeaderActions}
943 />
944 ) : null}
945
946 {/* Android surfaces the git/files/inspector actions in its in-flow
947 header above, so the fallback action toolbar stays iOS-only. */}
948 {renderThreadRouteBody(
949 Platform.OS !== "android" && !layout.usesSplitView && !usesNativeHeaderGlass,
950 )}
951 </>
952 );
953}