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

ThreadRouteScreen.tsx

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