Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadRouteScreen.tsx

852 lines31.5 KB

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