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

ThreadRouteScreen.tsx

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