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