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

ThreadRouteScreen.tsx

848 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?.thread.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 (!selectedThread || composer.interruptibleRunId === null) {
465 return;
466 }
467 return interruptThreadTurn({
468 environmentId: selectedThread.environmentId,
469 input: {
470 threadId: selectedThread.id,
471 runId: composer.interruptibleRunId,
472 },
473 });
474 }, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
475​
476 const handleOpenTerminal = useCallback(
477 (nextTerminalId?: string | null) => {
478 terminalDebugLog("terminal-menu:open-existing", {
479 terminalId: nextTerminalId ?? null,
480 hasThread: Boolean(selectedThread),
481 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
482 });
483​
484 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
485 return;
486 }
487​
488 void navigation.navigate("ThreadTerminal", {
489 environmentId: String(selectedThread.environmentId),
490 threadId: String(selectedThread.id),
491 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
492 });
493 },
494 [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
495 );
496​
497 const handleOpenNewTerminal = useCallback(() => {
498 terminalDebugLog("terminal-menu:open-new", {
499 hasThread: Boolean(selectedThread),
500 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
501 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
502 });
503​
504 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
505 return;
506 }
507​
508 const nextId = nextOpenTerminalId({
509 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
510 });
511 void navigation.navigate("ThreadTerminal", {
512 environmentId: String(selectedThread.environmentId),
513 threadId: String(selectedThread.id),
514 terminalId: nextId,
515 });
516 }, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
517​
518 const handleRunProjectScript = useCallback(
519 async (script: ProjectScript) => {
520 terminalDebugLog("project-script:press", {
521 scriptId: script.id,
522 command: script.command,
523 hasThread: Boolean(selectedThread),
524 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
525 });
526​
527 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
528 terminalDebugLog("project-script:abort", {
529 scriptId: script.id,
530 reason: "no-thread-or-workspace",
531 });
532 return;
533 }
534​
535 const targetTerminalId = resolveProjectScriptTerminalId({
536 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
537 hasRunningTerminal: terminalMenuSessions.some(
538 (session) => session.status === "running" || session.status === "starting",
539 ),
540 });
541 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
542 threadShellWorktreePath: selectedThread.worktreePath ?? null,
543 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
544 });
545 const cwd = projectScriptCwd({
546 project: { cwd: selectedThreadProject.workspaceRoot },
547 worktreePath: preferredWorktreePath,
548 });
549 const env = projectScriptRuntimeEnv({
550 project: { cwd: selectedThreadProject.workspaceRoot },
551 worktreePath: preferredWorktreePath,
552 });
553 stagePendingTerminalLaunch({
554 target: {
555 environmentId: selectedThread.environmentId,
556 threadId: selectedThread.id,
557 terminalId: targetTerminalId,
558 },
559 launch: {
560 cwd,
561 worktreePath: preferredWorktreePath,
562 env,
563 initialInput: `${script.command}\r`,
564 },
565 });
566 terminalDebugLog("project-script:staged", {
567 scriptId: script.id,
568 terminalId: targetTerminalId,
569 cwd,
570 worktreePath: preferredWorktreePath,
571 });
572​
573 void navigation.navigate("ThreadTerminal", {
574 environmentId: String(selectedThread.environmentId),
575 threadId: String(selectedThread.id),
576 terminalId: targetTerminalId,
577 });
578 },
579 [
580 navigation,
581 selectedThread,
582 selectedThreadDetailWorktreePath,
583 selectedThreadProject,
584 terminalMenuSessions,
585 ],
586 );
587 const threadGitControlProps = {
588 environmentId: environmentIdRaw ?? "",
589 threadId: threadId ?? "",
590 auxiliaryPaneControl:
591 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
592 ? {
593 accessibilityLabel: "Toggle inspector",
594 onPress: handleToggleInspector,
595 }
596 : undefined,
597 onOpenFilesInspector:
598 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
599 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
600 currentBranch: selectedThread?.branch ?? null,
601 gitStatus: gitStatus.data,
602 gitOperationLabel: gitState.gitOperationLabel,
603 canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
604 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
605 projectScripts: selectedThreadProject?.scripts ?? [],
606 terminalSessions: terminalMenuSessions,
607 showDirectFileControl: layout.usesSplitView,
608 onOpenTerminal: handleOpenTerminal,
609 onOpenNewTerminal: handleOpenNewTerminal,
610 onRunProjectScript: handleRunProjectScript,
611 onPull: gitActions.onPullSelectedThreadBranch,
612 onRunAction: gitActions.onRunSelectedThreadGitAction,
613 };
614 const threadCenterHeaderItems = useThreadGitCenterHeaderItems(threadGitControlProps);
615 const compactRightHeaderItems = useThreadGitRightHeaderItems(threadGitControlProps);
616 const splitLeftHeaderItems = useMemo<NativeHeaderItems>(
617 () => [
618 {
619 // Match Mail's split-view detail toolbar: the first detail action sits
620 // inside the content pane, not flush against the sidebar divider.
621 spacing: 18,
622 type: "spacing" as const,
623 },
624 ...(props.onReturnToThread
625 ? [
626 withNativeGlassHeaderItem({
627 accessibilityLabel: "Return to chat",
628 icon: { name: "chevron.left", type: "sfSymbol" as const },
629 identifier: "thread-left-return",
630 onPress: props.onReturnToThread,
631 type: "button" as const,
632 }),
633 ]
634 : []),
635 withNativeGlassHeaderItem({
636 accessibilityLabel: panes.primarySidebarVisible
637 ? "Maximize content"
638 : "Show thread sidebar",
639 icon: {
640 name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",
641 type: "sfSymbol" as const,
642 },
643 identifier: "thread-left-sidebar",
644 onPress: togglePrimarySidebar,
645 type: "button" as const,
646 }),
647 withNativeGlassHeaderItem({
648 accessibilityLabel: "New task",
649 icon: { name: "square.and.pencil", type: "sfSymbol" as const },
650 identifier: "thread-left-new-task",
651 onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),
652 type: "button" as const,
653 }),
654 ],
655 [panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
656 );
657 const androidHeaderActions = useMemo<ReadonlyArray<AndroidHeaderAction>>(() => {
658 if (Platform.OS !== "android") return [];
659​
660 const actions: AndroidHeaderAction[] = [];
661 if (props.onReturnToThread) {
662 actions.push({
663 accessibilityLabel: "Return to chat",
664 icon: "chevron.left",
665 onPress: props.onReturnToThread,
666 });
667 }
668 if (selectedThreadCwd !== null) {
669 actions.push({
670 accessibilityLabel: "Open files",
671 icon: "folder",
672 onPress: handleOpenFilesInspector,
673 });
674 }
675 if (selectedThreadProject?.workspaceRoot) {
676 actions.push({
677 accessibilityLabel: "Open terminal",
678 icon: "terminal",
679 onPress: () => handleOpenTerminal(null),
680 });
681 }
682 actions.push({
683 accessibilityLabel: "Open git controls",
684 icon: "point.topleft.down.curvedto.point.bottomright.up",
685 onPress: handleOpenGitInspector,
686 });
687 if (fileInspector.supported && selectedThreadCwd !== null) {
688 actions.push({
689 accessibilityLabel: "Toggle inspector",
690 icon: "sidebar.right",
691 onPress: handleToggleInspector,
692 });
693 }
694 return actions;
695 }, [
696 fileInspector.supported,
697 handleOpenFilesInspector,
698 handleOpenTerminal,
699 handleOpenGitInspector,
700 handleToggleInspector,
701 props.onReturnToThread,
702 selectedThreadCwd,
703 selectedThreadProject?.workspaceRoot,
704 ]);
705​
706 // Deep links / cold starts land with Thread as the ONLY route, where the
707 // native back button does not render. Provide an explicit Home escape for
708 // that case; when history exists the native back button is used instead.
709 const canGoBack = navigation.canGoBack();
710 const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
711 () => [
712 withNativeGlassHeaderItem({
713 accessibilityLabel: "Go to threads list",
714 icon: { name: "list.bullet", type: "sfSymbol" as const },
715 identifier: "thread-left-home",
716 onPress: () => navigation.dispatch(StackActions.replace("Home")),
717 type: "button" as const,
718 }),
719 ],
720 [navigation],
721 );
722​
723 if (!environmentId || !threadId) {
724 return <OpeningThreadLoadingScreen />;
725 }
726​
727 if (!selectedThread) {
728 return <OpeningThreadLoadingScreen />;
729 }
730​
731 const contentPresentation = projectThreadContentPresentation({
732 hasDetail: selectedThreadDetail !== null,
733 detailError: Option.getOrNull(selectedThreadDetailState.error),
734 detailDeleted: selectedThreadDetailState.status === "deleted",
735 connectionState: routeConnectionState,
736 });
737 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
738 const renderThreadRouteBody = (showActionControls: boolean) => (
739 <>
740 <ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
741​
742 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
743​
744 <View className="flex-1 bg-screen">
745 <ThreadDetailScreen
746 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
747 contentPresentation={contentPresentation}
748 screenTone={connectionTone(routeConnectionState)}
749 connectionError={routeConnectionError}
750 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
751 selectedThreadFeed={composer.selectedThreadFeed}
752 activityRun={composer.selectedThreadActivityRun}
753 activeWorkStartedAt={composer.activeWorkStartedAt}
754 activePendingApproval={requests.activePendingApproval}
755 respondingApprovalId={requests.respondingApprovalId}
756 activePendingUserInput={requests.activePendingUserInput}
757 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
758 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
759 respondingUserInputId={requests.respondingUserInputId}
760 draftMessage={composer.draftMessage}
761 draftAttachments={composer.draftAttachments}
762 connectionStateLabel={routeConnectionState}
763 threadSyncStatus={selectedThreadDetailState.status}
764 activeThreadBusy={composer.activeThreadBusy}
765 canStopThread={composer.interruptibleRunId !== null}
766 environmentId={selectedThread.environmentId}
767 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
768 threadCwd={selectedThreadCwd}
769 selectedThreadQueueCount={composer.selectedThreadQueueCount}
770 layoutVariant={layout.variant}
771 usesAutomaticContentInsets={usesNativeHeaderGlass}
772 onOpenConnectionEditor={handleOpenConnectionEditor}
773 onChangeDraftMessage={composer.onChangeDraftMessage}
774 onPickDraftImages={composer.onPickDraftImages}
775 onNativePasteImages={composer.onNativePasteImages}
776 onRemoveDraftImage={composer.onRemoveDraftImage}
777 serverConfig={serverConfig}
778 onStopThread={handleStopThread}
779 onSendMessage={composer.onSendMessage}
780 onReconnectEnvironment={handleReconnectEnvironment}
781 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
782 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
783 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
784 onRespondToApproval={requests.onRespondToApproval}
785 onSelectUserInputOption={requests.onSelectUserInputOption}
786 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
787 onSubmitUserInput={requests.onSubmitUserInput}
788 />
789 </View>
790 </>
791 );
792​
793 return (
794 <>
795 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
796 <NativeStackScreenOptions
797 options={{
798 // Android draws its own in-flow header (AndroidScreenHeader below);
799 // the native stack header stays iOS-only.
800 headerShown: Platform.OS !== "android",
801 headerTitle: selectedThread.title,
802 headerTitleStyle: usesNativeHeaderGlass
803 ? {
804 fontSize: 17,
805 fontWeight: "800",
806 }
807 : undefined,
808 title: selectedThread.title,
809 headerBackVisible: !layout.usesSplitView,
810 // Compact uses the NATIVE back button when a previous route exists;
811 // deep links / cold starts get an explicit Home button instead.
812 // Split view always uses its custom left items.
813 unstable_headerLeftItems:
814 Platform.OS === "ios"
815 ? layout.usesSplitView
816 ? () => splitLeftHeaderItems
817 : canGoBack
818 ? undefined
819 : () => compactHomeHeaderItems
820 : undefined,
821 // Search lives in the persistent sidebar, so the split header keeps
822 // the git controls on the RIGHT (no center items — center space is
823 // reserved for future breadcrumbs/status).
824 unstable_headerRightItems:
825 Platform.OS === "ios"
826 ? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
827 : undefined,
828 unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
829 }}
830 />
831​
832 {Platform.OS === "android" ? (
833 <AndroidScreenHeader
834 title={selectedThread.title}
835 subtitle={headerSubtitle}
836 onBack={layout.usesSplitView ? undefined : () => navigation.goBack()}
837 actions={androidHeaderActions}
838 />
839 ) : null}
840​
841 {/* Android surfaces the git/files/inspector actions in its in-flow
842 header above, so the fallback action toolbar stays iOS-only. */}
843 {renderThreadRouteBody(
844 Platform.OS !== "android" && !layout.usesSplitView && !usesNativeHeaderGlass,
845 )}
846 </>
847 );