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 // Derive pending requests from the FULL loaded set (older pages + live
198 // window) so a prompt the user scrolled back to load still surfaces.
199 const requests = useSelectedThreadRequests(composer.mergedActivities);
200 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
201 const navigation = useNavigation();
202 const params = props.route.params;
203 const environmentIdRaw = firstRouteParam(params.environmentId);
204 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
205 const threadId = firstRouteParam(params.threadId);
206 const routeThreadIdentity =
207 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
208 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
209 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
210 );
211 const inspectorMode = (() => {
212 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
213 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
214 return null;
215 }
216 return inspectorSelection.mode;
217 }
218 return null;
219 })();
220 useEffect(() => {
221 if (
222 fileInspector.supported &&
223 selectedThreadCwd === null &&
224 inspectorMode === null &&
225 panes.auxiliaryPaneVisible
226 ) {
227 toggleAuxiliaryPane();
228 }
229 }, [
230 fileInspector.supported,
231 inspectorMode,
232 panes.auxiliaryPaneVisible,
233 selectedThreadCwd,
234 toggleAuxiliaryPane,
235 ]);
236
237 useEffect(() => {
238 setInspectorSelection((current) => {
239 if (props.renderInspector === undefined) {
240 if (current === null || current.mode === "route") {
241 return null;
242 }
243 return { ...current, routeThreadIdentity };
244 }
245
246 if (current === null || current.mode === "route") {
247 return { routeThreadIdentity, mode: "route" };
248 }
249
250 return { ...current, routeThreadIdentity };
251 });
252 }, [props.renderInspector, routeThreadIdentity]);
253
254 useFocusEffect(
255 useCallback(() => {
256 return () => {
257 if (props.renderInspector === undefined) {
258 // Inspectors are contextual to this chat destination. Clear the
259 // hidden chat copy after a native push so returning from Files,
260 // Review, or Terminal cannot reserve an empty trailing pane.
261 setInspectorSelection(null);
262 }
263 };
264 }, [props.renderInspector]),
265 );
266 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
267 const routeConnectionState =
268 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
269 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
270 const selectedThreadWithDraftSettings = useMemo(
271 () =>
272 selectedThread
273 ? {
274 ...selectedThread,
275 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
276 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
277 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
278 }
279 : null,
280 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
281 );
282
283 /* ─── Native header theming ──────────────────────────────────────── */
284 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
285 const headerSubtitle = [
286 selectedThreadProject?.title ?? null,
287 selectedEnvironmentConnection?.environmentLabel ?? null,
288 ]
289 .filter(Boolean)
290 .join(" · ");
291 /* ─── Git status for native header trigger ───────────────────────── */
292 const gitStatus = useEnvironmentQuery(
293 selectedThread !== null && selectedThreadCwd !== null
294 ? vcsEnvironment.status({
295 environmentId: selectedThread.environmentId,
296 input: { cwd: selectedThreadCwd },
297 })
298 : null,
299 );
300 const knownTerminalSessions = useKnownTerminalSessions({
301 environmentId: selectedThread?.environmentId ?? null,
302 threadId: selectedThread?.id ?? null,
303 });
304 const terminalMenuSessions = useMemo(
305 () =>
306 buildTerminalMenuSessions({
307 knownSessions: knownTerminalSessions,
308 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
309 }),
310 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
311 );
312 const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
313 const handleReconnectEnvironment = useCallback(() => {
314 if (!environmentId) {
315 return;
316 }
317 onReconnectEnvironment(environmentId);
318 }, [environmentId, onReconnectEnvironment]);
319
320 /* ─── Git action progress (for overlay banner) ──────────────────── */
321 const gitActionProgressTarget = useMemo(
322 () => ({
323 environmentId: selectedThread?.environmentId ?? null,
324 cwd: selectedThreadCwd,
325 }),
326 [selectedThread?.environmentId, selectedThreadCwd],
327 );
328 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
329
330 const handleOpenGitInspector = useCallback(() => {
331 if (!fileInspector.supported) {
332 if (selectedThread === null) {
333 return;
334 }
335 navigation.navigate("GitOverview", {
336 environmentId: String(selectedThread.environmentId),
337 threadId: String(selectedThread.id),
338 });
339 return;
340 }
341 setInspectorSelection({ routeThreadIdentity, mode: "git" });
342 showAuxiliaryPane("inspector");
343 }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
344 const handleOpenFilesInspector = useCallback(() => {
345 if (selectedThread === null || selectedThreadCwd === null) {
346 return;
347 }
348 if (!fileInspector.supported) {
349 navigation.navigate("ThreadFiles", {
350 environmentId: String(selectedThread.environmentId),
351 threadId: String(selectedThread.id),
352 });
353 return;
354 }
355 setInspectorSelection({
356 routeThreadIdentity,
357 mode: props.renderInspector === undefined ? "files" : "route",
358 });
359 showAuxiliaryPane("inspector");
360 }, [
361 fileInspector.supported,
362 navigation,
363 props.renderInspector,
364 routeThreadIdentity,
365 selectedThread,
366 selectedThreadCwd,
367 showAuxiliaryPane,
368 ]);
369 const inspectorToggleActionRef = useRef({
370 inspectorMode,
371 openFilesInspector: handleOpenFilesInspector,
372 toggleAuxiliaryPane,
373 });
374 inspectorToggleActionRef.current = {
375 inspectorMode,
376 openFilesInspector: handleOpenFilesInspector,
377 toggleAuxiliaryPane,
378 };
379 const handleToggleInspector = useCallback(() => {
380 const action = inspectorToggleActionRef.current;
381 if (action.inspectorMode === null) {
382 action.openFilesInspector();
383 return;
384 }
385 action.toggleAuxiliaryPane();
386 }, []);
387 const handleSelectInspectorFile = useCallback(
388 (path: string) => {
389 if (selectedThread === null) {
390 return;
391 }
392 const params = {
393 environmentId: String(selectedThread.environmentId),
394 threadId: String(selectedThread.id),
395 path: path.split("/").filter((segment) => segment.length > 0),
396 };
397 if (fileInspector.supported) {
398 navigation.navigate("ThreadFile", params);
399 return;
400 }
401 navigation.navigate("ThreadFile", params);
402 },
403 [fileInspector.supported, navigation, selectedThread],
404 );
405 // The workspace inspector column spans the full window height. On iOS the
406 // panes bring their own nested native headers (which underlap the status
407 // bar); elsewhere the pane content pads itself below the top inset.
408 const safeAreaInsets = useSafeAreaInsets();
409 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
410 const GitInspector = useCallback(
411 () => (
412 <GitOverviewSheet
413 headerInset={inspectorHeaderInset}
414 presentation="inspector"
415 route={{ params: props.route.params }}
416 />
417 ),
418 [inspectorHeaderInset, props.route.params],
419 );
420 const FilesInspector = useCallback(
421 () =>
422 selectedThread !== null && selectedThreadCwd !== null ? (
423 <ThreadFileNavigatorPane
424 cwd={selectedThreadCwd}
425 environmentId={selectedThread.environmentId}
426 headerInset={inspectorHeaderInset}
427 projectName={selectedThreadProject?.title ?? "Files"}
428 selectedPath={null}
429 onSelectFile={handleSelectInspectorFile}
430 />
431 ) : null,
432 [
433 handleSelectInspectorFile,
434 inspectorHeaderInset,
435 selectedThread,
436 selectedThreadCwd,
437 selectedThreadProject?.title,
438 ],
439 );
440 const RouteInspector = useCallback(
441 () => props.renderInspector?.(inspectorHeaderInset),
442 [inspectorHeaderInset, props.renderInspector],
443 );
444 const renderInspectorStack = useCallback(
445 () =>
446 inspectorMode === null ? null : (
447 <ThreadInspectorContentStack
448 Files={FilesInspector}
449 Git={GitInspector}
450 mode={inspectorMode}
451 Route={props.renderInspector ? RouteInspector : undefined}
452 />
453 ),
454 [FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector],
455 );
456 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
457 // Hand the inspector to the workspace so it renders beside the navigator,
458 // outside this screen's native header — the terminal/git/files toolbar
459 // stays anchored to the chat pane instead of floating above the inspector.
460 useRegisterWorkspaceInspector(activeInspectorRenderer);
461
462 const handleOpenConnectionEditor = useCallback(() => {
463 void navigation.navigate("Connections");
464 }, [navigation]);
465 const handleStopThread = useCallback(() => {
466 if (
467 !selectedThread ||
468 (selectedThread.session?.status !== "running" &&
469 selectedThread.session?.status !== "starting")
470 ) {
471 return;
472 }
473 return interruptThreadTurn({
474 environmentId: selectedThread.environmentId,
475 input: {
476 threadId: selectedThread.id,
477 ...(selectedThread.session.activeTurnId
478 ? { turnId: selectedThread.session.activeTurnId }
479 : {}),
480 },
481 });
482 }, [interruptThreadTurn, selectedThread]);
483
484 const handleOpenTerminal = useCallback(
485 (nextTerminalId?: string | null) => {
486 terminalDebugLog("terminal-menu:open-existing", {
487 terminalId: nextTerminalId ?? null,
488 hasThread: Boolean(selectedThread),
489 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
490 });
491
492 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
493 return;
494 }
495
496 void navigation.navigate("ThreadTerminal", {
497 environmentId: String(selectedThread.environmentId),
498 threadId: String(selectedThread.id),
499 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
500 });
501 },
502 [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
503 );
504
505 const handleOpenNewTerminal = useCallback(() => {
506 terminalDebugLog("terminal-menu:open-new", {
507 hasThread: Boolean(selectedThread),
508 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
509 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
510 });
511
512 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
513 return;
514 }
515
516 const nextId = nextOpenTerminalId({
517 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
518 });
519 void navigation.navigate("ThreadTerminal", {
520 environmentId: String(selectedThread.environmentId),
521 threadId: String(selectedThread.id),
522 terminalId: nextId,
523 });
524 }, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
525
526 const handleRunProjectScript = useCallback(
527 async (script: ProjectScript) => {
528 terminalDebugLog("project-script:press", {
529 scriptId: script.id,
530 command: script.command,
531 hasThread: Boolean(selectedThread),
532 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
533 });
534
535 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
536 terminalDebugLog("project-script:abort", {
537 scriptId: script.id,
538 reason: "no-thread-or-workspace",
539 });
540 return;
541 }
542
543 const targetTerminalId = resolveProjectScriptTerminalId({
544 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
545 hasRunningTerminal: terminalMenuSessions.some(
546 (session) => session.status === "running" || session.status === "starting",
547 ),
548 });
549 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
550 threadShellWorktreePath: selectedThread.worktreePath ?? null,
551 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
552 });
553 const cwd = projectScriptCwd({
554 project: { cwd: selectedThreadProject.workspaceRoot },
555 worktreePath: preferredWorktreePath,
556 });
557 const env = projectScriptRuntimeEnv({
558 project: { cwd: selectedThreadProject.workspaceRoot },
559 worktreePath: preferredWorktreePath,
560 });
561 stagePendingTerminalLaunch({
562 target: {
563 environmentId: selectedThread.environmentId,
564 threadId: selectedThread.id,
565 terminalId: targetTerminalId,
566 },
567 launch: {
568 cwd,
569 worktreePath: preferredWorktreePath,
570 env,
571 initialInput: `${script.command}\r`,
572 },
573 });
574 terminalDebugLog("project-script:staged", {
575 scriptId: script.id,
576 terminalId: targetTerminalId,
577 cwd,
578 worktreePath: preferredWorktreePath,
579 });
580
581 void navigation.navigate("ThreadTerminal", {
582 environmentId: String(selectedThread.environmentId),
583 threadId: String(selectedThread.id),
584 terminalId: targetTerminalId,
585 });
586 },
587 [
588 navigation,
589 selectedThread,
590 selectedThreadDetailWorktreePath,
591 selectedThreadProject,
592 terminalMenuSessions,
593 ],
594 );
595 const threadGitControlProps = {
596 environmentId: environmentIdRaw ?? "",
597 threadId: threadId ?? "",
598 auxiliaryPaneControl:
599 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
600 ? {
601 accessibilityLabel: "Toggle inspector",
602 onPress: handleToggleInspector,
603 }
604 : undefined,
605 onOpenFilesInspector:
606 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
607 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
608 currentBranch: selectedThread?.branch ?? null,
609 gitStatus: gitStatus.data,
610 gitOperationLabel: gitState.gitOperationLabel,
611 canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
612 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
613 projectScripts: selectedThreadProject?.scripts ?? [],
614 terminalSessions: terminalMenuSessions,
615 showDirectFileControl: layout.usesSplitView,
616 onOpenTerminal: handleOpenTerminal,
617 onOpenNewTerminal: handleOpenNewTerminal,
618 onRunProjectScript: handleRunProjectScript,
619 onPull: gitActions.onPullSelectedThreadBranch,
620 onRunAction: gitActions.onRunSelectedThreadGitAction,
621 };
622 const threadCenterHeaderItems = useThreadGitCenterHeaderItems(threadGitControlProps);
623 const compactRightHeaderItems = useThreadGitRightHeaderItems(threadGitControlProps);
624 const splitLeftHeaderItems = useMemo<NativeHeaderItems>(
625 () => [
626 {
627 // Match Mail's split-view detail toolbar: the first detail action sits
628 // inside the content pane, not flush against the sidebar divider.
629 spacing: 18,
630 type: "spacing" as const,
631 },
632 ...(props.onReturnToThread
633 ? [
634 withNativeGlassHeaderItem({
635 accessibilityLabel: "Return to chat",
636 icon: { name: "chevron.left", type: "sfSymbol" as const },
637 identifier: "thread-left-return",
638 onPress: props.onReturnToThread,
639 type: "button" as const,
640 }),
641 ]
642 : []),
643 withNativeGlassHeaderItem({
644 accessibilityLabel: panes.primarySidebarVisible
645 ? "Maximize content"
646 : "Show thread sidebar",
647 icon: {
648 name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",
649 type: "sfSymbol" as const,
650 },
651 identifier: "thread-left-sidebar",
652 onPress: togglePrimarySidebar,
653 type: "button" as const,
654 }),
655 withNativeGlassHeaderItem({
656 accessibilityLabel: "New task",
657 icon: { name: "square.and.pencil", type: "sfSymbol" as const },
658 identifier: "thread-left-new-task",
659 onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),
660 type: "button" as const,
661 }),
662 ],
663 [panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
664 );
665 const androidHeaderActions = useMemo<ReadonlyArray<AndroidHeaderAction>>(() => {
666 if (Platform.OS !== "android") return [];
667
668 const actions: AndroidHeaderAction[] = [];
669 if (props.onReturnToThread) {
670 actions.push({
671 accessibilityLabel: "Return to chat",
672 icon: "chevron.left",
673 onPress: props.onReturnToThread,
674 });
675 }
676 if (selectedThreadCwd !== null) {
677 actions.push({
678 accessibilityLabel: "Open files",
679 icon: "folder",
680 onPress: handleOpenFilesInspector,
681 });
682 }
683 if (selectedThreadProject?.workspaceRoot) {
684 actions.push({
685 accessibilityLabel: "Open terminal",
686 icon: "terminal",
687 onPress: () => handleOpenTerminal(null),
688 });
689 }
690 actions.push({
691 accessibilityLabel: "Open git controls",
692 icon: "point.topleft.down.curvedto.point.bottomright.up",
693 onPress: handleOpenGitInspector,
694 });
695 if (fileInspector.supported && selectedThreadCwd !== null) {
696 actions.push({
697 accessibilityLabel: "Toggle inspector",
698 icon: "sidebar.right",
699 onPress: handleToggleInspector,
700 });
701 }
702 return actions;
703 }, [
704 fileInspector.supported,
705 handleOpenFilesInspector,
706 handleOpenTerminal,
707 handleOpenGitInspector,
708 handleToggleInspector,
709 props.onReturnToThread,
710 selectedThreadCwd,
711 selectedThreadProject?.workspaceRoot,
712 ]);
713
714 // Deep links / cold starts land with Thread as the ONLY route, where the
715 // native back button does not render. Provide an explicit Home escape for
716 // that case; when history exists the native back button is used instead.
717 const canGoBack = navigation.canGoBack();
718 const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
719 () => [
720 withNativeGlassHeaderItem({
721 accessibilityLabel: "Go to threads list",
722 icon: { name: "list.bullet", type: "sfSymbol" as const },
723 identifier: "thread-left-home",
724 onPress: () => navigation.dispatch(StackActions.replace("Home")),
725 type: "button" as const,
726 }),
727 ],
728 [navigation],
729 );
730
731 if (!environmentId || !threadId) {
732 return <OpeningThreadLoadingScreen />;
733 }
734
735 if (!selectedThread) {
736 return <OpeningThreadLoadingScreen />;
737 }
738
739 const contentPresentation = projectThreadContentPresentation({
740 hasDetail: selectedThreadDetail !== null,
741 detailError: Option.getOrNull(selectedThreadDetailState.error),
742 detailDeleted: selectedThreadDetailState.status === "deleted",
743 connectionState: routeConnectionState,
744 });
745 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
746 const renderThreadRouteBody = (showActionControls: boolean) => (
747 <>
748 <ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
749
750 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
751
752 <View className="flex-1 bg-screen">
753 <ThreadDetailScreen
754 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
755 contentPresentation={contentPresentation}
756 screenTone={connectionTone(routeConnectionState)}
757 connectionError={routeConnectionError}
758 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
759 selectedThreadFeed={composer.selectedThreadFeed}
760 activeWorkStartedAt={composer.activeWorkStartedAt}
761 activePendingApproval={requests.activePendingApproval}
762 respondingApprovalId={requests.respondingApprovalId}
763 activePendingUserInput={requests.activePendingUserInput}
764 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
765 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
766 respondingUserInputId={requests.respondingUserInputId}
767 draftMessage={composer.draftMessage}
768 draftAttachments={composer.draftAttachments}
769 connectionStateLabel={routeConnectionState}
770 threadSyncStatus={selectedThreadDetailState.status}
771 activeThreadBusy={composer.activeThreadBusy}
772 hasMoreOlderActivities={composer.hasMoreOlderActivities}
773 loadingOlderActivities={composer.loadingOlderActivities}
774 onLoadOlderActivities={composer.onLoadOlderActivities}
775 environmentId={selectedThread.environmentId}
776 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
777 threadCwd={selectedThreadCwd}
778 selectedThreadQueueCount={composer.selectedThreadQueueCount}
779 layoutVariant={layout.variant}
780 usesAutomaticContentInsets={usesNativeHeaderGlass}
781 onOpenConnectionEditor={handleOpenConnectionEditor}
782 onChangeDraftMessage={composer.onChangeDraftMessage}
783 onPickDraftImages={composer.onPickDraftImages}
784 onNativePasteImages={composer.onNativePasteImages}
785 onRemoveDraftImage={composer.onRemoveDraftImage}
786 serverConfig={serverConfig}
787 onStopThread={handleStopThread}
788 onSendMessage={composer.onSendMessage}
789 onReconnectEnvironment={handleReconnectEnvironment}
790 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
791 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
792 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
793 onRespondToApproval={requests.onRespondToApproval}
794 onSelectUserInputOption={requests.onSelectUserInputOption}
795 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
796 onSubmitUserInput={requests.onSubmitUserInput}
797 />
798 </View>
799 </>
800 );
801
802 return (
803 <>
804 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
805 <NativeStackScreenOptions
806 options={{
807 // Android draws its own in-flow header (AndroidScreenHeader below);
808 // the native stack header stays iOS-only.
809 headerShown: Platform.OS !== "android",
810 headerTitle: selectedThread.title,
811 headerTitleStyle: usesNativeHeaderGlass
812 ? {
813 fontSize: 17,
814 fontWeight: "800",
815 }
816 : undefined,
817 title: selectedThread.title,
818 headerBackVisible: !layout.usesSplitView,
819 // Compact uses the NATIVE back button when a previous route exists;
820 // deep links / cold starts get an explicit Home button instead.
821 // Split view always uses its custom left items.
822 unstable_headerLeftItems:
823 Platform.OS === "ios"
824 ? layout.usesSplitView
825 ? () => splitLeftHeaderItems
826 : canGoBack
827 ? undefined
828 : () => compactHomeHeaderItems
829 : undefined,
830 // Search lives in the persistent sidebar, so the split header keeps
831 // the git controls on the RIGHT (no center items — center space is
832 // reserved for future breadcrumbs/status).
833 unstable_headerRightItems:
834 Platform.OS === "ios"
835 ? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
836 : undefined,
837 unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
838 }}
839 />
840
841 {Platform.OS === "android" ? (
842 <AndroidScreenHeader
843 title={selectedThread.title}
844 subtitle={headerSubtitle}
845 onBack={layout.usesSplitView ? undefined : () => navigation.goBack()}
846 actions={androidHeaderActions}
847 />
848 ) : null}
849
850 {/* Android surfaces the git/files/inspector actions in its in-flow
851 header above, so the fallback action toolbar stays iOS-only. */}
852 {renderThreadRouteBody(
853 Platform.OS !== "android" && !layout.usesSplitView && !usesNativeHeaderGlass,
854 )}
855 </>
856 );
857}