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