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

ThreadRouteScreen.tsx

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