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

ThreadRouteScreen.tsx

876 lines32.5 KB

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