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

ThreadRouteScreen.tsx

1,031 lines38.5 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";
35​
36import { EmptyState } from "../../components/EmptyState";
37import {
38 AndroidScreenHeader,
39 type AndroidHeaderAction,
40} from "../../components/AndroidScreenHeader";
41import { LoadingScreen } from "../../components/LoadingScreen";
42import { scopedThreadKey } from "../../lib/scopedEntities";
43import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
44import { connectionTone } from "../connection/connectionTone";
45​
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 { materialYouStyleLayoutActive, 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 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 // A worktree bootstrap records a running setup on the thread before its
817 // turn, so a thread opened from another device (or after a restart) shows
818 // the same preparing state the sending client does. A starting session is
819 // not enough on its own: an ordinary first turn projects one too.
820 const awaitingBootstrapTurn = useMemo(
821 () =>
822 selectedThreadDetail !== null &&
823 selectedThreadDetail.latestTurn === null &&
824 selectedThreadDetail.activities.some(
825 (activity) =>
826 activity.kind === "worktree-setup" &&
827 typeof activity.payload === "object" &&
828 activity.payload !== null &&
829 (activity.payload as { phase?: unknown }).phase === "running",
830 ),
831 [selectedThreadDetail],
832 );
833 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
834 if (selectedThreadCreation === null) {
835 return awaitingBootstrapTurn ? { kind: "preparing", preparingWorktree: true } : null;
836 }
837 if (selectedThreadCreation.outcome?.kind === "failed") {
838 return {
839 kind: "failed",
840 reason: selectedThreadCreation.outcome.reason,
841 onEditTask: handleEditFailedCreation,
842 };
843 }
844 return {
845 kind: "preparing",
846 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
847 };
848 })();
849 // Deep links / cold starts land with Thread as the ONLY route, where the
850 // native back button does not render. Provide an explicit Home escape for
851 // that case; when history exists the native back button is used instead.
852 const canGoBack = navigation.canGoBack();
853 const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
854 () => [
855 withNativeGlassHeaderItem({
856 accessibilityLabel: "Go to threads list",
857 icon: { name: "list.bullet", type: "sfSymbol" as const },
858 identifier: "thread-left-home",
859 onPress: () => navigation.dispatch(StackActions.replace("Home")),
860 type: "button" as const,
861 }),
862 ],
863 [navigation],
864 );
865​
866 if (!environmentId || !threadId) {
867 return <OpeningThreadLoadingScreen />;
868 }
869​
870 if (!selectedThread) {
871 return <OpeningThreadLoadingScreen />;
872 }
873​
874 // A queued creation renders as ready content: its prompt is the whole
875 // conversation until the server creates the thread. The subscription's
876 // not-found error for that window is expected, not a load failure.
877 const contentPresentation =
878 creationState !== null
879 ? { kind: "ready" as const }
880 : projectThreadContentPresentation({
881 hasDetail: selectedThreadDetail !== null,
882 detailError: Option.getOrNull(selectedThreadDetailState.error),
883 detailDeleted: selectedThreadDetailState.status === "deleted",
884 connectionState: routeConnectionState,
885 });
886 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
887 const renderThreadRouteBody = (showActionControls: boolean) => (
888 <>
889 <ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
890​
891 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
892​
893 <View
894 className={materialYouStyleLayoutActive ? "flex-1 bg-thread-canvas" : "flex-1 bg-screen"}
895 style={
896 materialYouStyleLayoutActive
897 ? {
898 borderTopLeftRadius: 28,
899 borderTopRightRadius: 28,
900 marginRight: layout.usesSplitView ? 8 : 0,
901 overflow: "hidden",
902 }
903 : undefined
904 }
905 >
906 <ThreadDetailScreen
907 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
908 contentPresentation={contentPresentation}
909 screenTone={connectionTone(routeConnectionState)}
910 connectionError={routeConnectionError}
911 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
912 feedbackSubmissions={composer.feedbackSubmissions}
913 onDismissFeedback={composer.dismissFeedback}
914 selectedThreadFeed={composer.selectedThreadFeed}
915 activeWorkStartedAt={composer.activeWorkStartedAt}
916 isCompacting={composer.isCompacting}
917 creationState={creationState}
918 activePendingApproval={requests.activePendingApproval}
919 respondingApprovalId={requests.respondingApprovalId}
920 activePendingUserInput={requests.activePendingUserInput}
921 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
922 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
923 respondingUserInputId={requests.respondingUserInputId}
924 draftMessage={composer.draftMessage}
925 draftAttachments={composer.draftAttachments}
926 connectionStateLabel={routeConnectionState}
927 threadSyncStatus={selectedThreadDetailState.status}
928 loadEarlier={loadEarlierTurns}
929 environmentId={selectedThread.environmentId}
930 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
931 threadCwd={selectedThreadCwd}
932 selectedThreadQueueCount={composer.selectedThreadQueueCount}
933 queuedMessages={composer.selectedThreadQueuedMessages}
934 dispatchingMessageId={composer.dispatchingQueuedMessageId}
935 layoutVariant={layout.variant}
936 usesAutomaticContentInsets={usesNativeHeaderGlass}
937 onOpenConnectionEditor={handleOpenConnectionEditor}
938 onChangeDraftMessage={composer.onChangeDraftMessage}
939 onPickDraftMedia={composer.onPickDraftMedia}
940 onPickDraftFiles={composer.onPickDraftFiles}
941 onNativePasteImages={composer.onNativePasteImages}
942 onNativePasteText={composer.onNativePasteText}
943 onRemoveDraftImage={composer.onRemoveDraftImage}
944 serverConfig={serverConfig}
945 onStopThread={handleStopThread}
946 onSendMessage={composer.onSendMessage}
947 onReconnectEnvironment={handleReconnectEnvironment}
948 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
949 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
950 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
951 onRespondToApproval={requests.onRespondToApproval}
952 onSelectUserInputOption={requests.onSelectUserInputOption}
953 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
954 onSubmitUserInput={requests.onSubmitUserInput}
955 onDismissUserInput={requests.onDismissUserInput}
956 />
957 </View>
958 </>
959 );
960​
961 return (
962 <>
963 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
964 <NativeStackScreenOptions
965 optionsVersion={threadGitControlProps.projectScripts}
966 options={{
967 // Android draws its own in-flow header (AndroidScreenHeader below);
968 // the native stack header stays iOS-only.
969 headerShown: Platform.OS !== "android",
970 headerTitle: selectedThread.title,
971 headerTitleStyle: usesNativeHeaderGlass
972 ? {
973 fontSize: 17,
974 fontWeight: "800",
975 }
976 : undefined,
977 title: selectedThread.title,
978 headerBackVisible: !layout.usesSplitView,
979 // Compact uses the NATIVE back button when a previous route exists;
980 // deep links / cold starts get an explicit Home button instead.
981 // Split view always uses its custom left items.
982 unstable_headerLeftItems:
983 Platform.OS === "ios"
984 ? layout.usesSplitView
985 ? () => splitLeftHeaderItems
986 : canGoBack
987 ? undefined
988 : () => compactHomeHeaderItems
989 : undefined,
990 // Search lives in the persistent sidebar, so the split header keeps
991 // the git controls on the RIGHT (no center items — center space is
992 // reserved for future breadcrumbs/status).
993 unstable_headerRightItems:
994 Platform.OS === "ios"
995 ? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
996 : undefined,
997 unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
998 contentStyle:
999 Platform.OS === "android" && materialYouStyleLayoutActive
1000 ? { backgroundColor: headerColor }
1001 : undefined,
1002 }}
1003 />
1004​
1005 {Platform.OS === "android" ? (
1006 <AndroidScreenHeader
1007 title={selectedThread.title}
1008 subtitle={headerSubtitle}
1009 onBack={
1010 layout.usesSplitView
1011 ? undefined
1012 : () => {
1013 // A deep link or cold start has no previous route; Home is the way out.
1014 // Read the history at press time: it changes without re-rendering this screen.
1015 if (navigation.canGoBack()) navigation.goBack();
1016 else navigation.dispatch(StackActions.replace("Home"));
1019 actions={androidHeaderActions}
1020 hideBottomBorder={materialYouStyleLayoutActive}
1021 />
1022 ) : null}
1023​
1024 {/* Android surfaces the git/files/inspector actions in its in-flow
1025 header above, so the fallback action toolbar stays iOS-only. */}
1026 {renderThreadRouteBody(
1027 Platform.OS !== "android" && !layout.usesSplitView && !usesNativeHeaderGlass,
1028 )}
1029 </>
1030 );