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