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

ThreadRouteScreen.tsx

1,152 lines43.5 KB

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