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

ThreadRouteScreen.tsx

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