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 projectScriptCwd,
18 projectScriptRuntimeEnv,
19 resolveProjectScripts,
20} from "@t3tools/shared/projectScripts";
21import { Alert, Platform, ScrollView, View } from "react-native";
22import { useSafeAreaInsets } from "react-native-safe-area-context";
23import { useWorkspaceState } from "../../state/workspace";
24import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
25import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
26import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
27import { useEnvironmentQuery } from "../../state/query";
28import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
29import { vcsEnvironment } from "../../state/vcs";
30
31import { EmptyState } from "../../components/EmptyState";
32import {
33 AndroidScreenHeader,
34 type AndroidHeaderAction,
35} from "../../components/AndroidScreenHeader";
36import { LoadingScreen } from "../../components/LoadingScreen";
37import { scopedThreadKey } from "../../lib/scopedEntities";
38import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
39import { connectionTone } from "../connection/connectionTone";
40
41import {
42 useRemoteConnections,
43 useRemoteConnectionStatus,
44 useRemoteEnvironmentRuntime,
45} from "../../state/use-remote-environment-registry";
46import { useKnownTerminalSessions } from "../../state/use-terminal-session";
47import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
48import { useThreadSelection } from "../../state/use-thread-selection";
49import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
50import {
51 buildTerminalMenuSessions,
52 nextOpenTerminalId,
53 resolveProjectScriptTerminalId,
54} from "../terminal/terminalMenu";
55import {
56 resolvePreferredThreadWorktreePath,
57 stagePendingTerminalLaunch,
58} from "../terminal/terminalLaunchContext";
59import { terminalDebugLog } from "../terminal/terminalDebugLog";
60import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
61import {
62 ThreadGitControls,
63 useThreadGitCenterHeaderItems,
64 useThreadGitRightHeaderItems,
65} from "./ThreadGitControls";
66import { GitOverviewSheet } from "./git/GitOverviewSheet";
67import { useAtomCommand } from "../../state/use-atom-command";
68import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
69import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
70import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
71import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
72import { useThreadComposerState } from "../../state/use-thread-composer-state";
73import { threadEnvironment } from "../../state/threads";
74import { projectThreadContentPresentation } from "./threadContentPresentation";
75import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
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;
91}
92
93type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;
94
95function InspectorPaneRoleActivation() {
96 useAdaptiveWorkspacePaneRole("inspector");
97 return null;
98}
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;
106}
107
108function OpeningThreadLoadingScreen() {
109 return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
110}
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;
120}
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 );
140}
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 />;
186}
187
188function ThreadRouteContent(
189 props: ThreadRouteScreenProps & {
190 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
191 },
192) {
193 const { materialYouStyleLayoutActive, themeVariables } = useAppearancePreferences();
194 const headerColor = themeVariables["--color-header"];
195 const {
196 fileInspector,
197 layout,
198 panes,
199 showAuxiliaryPane,
200 toggleAuxiliaryPane,
201 togglePrimarySidebar,
202 } = useAdaptiveWorkspaceLayout();
203 const { connectionState } = useRemoteConnectionStatus();
204 const { onReconnectEnvironment } = useRemoteConnections();
205 const {
206 selectedThread,
207 selectedThreadCreation,
208 selectedThreadProject,
209 selectedEnvironmentConnection,
210 } = useThreadSelection();
211 const selectedThreadDetailState = props.selectedThreadDetailState;
212 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
213 const { selectedThreadCwd } = useSelectedThreadWorktree();
214 const composer = useThreadComposerState();
215 const gitState = useSelectedThreadGitState();
216 const gitActions = useSelectedThreadGitActions();
217 const requests = useSelectedThreadRequests();
218 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
219 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
220 label: "load earlier thread history",
221 reportFailure: false,
222 });
223 const historyControls = useMemo(() => {
224 const history = selectedThreadDetailState.history;
225 if (!selectedThread) {
226 return undefined;
227 }
228 if (!history.hasMoreHistory && history.error === null) {
229 return undefined;
230 }
231 return {
232 hasMoreHistory: history.hasMoreHistory,
233 loading: history.loading,
234 error: history.error,
235 onLoadEarlier: () => {
236 void loadEarlierHistory({
237 environmentId: selectedThread.environmentId,
238 input: { threadId: selectedThread.id },
239 });
240 },
241 };
242 }, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]);
243 const navigation = useNavigation();
244 const params = props.route.params;
245 const environmentIdRaw = firstRouteParam(params.environmentId);
246 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
247 const threadId = firstRouteParam(params.threadId);
248 const routeThreadIdentity =
249 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
250 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
251 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
252 );
253 const inspectorMode = (() => {
254 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
255 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
256 return null;
257 }
258 return inspectorSelection.mode;
259 }
260 return null;
261 })();
262 useEffect(() => {
263 if (
264 fileInspector.supported &&
265 selectedThreadCwd === null &&
266 inspectorMode === null &&
267 panes.auxiliaryPaneVisible
268 ) {
269 toggleAuxiliaryPane();
270 }
271 }, [
272 fileInspector.supported,
273 inspectorMode,
274 panes.auxiliaryPaneVisible,
275 selectedThreadCwd,
276 toggleAuxiliaryPane,
277 ]);
278
279 useEffect(() => {
280 setInspectorSelection((current) => {
281 if (props.renderInspector === undefined) {
282 if (current === null || current.mode === "route") {
283 return null;
284 }
285 return { ...current, routeThreadIdentity };
286 }
287
288 if (current === null || current.mode === "route") {
289 return { routeThreadIdentity, mode: "route" };
290 }
291
292 return { ...current, routeThreadIdentity };
293 });
294 }, [props.renderInspector, routeThreadIdentity]);
295
296 useFocusEffect(
297 useCallback(() => {
298 return () => {
299 if (props.renderInspector === undefined) {
300 // Inspectors are contextual to this chat destination. Clear the
301 // hidden chat copy after a native push so returning from Files,
302 // Review, or Terminal cannot reserve an empty trailing pane.
303 setInspectorSelection(null);
304 }
305 };
306 }, [props.renderInspector]),
307 );
308 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
309 const routeConnectionState =
310 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
311 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
312 const selectedThreadWithDraftSettings = useMemo(
313 () =>
314 selectedThread
315 ? {
316 ...selectedThread,
317 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
318 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
319 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
320 }
321 : null,
322 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
323 );
324
325 /* ─── Native header theming ──────────────────────────────────────── */
326 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
327 const headerSubtitle = [
328 selectedThreadProject?.title ?? null,
329 selectedEnvironmentConnection?.environmentLabel ?? null,
330 ]
331 .filter(Boolean)
332 .join(" · ");
333 /* ─── Git status for native header trigger ───────────────────────── */
334 const gitStatus = useEnvironmentQuery(
335 selectedThread !== null && selectedThreadCwd !== null
336 ? vcsEnvironment.status({
337 environmentId: selectedThread.environmentId,
338 input: { cwd: selectedThreadCwd },
339 })
340 : null,
341 );
342 const knownTerminalSessions = useKnownTerminalSessions({
343 environmentId: selectedThread?.environmentId ?? null,
344 threadId: selectedThread?.id ?? null,
345 });
346 const terminalMenuSessions = useMemo(
347 () =>
348 buildTerminalMenuSessions({
349 knownSessions: knownTerminalSessions,
350 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
351 }),
352 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
353 );
354 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
355 const handleReconnectEnvironment = useCallback(() => {
356 if (!environmentId) {
357 return;
358 }
359 onReconnectEnvironment(environmentId);
360 }, [environmentId, onReconnectEnvironment]);
361
362 /* ─── Git action progress (for overlay banner) ──────────────────── */
363 const gitActionProgressTarget = useMemo(
364 () => ({
365 environmentId: selectedThread?.environmentId ?? null,
366 cwd: selectedThreadCwd,
367 }),
368 [selectedThread?.environmentId, selectedThreadCwd],
369 );
370 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
371
372 const handleOpenGitInspector = useCallback(() => {
373 if (!fileInspector.supported) {
374 if (selectedThread === null) {
375 return;
376 }
377 navigation.navigate("GitOverview", {
378 environmentId: String(selectedThread.environmentId),
379 threadId: String(selectedThread.id),
380 });
381 return;
382 }
383 setInspectorSelection({ routeThreadIdentity, mode: "git" });
384 showAuxiliaryPane("inspector");
385 }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
386 const handleOpenFilesInspector = useCallback(() => {
387 if (selectedThread === null || selectedThreadCwd === null) {
388 return;
389 }
390 if (!fileInspector.supported) {
391 navigation.navigate("ThreadFiles", {
392 environmentId: String(selectedThread.environmentId),
393 threadId: String(selectedThread.id),
394 });
395 return;
396 }
397 setInspectorSelection({
398 routeThreadIdentity,
399 mode: props.renderInspector === undefined ? "files" : "route",
400 });
401 showAuxiliaryPane("inspector");
402 }, [
403 fileInspector.supported,
404 navigation,
405 props.renderInspector,
406 routeThreadIdentity,
407 selectedThread,
408 selectedThreadCwd,
409 showAuxiliaryPane,
410 ]);
411 const inspectorToggleActionRef = useRef({
412 inspectorMode,
413 openFilesInspector: handleOpenFilesInspector,
414 toggleAuxiliaryPane,
415 });
416 inspectorToggleActionRef.current = {
417 inspectorMode,
418 openFilesInspector: handleOpenFilesInspector,
419 toggleAuxiliaryPane,
420 };
421 const handleToggleInspector = useCallback(() => {
422 const action = inspectorToggleActionRef.current;
423 if (action.inspectorMode === null) {
424 action.openFilesInspector();
425 return;
426 }
427 action.toggleAuxiliaryPane();
428 }, []);
429 const handleSelectInspectorFile = useCallback(
430 (path: string) => {
431 if (selectedThread === null) {
432 return;
433 }
434 const params = {
435 environmentId: String(selectedThread.environmentId),
436 threadId: String(selectedThread.id),
437 path: path.split("/").filter((segment) => segment.length > 0),
438 };
439 if (fileInspector.supported) {
440 navigation.navigate("ThreadFile", params);
441 return;
442 }
443 navigation.navigate("ThreadFile", params);
444 },
445 [fileInspector.supported, navigation, selectedThread],
446 );
447 // The workspace inspector column spans the full window height. On iOS the
448 // panes bring their own nested native headers (which underlap the status
449 // bar); elsewhere the pane content pads itself below the top inset.
450 const safeAreaInsets = useSafeAreaInsets();
451 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
452 const GitInspector = useCallback(
453 () => (
454 <GitOverviewSheet
455 headerInset={inspectorHeaderInset}
456 presentation="inspector"
457 route={{ params: props.route.params }}
458 />
459 ),
460 [inspectorHeaderInset, props.route.params],
461 );
462 const FilesInspector = useCallback(
463 () =>
464 selectedThread !== null && selectedThreadCwd !== null ? (
465 <ThreadFileNavigatorPane
466 cwd={selectedThreadCwd}
467 environmentId={selectedThread.environmentId}
468 headerInset={inspectorHeaderInset}
469 projectName={selectedThreadProject?.title ?? "Files"}
470 selectedPath={null}
471 onSelectFile={handleSelectInspectorFile}
472 />
473 ) : null,
474 [
475 handleSelectInspectorFile,
476 inspectorHeaderInset,
477 selectedThread,
478 selectedThreadCwd,
479 selectedThreadProject?.title,
480 ],
481 );
482 const RouteInspector = useCallback(
483 () => props.renderInspector?.(inspectorHeaderInset),
484 [inspectorHeaderInset, props.renderInspector],
485 );
486 const renderInspectorStack = useCallback(
487 () =>
488 inspectorMode === null ? null : (
489 <ThreadInspectorContentStack
490 Files={FilesInspector}
491 Git={GitInspector}
492 mode={inspectorMode}
493 Route={props.renderInspector ? RouteInspector : undefined}
494 />
495 ),
496 [FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector],
497 );
498 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
499 // Hand the inspector to the workspace so it renders beside the navigator,
500 // outside this screen's native header — the terminal/git/files toolbar
501 // stays anchored to the chat pane instead of floating above the inspector.
502 useRegisterWorkspaceInspector(activeInspectorRenderer);
503
504 const handleOpenConnectionEditor = useCallback(() => {
505 void navigation.navigate("Connections");
506 }, [navigation]);
507 const handleStopThread = useCallback(() => {
508 if (!selectedThread || composer.interruptibleRunId === null) {
509 return;
510 }
511 return interruptThreadTurn({
512 environmentId: selectedThread.environmentId,
513 input: {
514 threadId: selectedThread.id,
515 runId: composer.interruptibleRunId,
516 },
517 });
518 }, [composer.interruptibleRunId, 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 activityRun={composer.selectedThreadActivityRun}
868 activeWorkStartedAt={composer.activeWorkStartedAt}
869 isCompacting={composer.isCompacting}
870 creationState={creationState}
871 activePendingApproval={requests.activePendingApproval}
872 respondingApprovalId={requests.respondingApprovalId}
873 activePendingUserInput={requests.activePendingUserInput}
874 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
875 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
876 respondingUserInputId={requests.respondingUserInputId}
877 draftMessage={composer.draftMessage}
878 draftAttachments={composer.draftAttachments}
879 connectionStateLabel={routeConnectionState}
880 threadSyncStatus={selectedThreadDetailState.status}
881 historyControls={historyControls}
882 activeThreadBusy={composer.activeThreadBusy}
883 canStopThread={composer.interruptibleRunId !== null}
884 environmentId={selectedThread.environmentId}
885 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
886 threadCwd={selectedThreadCwd}
887 selectedThreadQueueCount={composer.selectedThreadQueueCount}
888 queuedMessages={composer.selectedThreadQueuedMessages}
889 dispatchingMessageId={composer.dispatchingQueuedMessageId}
890 layoutVariant={layout.variant}
891 usesAutomaticContentInsets={usesNativeHeaderGlass}
892 onOpenConnectionEditor={handleOpenConnectionEditor}
893 onChangeDraftMessage={composer.onChangeDraftMessage}
894 onPickDraftMedia={composer.onPickDraftMedia}
895 onPickDraftFiles={composer.onPickDraftFiles}
896 onNativePasteImages={composer.onNativePasteImages}
897 onRemoveDraftImage={composer.onRemoveDraftImage}
898 serverConfig={serverConfig}
899 onStopThread={handleStopThread}
900 onSendMessage={composer.onSendMessage}
901 onReconnectEnvironment={handleReconnectEnvironment}
902 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
903 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
904 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
905 onRespondToApproval={requests.onRespondToApproval}
906 onSelectUserInputOption={requests.onSelectUserInputOption}
907 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
908 onSubmitUserInput={requests.onSubmitUserInput}
909 onDismissUserInput={requests.onDismissUserInput}
910 />
911 </View>
912 </>
913 );
914
915 return (
916 <>
917 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
918 <NativeStackScreenOptions
919 optionsVersion={threadGitControlProps.projectScripts}
920 options={{
921 // Android draws its own in-flow header (AndroidScreenHeader below);
922 // the native stack header stays iOS-only.
923 headerShown: Platform.OS !== "android",
924 headerTitle: selectedThread.title,
925 headerTitleStyle: usesNativeHeaderGlass
926 ? {
927 fontSize: 17,
928 fontWeight: "800",
929 }
930 : undefined,
931 title: selectedThread.title,
932 headerBackVisible: !layout.usesSplitView,
933 // Compact uses the NATIVE back button when a previous route exists;
934 // deep links / cold starts get an explicit Home button instead.
935 // Split view always uses its custom left items.
936 unstable_headerLeftItems:
937 Platform.OS === "ios"
938 ? layout.usesSplitView
939 ? () => splitLeftHeaderItems
940 : canGoBack
941 ? undefined
942 : () => compactHomeHeaderItems
943 : undefined,
944 // Search lives in the persistent sidebar, so the split header keeps
945 // the git controls on the RIGHT (no center items — center space is
946 // reserved for future breadcrumbs/status).
947 unstable_headerRightItems:
948 Platform.OS === "ios"
949 ? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
950 : undefined,
951 unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
952 contentStyle:
953 Platform.OS === "android" && materialYouStyleLayoutActive
954 ? { backgroundColor: headerColor }
955 : undefined,
956 }}
957 />
958
959 {Platform.OS === "android" ? (
960 <AndroidScreenHeader
961 title={selectedThread.title}
962 subtitle={headerSubtitle}
963 onBack={layout.usesSplitView ? undefined : () => navigation.goBack()}
964 actions={androidHeaderActions}
965 hideBottomBorder={materialYouStyleLayoutActive}
966 />
967 ) : null}
968
969 {/* Android surfaces the git/files/inspector actions in its in-flow
970 header above, so the fallback action toolbar stays iOS-only. */}
971 {renderThreadRouteBody(
972 Platform.OS !== "android" && !layout.usesSplitView && !usesNativeHeaderGlass,
973 )}
974 </>
975 );
976}