Open History to see the last commit
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 { Alert, Platform, ScrollView, View } from "react-native";
26import { useSafeAreaInsets } from "react-native-safe-area-context";
27import { useWorkspaceState } from "../../state/workspace";
28import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
29import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
30import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
31import { useEnvironmentQuery } from "../../state/query";
32import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
33import { vcsEnvironment } from "../../state/vcs";
34
35import { EmptyState } from "../../components/EmptyState";
36import {
37 AndroidScreenHeader,
38 type AndroidHeaderAction,
39} from "../../components/AndroidScreenHeader";
40import { LoadingScreen } from "../../components/LoadingScreen";
41import { scopedThreadKey } from "../../lib/scopedEntities";
42import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
43import { connectionTone } from "../connection/connectionTone";
44
45import {
46 useRemoteConnections,
47 useRemoteConnectionStatus,
48 useRemoteEnvironmentRuntime,
49} from "../../state/use-remote-environment-registry";
50import { useKnownTerminalSessions } from "../../state/use-terminal-session";
51import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
52import { useThreadSelection } from "../../state/use-thread-selection";
53import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
54import {
55 buildTerminalMenuSessions,
56 nextOpenTerminalId,
57 resolveProjectScriptTerminalId,
58} from "../terminal/terminalMenu";
59import {
60 resolvePreferredThreadWorktreePath,
61 stagePendingTerminalLaunch,
62} from "../terminal/terminalLaunchContext";
63import { terminalDebugLog } from "../terminal/terminalDebugLog";
64import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
65import {
66 ThreadGitControls,
67 useThreadGitCenterHeaderItems,
68 useThreadGitRightHeaderItems,
69} from "./ThreadGitControls";
70import { GitOverviewSheet } from "./git/GitOverviewSheet";
71import { useAtomCommand } from "../../state/use-atom-command";
72import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
73import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
74import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
75import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
76import { useThreadComposerState } from "../../state/use-thread-composer-state";
77import { threadEnvironment } from "../../state/threads";
78import { projectThreadContentPresentation } from "./threadContentPresentation";
79import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
80import {
81 useAdaptiveWorkspaceLayout,
82 useAdaptiveWorkspacePaneRole,
83 useRegisterWorkspaceInspector,
84} from "../layout/AdaptiveWorkspaceLayout";
85import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
86import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
87import {
88 ThreadInspectorContentStack,
89 type ThreadInspectorMode,
90} from "./thread-inspector-content-stack";
91
92interface ThreadInspectorSelection {
93 readonly routeThreadIdentity: string | null;
94 readonly mode: ThreadInspectorMode;
95}
96
97type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;
98
99function InspectorPaneRoleActivation() {
100 useAdaptiveWorkspacePaneRole("inspector");
101 return null;
102}
103
104function firstRouteParam(value: string | string[] | undefined): string | null {
105 if (Array.isArray(value)) {
106 return value[0] ?? null;
107 }
108
109 return value ?? null;
110}
111
112function OpeningThreadLoadingScreen() {
113 return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
114}
115
116type ThreadRouteScreenRouteProps = StaticScreenProps<{
117 readonly environmentId: string;
118 readonly threadId: string;
119}>;
120
121interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
122 readonly onReturnToThread?: () => void;
123 readonly renderInspector?: (headerInset: number) => ReactNode;
124}
125
126function ThreadUnavailableScreen() {
127 return (
128 <ScrollView
129 contentInsetAdjustmentBehavior="automatic"
130 contentContainerStyle={{
131 flexGrow: 1,
132 justifyContent: "center",
133 paddingHorizontal: 24,
134 paddingVertical: 32,
135 }}
136 className="bg-screen flex-1"
137 >
138 <EmptyState
139 title="Thread unavailable"
140 detail="This thread is not available in the current mobile snapshot."
141 />
142 </ScrollView>
143 );
144}
145
146export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
147 const { state: workspaceState } = useWorkspaceState();
148 const { connectionState } = useRemoteConnectionStatus();
149 const { selectedThread } = useThreadSelection();
150 const params = props.route.params;
151 const environmentIdRaw = firstRouteParam(params.environmentId);
152 const threadIdRaw = firstRouteParam(params.threadId);
153 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
154 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
155 const routeConnectionState =
156 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
157 const routeThreadKey =
158 environmentId !== null && threadIdRaw !== null
159 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
160 : null;
161 const selectedThreadKey =
162 selectedThread === null
163 ? null
164 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
165 const selectedThreadDetailState = useSelectedThreadDetailState();
166
167 if (environmentId === null || threadIdRaw === null) {
168 return <OpeningThreadLoadingScreen />;
169 }
170
171 // Render the full thread chrome (header, feed, composer) as soon as the
172 // thread SHELL is known — no blocking on message detail. The feed shows a
173 // loading placeholder while messages fetch, the floating pill above the
174 // composer reports loading/syncing, and the composer's connection pill
175 // reports connecting/reconnecting status.
176 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
177 return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
178 }
179
180 const stillHydrating =
181 workspaceState.isLoadingConnections ||
182 routeConnectionState === "connecting" ||
183 routeConnectionState === "reconnecting";
184
185 if (stillHydrating) {
186 return <OpeningThreadLoadingScreen />;
187 }
188
189 return <ThreadUnavailableScreen />;
190}
191
192function ThreadRouteContent(
193 props: ThreadRouteScreenProps & {
194 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
195 },
196) {
197 const { materialYouStyleLayoutActive, themeVariables } = useAppearancePreferences();
198 const headerColor = themeVariables["--color-header"];
199 const {
200 fileInspector,
201 layout,
202 panes,
203 showAuxiliaryPane,
204 toggleAuxiliaryPane,
205 togglePrimarySidebar,
206 } = useAdaptiveWorkspaceLayout();
207 const { connectionState } = useRemoteConnectionStatus();
208 const { onReconnectEnvironment } = useRemoteConnections();
209 const {
210 selectedThread,
211 selectedThreadCreation,
212 selectedThreadProject,
213 selectedEnvironmentConnection,
214 } = useThreadSelection();
215 const selectedThreadDetailState = props.selectedThreadDetailState;
216 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
217 // "Load earlier turns" header state for windowed (paginated) thread loads.
218 const loadEarlierTurns = useMemo(() => {
219 if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
220 return null;
221 }
222 return {
223 loading:
224 selectedThreadDetailState.page._tag === "Some" &&
225 selectedThreadDetailState.page.value.loadingOlder,
226 onLoadEarlier: () => {
227 requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
228 },
229 };
230 }, [selectedThread, selectedThreadDetailState]);
231 const { selectedThreadCwd } = useSelectedThreadWorktree();
232 const composer = useThreadComposerState();
233 const gitState = useSelectedThreadGitState();
234 const gitActions = useSelectedThreadGitActions();
235 const requests = useSelectedThreadRequests();
236 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
237 const navigation = useNavigation();
238 const params = props.route.params;
239 const environmentIdRaw = firstRouteParam(params.environmentId);
240 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
241 const threadId = firstRouteParam(params.threadId);
242 const routeThreadIdentity =
243 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
244 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
245 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
246 );
247 const inspectorMode = (() => {
248 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
249 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
250 return null;
251 }
252 return inspectorSelection.mode;
253 }
254 return null;
255 })();
256 useEffect(() => {
257 if (
258 fileInspector.supported &&
259 selectedThreadCwd === null &&
260 inspectorMode === null &&
261 panes.auxiliaryPaneVisible
262 ) {
263 toggleAuxiliaryPane();
264 }
265 }, [
266 fileInspector.supported,
267 inspectorMode,
268 panes.auxiliaryPaneVisible,
269 selectedThreadCwd,
270 toggleAuxiliaryPane,
271 ]);
272
273 useEffect(() => {
274 setInspectorSelection((current) => {
275 if (props.renderInspector === undefined) {
276 if (current === null || current.mode === "route") {
277 return null;
278 }
279 return { ...current, routeThreadIdentity };
280 }
281
282 if (current === null || current.mode === "route") {
283 return { routeThreadIdentity, mode: "route" };
284 }
285
286 return { ...current, routeThreadIdentity };
287 });
288 }, [props.renderInspector, routeThreadIdentity]);
289
290 useFocusEffect(
291 useCallback(() => {
292 return () => {
293 if (props.renderInspector === undefined) {
294 // Inspectors are contextual to this chat destination. Clear the
295 // hidden chat copy after a native push so returning from Files,
296 // Review, or Terminal cannot reserve an empty trailing pane.
297 setInspectorSelection(null);
298 }
299 };
300 }, [props.renderInspector]),
301 );
302 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
303 const routeConnectionState =
304 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
305 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
306 const selectedThreadWithDraftSettings = useMemo(
307 () =>
308 selectedThread
309 ? {
310 ...selectedThread,
311 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
312 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
313 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
314 }
315 : null,
316 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
317 );
318
319 /* ─── Native header theming ──────────────────────────────────────── */
320 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
321 const headerSubtitle = [
322 selectedThreadProject?.title ?? null,
323 selectedEnvironmentConnection?.environmentLabel ?? null,
324 ]
325 .filter(Boolean)
326 .join(" · ");
327 /* ─── Git status for native header trigger ───────────────────────── */
328 const gitStatus = useEnvironmentQuery(
329 selectedThread !== null && selectedThreadCwd !== null
330 ? vcsEnvironment.status({
331 environmentId: selectedThread.environmentId,
332 input: { cwd: selectedThreadCwd },
333 })
334 : null,
335 );
336 const knownTerminalSessions = useKnownTerminalSessions({
337 environmentId: selectedThread?.environmentId ?? null,
338 threadId: selectedThread?.id ?? null,
339 });
340 const terminalMenuSessions = useMemo(
341 () =>
342 buildTerminalMenuSessions({
343 knownSessions: knownTerminalSessions,
344 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
345 }),
346 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
347 );
348 const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
349 const handleReconnectEnvironment = useCallback(() => {
350 if (!environmentId) {
351 return;
352 }
353 onReconnectEnvironment(environmentId);
354 }, [environmentId, onReconnectEnvironment]);
355
356 /* ─── Git action progress (for overlay banner) ──────────────────── */
357 const gitActionProgressTarget = useMemo(
358 () => ({
359 environmentId: selectedThread?.environmentId ?? null,
360 cwd: selectedThreadCwd,
361 }),
362 [selectedThread?.environmentId, selectedThreadCwd],
363 );
364 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
365
366 const handleOpenGitInspector = useCallback(() => {
367 if (!fileInspector.supported) {
368 if (selectedThread === null) {
369 return;
370 }
371 navigation.navigate("GitOverview", {
372 environmentId: String(selectedThread.environmentId),
373 threadId: String(selectedThread.id),
374 });
375 return;
376 }
377 setInspectorSelection({ routeThreadIdentity, mode: "git" });
378 showAuxiliaryPane("inspector");
379 }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
380 const handleOpenFilesInspector = useCallback(() => {
381 if (selectedThread === null || selectedThreadCwd === null) {
382 return;
383 }
384 if (!fileInspector.supported) {
385 navigation.navigate("ThreadFiles", {
386 environmentId: String(selectedThread.environmentId),
387 threadId: String(selectedThread.id),
388 });
389 return;
390 }
391 setInspectorSelection({
392 routeThreadIdentity,
393 mode: props.renderInspector === undefined ? "files" : "route",
394 });
395 showAuxiliaryPane("inspector");
396 }, [
397 fileInspector.supported,
398 navigation,
399 props.renderInspector,
400 routeThreadIdentity,
401 selectedThread,
402 selectedThreadCwd,
403 showAuxiliaryPane,
404 ]);
405 const inspectorToggleActionRef = useRef({
406 inspectorMode,
407 openFilesInspector: handleOpenFilesInspector,
408 toggleAuxiliaryPane,
409 });
410 inspectorToggleActionRef.current = {
411 inspectorMode,
412 openFilesInspector: handleOpenFilesInspector,
413 toggleAuxiliaryPane,
414 };
415 const handleToggleInspector = useCallback(() => {
416 const action = inspectorToggleActionRef.current;
417 if (action.inspectorMode === null) {
418 action.openFilesInspector();
419 return;
420 }
421 action.toggleAuxiliaryPane();
422 }, []);
423 const handleSelectInspectorFile = useCallback(
424 (path: string) => {
425 if (selectedThread === null) {
426 return;
427 }
428 const params = {
429 environmentId: String(selectedThread.environmentId),
430 threadId: String(selectedThread.id),
431 path: path.split("/").filter((segment) => segment.length > 0),
432 };
433 if (fileInspector.supported) {
434 navigation.navigate("ThreadFile", params);
435 return;
436 }
437 navigation.navigate("ThreadFile", params);
438 },
439 [fileInspector.supported, navigation, selectedThread],
440 );
441 // The workspace inspector column spans the full window height. On iOS the
442 // panes bring their own nested native headers (which underlap the status
443 // bar); elsewhere the pane content pads itself below the top inset.
444 const safeAreaInsets = useSafeAreaInsets();
445 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
446 const GitInspector = useCallback(
447 () => (
448 <GitOverviewSheet
449 headerInset={inspectorHeaderInset}
450 presentation="inspector"
451 route={{ params: props.route.params }}
452 />
453 ),
454 [inspectorHeaderInset, props.route.params],
455 );
456 const FilesInspector = useCallback(
457 () =>
458 selectedThread !== null && selectedThreadCwd !== null ? (
459 <ThreadFileNavigatorPane
460 cwd={selectedThreadCwd}
461 environmentId={selectedThread.environmentId}
462 headerInset={inspectorHeaderInset}
463 projectName={selectedThreadProject?.title ?? "Files"}
464 selectedPath={null}
465 onSelectFile={handleSelectInspectorFile}
466 />
467 ) : null,
468 [
469 handleSelectInspectorFile,
470 inspectorHeaderInset,
471 selectedThread,
472 selectedThreadCwd,
473 selectedThreadProject?.title,
474 ],
475 );
476 const RouteInspector = useCallback(
477 () => props.renderInspector?.(inspectorHeaderInset),
478 [inspectorHeaderInset, props.renderInspector],
479 );
480 const renderInspectorStack = useCallback(
481 () =>
482 inspectorMode === null ? null : (
483 <ThreadInspectorContentStack
484 Files={FilesInspector}
485 Git={GitInspector}
486 mode={inspectorMode}
487 Route={props.renderInspector ? RouteInspector : undefined}
488 />
489 ),
490 [FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector],
491 );
492 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
493 // Hand the inspector to the workspace so it renders beside the navigator,
494 // outside this screen's native header — the terminal/git/files toolbar
495 // stays anchored to the chat pane instead of floating above the inspector.
496 useRegisterWorkspaceInspector(activeInspectorRenderer);
497
498 const handleOpenConnectionEditor = useCallback(() => {
499 void navigation.navigate("Connections");
500 }, [navigation]);
501 const handleStopThread = useCallback(() => {
502 if (
503 !selectedThread ||
504 (selectedThread.session?.status !== "running" &&
505 selectedThread.session?.status !== "starting")
506 ) {
507 return;
508 }
509 return interruptThreadTurn({
510 environmentId: selectedThread.environmentId,
511 input: {
512 threadId: selectedThread.id,
513 ...(selectedThread.session.activeTurnId
514 ? { turnId: selectedThread.session.activeTurnId }
515 : {}),
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
650 ? resolveProjectScripts(
651 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
652 selectedThreadProject,
653 )
654 : [],
655 terminalSessions: terminalMenuSessions,
656 showDirectFileControl: layout.usesSplitView,
657 onOpenTerminal: handleOpenTerminal,
658 onOpenNewTerminal: handleOpenNewTerminal,
659 onRunProjectScript: handleRunProjectScript,
660 onPull: gitActions.onPullSelectedThreadBranch,
661 onRunAction: gitActions.onRunSelectedThreadGitAction,
662 };
663 const threadCenterHeaderItems = useThreadGitCenterHeaderItems(threadGitControlProps);
664 const compactRightHeaderItems = useThreadGitRightHeaderItems(threadGitControlProps);
665 const splitLeftHeaderItems = useMemo<NativeHeaderItems>(
666 () => [
667 {
668 // Match Mail's split-view detail toolbar: the first detail action sits
669 // inside the content pane, not flush against the sidebar divider.
670 spacing: 18,
671 type: "spacing" as const,
672 },
673 ...(props.onReturnToThread
674 ? [
675 withNativeGlassHeaderItem({
676 accessibilityLabel: "Return to chat",
677 icon: { name: "chevron.left", type: "sfSymbol" as const },
678 identifier: "thread-left-return",
679 onPress: props.onReturnToThread,
680 type: "button" as const,
681 }),
682 ]
683 : []),
684 withNativeGlassHeaderItem({
685 accessibilityLabel: panes.primarySidebarVisible
686 ? "Maximize content"
687 : "Show thread sidebar",
688 icon: {
689 name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",
690 type: "sfSymbol" as const,
691 },
692 identifier: "thread-left-sidebar",
693 onPress: togglePrimarySidebar,
694 type: "button" as const,
695 }),
696 withNativeGlassHeaderItem({
697 accessibilityLabel: "New task",
698 icon: { name: "square.and.pencil", type: "sfSymbol" as const },
699 identifier: "thread-left-new-task",
700 onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),
701 type: "button" as const,
702 }),
703 ],
704 [panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
705 );
706 const androidHeaderActions = useMemo<ReadonlyArray<AndroidHeaderAction>>(() => {
707 if (Platform.OS !== "android") return [];
708
709 const actions: AndroidHeaderAction[] = [];
710 if (props.onReturnToThread) {
711 actions.push({
712 accessibilityLabel: "Return to chat",
713 icon: "chevron.left",
714 onPress: props.onReturnToThread,
715 });
716 }
717 if (selectedThreadCwd !== null) {
718 actions.push({
719 accessibilityLabel: "Open files",
720 icon: "folder",
721 onPress: handleOpenFilesInspector,
722 });
723 }
724 if (selectedThreadProject?.workspaceRoot) {
725 actions.push({
726 accessibilityLabel: "Open terminal",
727 icon: "terminal",
728 onPress: () => handleOpenTerminal(null),
729 });
730 }
731 actions.push({
732 accessibilityLabel: "Open git controls",
733 icon: "point.topleft.down.curvedto.point.bottomright.up",
734 onPress: handleOpenGitInspector,
735 });
736 if (fileInspector.supported && selectedThreadCwd !== null) {
737 actions.push({
738 accessibilityLabel: "Toggle inspector",
739 icon: "sidebar.right",
740 onPress: handleToggleInspector,
741 });
742 }
743 return actions;
744 }, [
745 fileInspector.supported,
746 handleOpenFilesInspector,
747 handleOpenTerminal,
748 handleOpenGitInspector,
749 handleToggleInspector,
750 props.onReturnToThread,
751 selectedThreadCwd,
752 selectedThreadProject?.workspaceRoot,
753 ]);
754
755 const handleEditFailedCreation = useCallback(async () => {
756 const creation = selectedThreadCreation?.message;
757 if (!creation?.creation || routeThreadIdentity === null) {
758 return;
759 }
760 // The drain restored the prompt and attachments into the recovery draft
761 // the rejected creation owns. Open that draft by id: without it the sheet
762 // mints a fresh empty one and the restored content is unreachable.
763 try {
764 await recoverFailedThreadDraft(creation);
765 } catch (error) {
766 Alert.alert(
767 "Could not restore draft",
768 error instanceof Error ? error.message : String(error),
769 );
770 return;
771 }
772 clearPendingThreadCreationOutcome(routeThreadIdentity);
773 navigation.dispatch(
774 StackActions.replace("NewTaskSheet", {
775 screen: "NewTaskDraft",
776 params: {
777 draftId: restoredNewTaskDraftKey(creation.messageId),
778 environmentId: String(creation.environmentId),
779 projectId: String(creation.creation.projectId),
780 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
781 },
782 }),
783 );
784 }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
785 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
786 if (selectedThreadCreation === null) {
787 return null;
788 }
789 if (selectedThreadCreation.outcome?.kind === "failed") {
790 return {
791 kind: "failed",
792 reason: selectedThreadCreation.outcome.reason,
793 onEditTask: handleEditFailedCreation,
794 };
795 }
796 return {
797 kind: "preparing",
798 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
799 };
800 })();
801 // Deep links / cold starts land with Thread as the ONLY route, where the
802 // native back button does not render. Provide an explicit Home escape for
803 // that case; when history exists the native back button is used instead.
804 const canGoBack = navigation.canGoBack();
805 const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
806 () => [
807 withNativeGlassHeaderItem({
808 accessibilityLabel: "Go to threads list",
809 icon: { name: "list.bullet", type: "sfSymbol" as const },
810 identifier: "thread-left-home",
811 onPress: () => navigation.dispatch(StackActions.replace("Home")),
812 type: "button" as const,
813 }),
814 ],
815 [navigation],
816 );
817
818 if (!environmentId || !threadId) {
819 return <OpeningThreadLoadingScreen />;
820 }
821
822 if (!selectedThread) {
823 return <OpeningThreadLoadingScreen />;
824 }
825
826 // A queued creation renders as ready content: its prompt is the whole
827 // conversation until the server creates the thread. The subscription's
828 // not-found error for that window is expected, not a load failure.
829 const contentPresentation =
830 creationState !== null
831 ? { kind: "ready" as const }
832 : projectThreadContentPresentation({
833 hasDetail: selectedThreadDetail !== null,
834 detailError: Option.getOrNull(selectedThreadDetailState.error),
835 detailDeleted: selectedThreadDetailState.status === "deleted",
836 connectionState: routeConnectionState,
837 });
838 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
839 const renderThreadRouteBody = (showActionControls: boolean) => (
840 <>
841 <ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
842
843 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
844
845 <View
846 className={materialYouStyleLayoutActive ? "flex-1 bg-thread-canvas" : "flex-1 bg-screen"}
847 style={
848 materialYouStyleLayoutActive
849 ? {
850 borderTopLeftRadius: 28,
851 borderTopRightRadius: 28,
852 marginRight: layout.usesSplitView ? 8 : 0,
853 overflow: "hidden",
854 }
855 : undefined
856 }
857 >
858 <ThreadDetailScreen
859 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
860 contentPresentation={contentPresentation}
861 screenTone={connectionTone(routeConnectionState)}
862 connectionError={routeConnectionError}
863 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
864 feedbackSubmissions={composer.feedbackSubmissions}
865 onDismissFeedback={composer.dismissFeedback}
866 selectedThreadFeed={composer.selectedThreadFeed}
867 activeWorkStartedAt={composer.activeWorkStartedAt}
868 isCompacting={composer.isCompacting}
869 creationState={creationState}
870 activePendingApproval={requests.activePendingApproval}
871 respondingApprovalId={requests.respondingApprovalId}
872 activePendingUserInput={requests.activePendingUserInput}
873 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
874 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
875 respondingUserInputId={requests.respondingUserInputId}
876 draftMessage={composer.draftMessage}
877 draftAttachments={composer.draftAttachments}
878 connectionStateLabel={routeConnectionState}
879 threadSyncStatus={selectedThreadDetailState.status}
880 loadEarlier={loadEarlierTurns}
881 environmentId={selectedThread.environmentId}
882 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
883 threadCwd={selectedThreadCwd}
884 selectedThreadQueueCount={composer.selectedThreadQueueCount}
885 queuedMessages={composer.selectedThreadQueuedMessages}
886 dispatchingMessageId={composer.dispatchingQueuedMessageId}
887 layoutVariant={layout.variant}
888 usesAutomaticContentInsets={usesNativeHeaderGlass}
889 onOpenConnectionEditor={handleOpenConnectionEditor}
890 onChangeDraftMessage={composer.onChangeDraftMessage}
891 onPickDraftMedia={composer.onPickDraftMedia}
892 onPickDraftFiles={composer.onPickDraftFiles}
893 onNativePasteImages={composer.onNativePasteImages}
894 onRemoveDraftImage={composer.onRemoveDraftImage}
895 serverConfig={serverConfig}
896 onStopThread={handleStopThread}
897 onSendMessage={composer.onSendMessage}
898 onReconnectEnvironment={handleReconnectEnvironment}
899 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
900 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
901 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
902 onRespondToApproval={requests.onRespondToApproval}
903 onSelectUserInputOption={requests.onSelectUserInputOption}
904 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
905 onSubmitUserInput={requests.onSubmitUserInput}
906 onDismissUserInput={requests.onDismissUserInput}
907 />
908 </View>
909 </>
910 );
911
912 return (
913 <>
914 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
915 <NativeStackScreenOptions
916 optionsVersion={threadGitControlProps.projectScripts}
917 options={{
918 // Android draws its own in-flow header (AndroidScreenHeader below);
919 // the native stack header stays iOS-only.
920 headerShown: Platform.OS !== "android",
921 headerTitle: selectedThread.title,
922 headerTitleStyle: usesNativeHeaderGlass
923 ? {
924 fontSize: 17,
925 fontWeight: "800",
926 }
927 : undefined,
928 title: selectedThread.title,
929 headerBackVisible: !layout.usesSplitView,
930 // Compact uses the NATIVE back button when a previous route exists;
931 // deep links / cold starts get an explicit Home button instead.
932 // Split view always uses its custom left items.
933 unstable_headerLeftItems:
934 Platform.OS === "ios"
935 ? layout.usesSplitView
936 ? () => splitLeftHeaderItems
937 : canGoBack
938 ? undefined
939 : () => compactHomeHeaderItems
940 : undefined,
941 // Search lives in the persistent sidebar, so the split header keeps
942 // the git controls on the RIGHT (no center items — center space is
943 // reserved for future breadcrumbs/status).
944 unstable_headerRightItems:
945 Platform.OS === "ios"
946 ? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
947 : undefined,
948 unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
949 contentStyle:
950 Platform.OS === "android" && materialYouStyleLayoutActive
951 ? { backgroundColor: headerColor }
952 : undefined,
953 }}
954 />
955
956 {Platform.OS === "android" ? (
957 <AndroidScreenHeader
958 title={selectedThread.title}
959 subtitle={headerSubtitle}
960 onBack={
961 layout.usesSplitView
962 ? undefined
963 : () => {
964 // A deep link or cold start has no previous route; Home is the way out.
965 // Read the history at press time: it changes without re-rendering this screen.
966 if (navigation.canGoBack()) navigation.goBack();
967 else navigation.dispatch(StackActions.replace("Home"));
968 }
969 }
970 actions={androidHeaderActions}
971 hideBottomBorder={materialYouStyleLayoutActive}
972 />
973 ) : null}
974
975 {/* Android surfaces the git/files/inspector actions in its in-flow
976 header above, so the fallback action toolbar stays iOS-only. */}
977 {renderThreadRouteBody(
978 Platform.OS !== "android" && !layout.usesSplitView && !usesNativeHeaderGlass,
979 )}
980 </>
981 );
982}