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

ThreadRouteScreen.tsx

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