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

ThreadRouteScreen.tsx

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