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

ThreadRouteScreen.tsx

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