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