Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { useOpenPullRequest } from "../../native/useOpenPullRequest";
3import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
4import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
5import { useWorktreeSetup } from "./use-worktree-setup";
6import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
7import { AppBar } from "../../components/ui/AppBar";
8import {
9 StackActions,
10 useFocusEffect,
11 useNavigation,
12 type StaticScreenProps,
13} from "@react-navigation/native";
14import { useEffect, useRef, useState, type ReactNode } from "react";
15import * as Option from "effect/Option";
16import {
17 AuthOrchestrationOperateScope,
18 AuthTerminalOperateScope,
19 AuthTerminalReadScope,
20 DEFAULT_SERVER_SETTINGS,
21 EnvironmentId,
22 ThreadId,
23 type ProjectScript,
24} from "@t3tools/contracts";
25import {
26 projectScriptCwd,
27 projectScriptRuntimeEnv,
28 projectScriptTerminalInput,
29 resolveProjectScripts,
30} from "@t3tools/shared/projectScripts";
31import { Platform, ScrollView } from "react-native";
32import { useSafeAreaInsets } from "react-native-safe-area-context";
33import { useConnectionsReady } from "../../state/workspace";
34import { useEnvironmentShellReadiness } from "../../state/shell";
35import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
36import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
37import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
38import { useEnvironmentQuery } from "../../state/query";
39import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
40import { vcsEnvironment } from "../../state/vcs";
41import { EmptyState } from "../../components/ui/EmptyState";
42import { LoadingScreen } from "../../components/LoadingScreen";
43import { scopedThreadKey } from "../../lib/scopedEntities";
44import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
45import { connectionTone } from "../connection/connectionTone";
46import {
47 useRemoteConnections,
48 useRemoteConnectionStatus,
49 useRemoteEnvironmentRuntime,
50} from "../../state/use-remote-environment-registry";
51import { useKnownTerminalSessions } from "../../state/use-terminal-session";
52import { uuidv4 } from "../../lib/uuid";
53import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
54import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
55import { useThreadSelection } from "../../state/use-thread-selection";
56import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
57import {
58 buildTerminalMenuSessions,
59 nextOpenTerminalId,
60 resolveProjectScriptTerminalId,
61} from "../terminal/terminalMenu";
62import {
63 resolvePreferredThreadWorktreePath,
64 stagePendingTerminalLaunch,
65} from "../terminal/terminalLaunchContext";
66import { terminalDebugLog } from "../terminal/terminalDebugLog";
67import type { ThreadDetailScreenProps } from "./ThreadDetailScreen";
68import { ThreadScreenBinding, ThreadScreenFallback, ThreadScreenHost } from "./ThreadScreenHost";
69import { draftRouteIdentity } from "./thread-route-state";
70import { NewTaskDraftRouteScreen, type NewTaskDraftRouteParams } from "./NewTaskDraftRouteScreen";
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 { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
79import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
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";
94import { useThreadPromptLink } from "../prompt-links/useThreadPromptLink";
95import { ThreadHeader } from "./ThreadHeader";
96import {
97 useAndroidWorkspaceBack,
98 useWorkspaceBackNavigation,
99} from "../workspace/useAndroidWorkspaceNavigation";
100
101interface ThreadInspectorSelection {
102 readonly routeThreadIdentity: string | null;
103 readonly mode: ThreadInspectorMode;
104}
105
106function InspectorPaneRoleActivation() {
107 useAdaptiveWorkspacePaneRole("inspector");
108 return null;
109}
110
111function firstRouteParam(value: string | string[] | undefined): string | null {
112 const first = Array.isArray(value) ? value[0] : value;
113 return first === undefined || first.trim().length === 0 ? null : first;
114}
115
116function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) {
117 const goBack = useWorkspaceBackNavigation("threads");
118 const { layout } = useAdaptiveWorkspaceLayout();
119 const { themeVariables } = useAppearancePreferences();
120 if (Platform.OS !== "android")
121 return <ThreadScreenFallback>{props.children}</ThreadScreenFallback>;
122
123 return (
124 <>
125 <AppBar
126 title="Thread"
127 options={{ contentStyle: { backgroundColor: themeVariables["--color-header"] } }}
128 onBack={layout.usesSplitView ? undefined : goBack}
129 hideBottomBorder
130 />
131 <ThreadScreenFallback>{props.children}</ThreadScreenFallback>
132 </>
133 );
134}
135
136function OpeningThreadLoadingScreen() {
137 return (
138 <ThreadRouteFallbackLayout>
139 <LoadingScreen
140 message="Opening thread…"
141 messagePlacement="above-spinner"
142 embedded={Platform.OS === "android"}
143 />
144 </ThreadRouteFallbackLayout>
145 );
146}
147
148type ThreadRouteScreenRouteProps = StaticScreenProps<{
149 readonly environmentId?: string;
150 readonly threadId?: string;
151 readonly draft?: NewTaskDraftRouteParams;
152 readonly prompt?: string | string[];
153}>;
154
155interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
156 readonly onReturnToThread?: () => void;
157 readonly renderInspector?: (headerInset: number) => ReactNode;
158}
159
160function ThreadUnavailableScreen(props: {
161 readonly actionLabel: string;
162 readonly onAction: () => void;
163}) {
164 return (
165 <ThreadRouteFallbackLayout>
166 <ScrollView
167 contentInsetAdjustmentBehavior="automatic"
168 contentContainerStyle={{
169 flexGrow: 1,
170 justifyContent: "center",
171 paddingHorizontal: 24,
172 paddingVertical: 32,
173 }}
174 className="bg-screen flex-1 android:bg-transparent"
175 >
176 <EmptyState
177 title="Thread unavailable"
178 detail="This thread is not available in the current mobile snapshot."
179 actionLabel={props.actionLabel}
180 onAction={props.onAction}
181 />
182 </ScrollView>
183 </ThreadRouteFallbackLayout>
184 );
185}
186
187export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
188 return (
189 <ThreadScreenHost>
190 {props.route.params?.draft ? (
191 <NewTaskDraftRouteScreen
192 key={draftRouteIdentity(props.route.params.draft)}
193 route={{ ...props.route, params: props.route.params.draft }}
194 />
195 ) : (
196 <LiveThreadRouteController {...props} />
197 )}
198 </ThreadScreenHost>
199 );
200}
201
202function LiveThreadRouteController(props: ThreadRouteScreenProps) {
203 useAndroidWorkspaceBack("threads");
204 const connectionsReady = useConnectionsReady();
205 const { connectionState } = useRemoteConnectionStatus();
206 const { selectedThread } = useThreadSelection();
207 const params = props.route.params ?? {};
208 const environmentIdRaw = firstRouteParam(params.environmentId);
209 const threadIdRaw = firstRouteParam(params.threadId);
210 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
211 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
212 const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
213 const { onReconnectEnvironment } = useRemoteConnections();
214 const navigation = useNavigation();
215 const routeConnectionState =
216 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
217 const routeThreadKey =
218 environmentId !== null && threadIdRaw !== null
219 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
220 : null;
221 const selectedThreadKey =
222 selectedThread === null
223 ? null
224 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
225 const selectedThreadDetailState = useSelectedThreadDetailState();
226 useThreadPromptLink(params, routeThreadKey);
227
228 if (environmentId === null || threadIdRaw === null) {
229 return <OpeningThreadLoadingScreen />;
230 }
231
232 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
233 return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
234 }
235
236 const stillHydrating = threadRouteIsHydrating({
237 isLoadingConnections: !connectionsReady,
238 connectionState: routeConnectionState,
239 shellStatus: routeEnvironmentShellState.status,
240 shellHasError: routeEnvironmentShellState.hasError,
241 detailStatus: selectedThreadDetailState.status,
242 detailHasError: Option.isSome(selectedThreadDetailState.error),
243 });
244
245 if (stillHydrating) {
246 return <OpeningThreadLoadingScreen />;
247 }
248
249 return (
250 <ThreadUnavailableScreen
251 actionLabel={
252 routeEnvironmentRuntime === null ? "Manage environments" : "Reconnect environment"
253 }
254 onAction={() => {
255 if (routeEnvironmentRuntime !== null) {
256 onReconnectEnvironment(environmentId);
257 return;
258 }
259 navigation.navigate("SettingsSheet", {
260 screen: "SettingsContent",
261 params: { screen: "SettingsEnvironments" },
262 });
263 }}
264 />
265 );
266}
267
268function ThreadRouteContent(
269 props: ThreadRouteScreenProps & {
270 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
271 },
272) {
273 const { themeVariables } = useAppearancePreferences();
274 const headerColor = themeVariables["--color-header"];
275 const { fileInspector, layout, panes, showAuxiliaryPane, toggleAuxiliaryPane } =
276 useAdaptiveWorkspaceLayout();
277 const { connectionState } = useRemoteConnectionStatus();
278 const { onReconnectEnvironment } = useRemoteConnections();
279 const {
280 selectedThread,
281 selectedThreadCreation,
282 selectedThreadDetailRef,
283 selectedThreadProject,
284 selectedEnvironmentConnection,
285 } = useThreadSelection();
286 const canOperateThread = useEnvironmentScope(
287 selectedThread?.environmentId ?? null,
288 AuthOrchestrationOperateScope,
289 );
290 const canReadTerminal = useEnvironmentScope(
291 selectedThread?.environmentId ?? null,
292 AuthTerminalReadScope,
293 );
294 const canOperateTerminal = useEnvironmentScope(
295 selectedThread?.environmentId ?? null,
296 AuthTerminalOperateScope,
297 );
298 const selectedThreadDetailState = props.selectedThreadDetailState;
299 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
300 const { selectedThreadCwd } = useSelectedThreadWorktree();
301 const composer = useThreadComposerState();
302 const gitState = useSelectedThreadGitState();
303 const gitActions = useSelectedThreadGitActions();
304 const requests = useSelectedThreadRequests();
305 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
306 const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue");
307 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
308 label: "load earlier thread history",
309 reportFailure: false,
310 });
311 const historyControls = (() => {
312 const history = selectedThreadDetailState.history;
313 if (!selectedThread) {
314 return undefined;
315 }
316 if (!history.hasMoreHistory && history.error === null) {
317 return undefined;
318 }
319 return {
320 hasMoreHistory: history.hasMoreHistory,
321 loading: history.loading,
322 error: history.error,
323 onLoadEarlier: () => {
324 void loadEarlierHistory({
325 environmentId: selectedThread.environmentId,
326 input: { threadId: selectedThread.id },
327 });
328 },
329 onLoadThrough: (throughEntryId: string) => {
330 void loadEarlierHistory({
331 environmentId: selectedThread.environmentId,
332 input: { threadId: selectedThread.id, throughEntryId },
333 });
334 },
335 };
336 })();
337 const navigation = useNavigation();
338 const openPullRequest = useOpenPullRequest();
339 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
340 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
341 const mergeBackRun =
342 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
343 const mergeBackBusyRef = useRef(false);
344 const handleMergeBack = async () => {
345 if (
346 mergeBackBusyRef.current ||
347 !selectedThread ||
348 mergeBackTargetThreadId === null ||
349 mergeBackRun === null
350 ) {
351 return;
352 }
353 mergeBackBusyRef.current = true;
354 const result = await mergeBack({
355 environmentId: selectedThread.environmentId,
356 input: {
357 sourceThreadId: selectedThread.id,
358 targetThreadId: mergeBackTargetThreadId,
359 runId: mergeBackRun.id,
360 creationSource: "mobile",
361 },
362 });
363 mergeBackBusyRef.current = false;
364 if (result._tag !== "Success") return;
365 navigation.navigate("Thread", {
366 environmentId: selectedThread.environmentId,
367 threadId: mergeBackTargetThreadId,
368 });
369 };
370 const params = props.route.params ?? {};
371 const environmentIdRaw = firstRouteParam(params.environmentId);
372 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
373 const threadId = firstRouteParam(params.threadId);
374 const routeThreadIdentity =
375 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
376 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
377 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
378 );
379 const inspectorMode = (() => {
380 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
381 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
382 return null;
383 }
384 return inspectorSelection.mode;
385 }
386 return null;
387 })();
388 useEffect(() => {
389 if (
390 fileInspector.supported &&
391 selectedThreadCwd === null &&
392 inspectorMode === null &&
393 panes.auxiliaryPaneVisible
394 ) {
395 toggleAuxiliaryPane();
396 }
397 }, [
398 fileInspector.supported,
399 inspectorMode,
400 panes.auxiliaryPaneVisible,
401 selectedThreadCwd,
402 toggleAuxiliaryPane,
403 ]);
404
405 useEffect(() => {
406 setInspectorSelection((current) => {
407 if (props.renderInspector === undefined) {
408 if (current === null || current.mode === "route") {
409 return null;
410 }
411 return { ...current, routeThreadIdentity };
412 }
413
414 if (current === null || current.mode === "route") {
415 return { routeThreadIdentity, mode: "route" };
416 }
417
418 return { ...current, routeThreadIdentity };
419 });
420 }, [props.renderInspector, routeThreadIdentity]);
421
422 useFocusEffect(() => {
423 return () => {
424 if (props.renderInspector === undefined) {
425 setInspectorSelection(null);
426 }
427 };
428 });
429 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
430 const routeConnectionState =
431 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
432 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
433 const selectedThreadWithDraftSettings = selectedThread
434 ? {
435 ...selectedThread,
436 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
437 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
438 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
439 }
440 : null;
441
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 const gitStatus = useEnvironmentQuery(
450 selectedThread !== null && selectedThreadCwd !== null
451 ? vcsEnvironment.status({
452 environmentId: selectedThread.environmentId,
453 input: { cwd: selectedThreadCwd },
454 })
455 : null,
456 );
457 const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
458 environmentId: selectedThread?.environmentId ?? null,
459 threadId: selectedThread?.id ?? null,
460 });
461 const terminalMenuSessions = buildTerminalMenuSessions({
462 knownSessions: knownTerminalSessions ?? [],
463 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
464 });
465 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
466 const handleReconnectEnvironment = () => {
467 if (!environmentId) {
468 return;
469 }
470 onReconnectEnvironment(environmentId);
471 };
472
473 const gitActionProgressTarget = {
474 environmentId: selectedThread?.environmentId ?? null,
475 cwd: selectedThreadCwd,
476 };
477 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
478
479 const handleOpenGitInspector = () => {
480 if (!fileInspector.supported) {
481 if (selectedThread === null) {
482 return;
483 }
484 navigation.navigate("GitOverview", {
485 environmentId: String(selectedThread.environmentId),
486 threadId: String(selectedThread.id),
487 });
488 return;
489 }
490 setInspectorSelection({ routeThreadIdentity, mode: "git" });
491 showAuxiliaryPane("inspector");
492 };
493 const handleOpenFilesInspector = () => {
494 if (selectedThread === null || selectedThreadCwd === null) {
495 return;
496 }
497 if (!fileInspector.supported) {
498 navigation.navigate("ThreadFiles", {
499 environmentId: String(selectedThread.environmentId),
500 threadId: String(selectedThread.id),
501 });
502 return;
503 }
504 setInspectorSelection({
505 routeThreadIdentity,
506 mode: props.renderInspector === undefined ? "files" : "route",
507 });
508 showAuxiliaryPane("inspector");
509 };
510 const handleToggleInspector = () => {
511 if (inspectorMode === null) {
512 handleOpenFilesInspector();
513 return;
514 }
515 toggleAuxiliaryPane();
516 };
517 const handleSelectInspectorFile = (path: string) => {
518 if (selectedThread === null) {
519 return;
520 }
521 const params = {
522 environmentId: String(selectedThread.environmentId),
523 threadId: String(selectedThread.id),
524 path: path.split("/").filter((segment) => segment.length > 0),
525 };
526 if (fileInspector.supported) {
527 navigation.navigate("ThreadFile", params);
528 return;
529 }
530 navigation.navigate("ThreadFile", params);
531 };
532 const safeAreaInsets = useSafeAreaInsets();
533 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
534 const GitInspector = () => (
535 <GitOverviewSheet
536 headerInset={inspectorHeaderInset}
537 presentation="inspector"
538 route={{ params: { environmentId: environmentId!, threadId: threadId! } }}
539 />
540 );
541 const FilesInspector = () =>
542 selectedThread !== null && selectedThreadCwd !== null ? (
543 <ThreadFileNavigatorPane
544 cwd={selectedThreadCwd}
545 environmentId={selectedThread.environmentId}
546 headerInset={inspectorHeaderInset}
547 projectName={selectedThreadProject?.title ?? "Files"}
548 selectedPath={null}
549 onSelectFile={handleSelectInspectorFile}
550 />
551 ) : null;
552 const RouteInspector = () => props.renderInspector?.(inspectorHeaderInset);
553 const renderInspectorStack = () =>
554 inspectorMode === null ? null : (
555 <ThreadInspectorContentStack
556 renderFiles={FilesInspector}
557 renderGit={GitInspector}
558 mode={inspectorMode}
559 resetKeys={[routeThreadIdentity, selectedThreadCwd]}
560 renderRoute={props.renderInspector ? RouteInspector : undefined}
561 />
562 );
563 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
564 useRegisterWorkspaceInspector(activeInspectorRenderer);
565
566 const handleOpenConnectionEditor = () => {
567 void navigation.navigate("Connections");
568 };
569 const handleStopThread = () => {
570 if (
571 !selectedThread ||
572 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
573 composer.interruptibleRunId === null
574 ) {
575 return;
576 }
577 return interruptThreadTurn({
578 environmentId: selectedThread.environmentId,
579 input: {
580 threadId: selectedThread.id,
581 runId: composer.interruptibleRunId,
582 },
583 });
584 };
585
586 const handleResumeQueue = async () => {
587 if (!selectedThread) return;
588 await resumeThreadQueue({
589 environmentId: selectedThread.environmentId,
590 input: { threadId: selectedThread.id },
591 });
592 };
593
594 const handleOpenTerminal = (nextTerminalId?: string | null) => {
595 terminalDebugLog("terminal-menu:open-existing", {
596 terminalId: nextTerminalId ?? null,
597 hasThread: Boolean(selectedThread),
598 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
599 });
600
601 if (
602 !selectedThread ||
603 !selectedThreadProject?.workspaceRoot ||
604 (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
605 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
606 ) {
607 return;
608 }
609
610 void navigation.navigate("ThreadTerminal", {
611 environmentId: String(selectedThread.environmentId),
612 threadId: String(selectedThread.id),
613 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
614 });
615 };
616
617 const handleOpenNewTerminal = () => {
618 terminalDebugLog("terminal-menu:open-new", {
619 hasThread: Boolean(selectedThread),
620 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
621 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
622 });
623
624 if (
625 !selectedThread ||
626 !selectedThreadProject?.workspaceRoot ||
627 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
628 ) {
629 return;
630 }
631
632 const nextId = nextOpenTerminalId({
633 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
634 ...(knownTerminalSessions === null ||
635 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
636 ? { uniqueSuffix: uuidv4() }
637 : {}),
638 });
639 void navigation.navigate("ThreadTerminal", {
640 environmentId: String(selectedThread.environmentId),
641 threadId: String(selectedThread.id),
642 terminalId: nextId,
643 });
644 };
645
646 const handleRunProjectScript = async (script: ProjectScript) => {
647 terminalDebugLog("project-script:press", {
648 scriptId: script.id,
649 command: script.command,
650 hasThread: Boolean(selectedThread),
651 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
652 });
653
654 if (
655 !selectedThread ||
656 !selectedThreadProject?.workspaceRoot ||
657 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
658 ) {
659 terminalDebugLog("project-script:abort", {
660 scriptId: script.id,
661 reason: "no-thread-workspace-or-terminal-access",
662 });
663 return;
664 }
665
666 const targetTerminalId = resolveProjectScriptTerminalId({
667 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
668 ...(knownTerminalSessions === null ||
669 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
670 ? { uniqueSuffix: uuidv4() }
671 : {}),
672 hasRunningTerminal: terminalMenuSessions.some(
673 (session) => session.status === "running" || session.status === "starting",
674 ),
675 });
676 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
677 threadShellWorktreePath: selectedThread.worktreePath ?? null,
678 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
679 });
680 const cwd = projectScriptCwd({
681 project: { cwd: selectedThreadProject.workspaceRoot },
682 worktreePath: preferredWorktreePath,
683 });
684 const env = projectScriptRuntimeEnv({
685 project: { cwd: selectedThreadProject.workspaceRoot },
686 worktreePath: preferredWorktreePath,
687 });
688 stagePendingTerminalLaunch({
689 target: {
690 environmentId: selectedThread.environmentId,
691 threadId: selectedThread.id,
692 terminalId: targetTerminalId,
693 },
694 launch: {
695 cwd,
696 worktreePath: preferredWorktreePath,
697 env,
698 initialInput: projectScriptTerminalInput(script.command),
699 },
700 });
701 terminalDebugLog("project-script:staged", {
702 scriptId: script.id,
703 terminalId: targetTerminalId,
704 cwd,
705 worktreePath: preferredWorktreePath,
706 });
707
708 void navigation.navigate("ThreadTerminal", {
709 environmentId: String(selectedThread.environmentId),
710 threadId: String(selectedThread.id),
711 terminalId: targetTerminalId,
712 });
713 };
714 const threadGitControlProps = {
715 environmentId: environmentIdRaw ?? "",
716 threadId: threadId ?? "",
717 auxiliaryPaneControl:
718 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
719 ? {
720 accessibilityLabel: "Toggle inspector",
721 onPress: handleToggleInspector,
722 }
723 : undefined,
724 onOpenFilesInspector:
725 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
726 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
727 onMergeBack:
728 mergeBackTargetThreadId !== null && mergeBackRun !== null
729 ? () => void handleMergeBack()
730 : undefined,
731 currentBranch: selectedThread?.branch ?? null,
732 gitStatus: gitStatus.data,
733 gitOperationLabel: gitState.gitOperationLabel,
734 canOpenTerminal:
735 Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
736 canOperateTerminal,
737 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
738 projectScripts: selectedThreadProject
739 ? resolveProjectScripts(
740 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
741 selectedThreadProject,
742 )
743 : [],
744 terminalSessions: terminalMenuSessions,
745 showDirectFileControl: layout.usesSplitView,
746 onOpenTerminal: handleOpenTerminal,
747 onOpenNewTerminal: handleOpenNewTerminal,
748 onRunProjectScript: handleRunProjectScript,
749 onPull: gitActions.onPullSelectedThreadBranch,
750 onRunAction: gitActions.onRunSelectedThreadGitAction,
751 };
752 const handleEditFailedCreation = async () => {
753 const creation = selectedThreadCreation?.message;
754 if (!creation?.creation || routeThreadIdentity === null) {
755 return;
756 }
757 // The drain restored the prompt and attachments into the recovery draft
758 // the rejected creation owns. Open that draft by id: without it the sheet
759 // mints a fresh empty one and the restored content is unreachable.
760 try {
761 await recoverFailedThreadDraft(creation);
762 } catch (error) {
763 Dialog.alert(
764 "Could not restore draft",
765 error instanceof Error ? error.message : String(error),
766 );
767 return;
768 }
769 clearPendingThreadCreationOutcome(routeThreadIdentity);
770 navigation.dispatch(
771 StackActions.replace("Thread", {
772 draft: {
773 draftId: restoredNewTaskDraftKey(creation.messageId),
774 environmentId: String(creation.environmentId),
775 projectId: String(creation.creation.projectId),
776 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
777 },
778 }),
779 );
780 };
781 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
782 const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({
783 environmentId: selectedThread?.environmentId ?? null,
784 threadId: selectedThread?.id ?? null,
785 preparing:
786 composer.selectedThreadActivityRun?.status === "preparing" ||
787 selectedThread?.runtime?.status === "preparing" ||
788 selectedThread?.worktreePath != null ||
789 (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
790 selectedThreadCreation.outcome == null),
791 turnStarted: setupTurnStartedAt !== null,
792 followUpSent:
793 composer.selectedThreadFeed.filter(
794 (entry) => entry.type === "message" && entry.message.role === "user",
795 ).length +
796 composer.selectedThreadQueueCount >
797 1,
798 });
799 const awaitingBootstrapTurn =
800 worktreeSetup !== null
801 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
802 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
803 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
804 const handleCancelWorktreeSetup = () => {
805 if (!selectedThread) return;
806 void cancelWorktreeSetup({
807 environmentId: selectedThread.environmentId,
808 input: { threadId: selectedThread.id },
809 });
810 };
811 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
812 const localResendBusy = useRef(false);
813 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
814 const handleWorkLocally = async () => {
815 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
816 return;
817 localResendBusy.current = true;
818 const result = await cancelWorktreeSetup({
819 environmentId: selectedThread.environmentId,
820 input: { threadId: selectedThread.id },
821 });
822 if (result._tag !== "Success" || !result.value.cancelled) {
823 localResendBusy.current = false;
824 return;
825 }
826 // V2 accepts the launch before setup runs, so cancellation never rejects
827 // the original outbox delivery. Reuse the server-owned prompt and uploads.
828 const metadata = makeTurnCommandMetadata();
829 const launched = await startLocalThread({
830 environmentId: selectedThread.environmentId,
831 input: buildProjectThreadStartTurnInput({
832 ...metadata,
833 projectId: selectedThread.projectId,
834 projectCwd: selectedThreadProject.workspaceRoot,
835 text: setupMessage.text,
836 titleText: selectedThread.title,
837 ...(setupMessage.context ? { context: setupMessage.context } : {}),
838 uploadedAttachments: setupMessage.attachments,
839 modelSelection: selectedThread.modelSelection,
840 runtimeMode: selectedThread.runtimeMode,
841 interactionMode: selectedThread.interactionMode,
842 workspaceMode: "local",
843 branch: null,
844 worktreePath: null,
845 startFromOrigin: false,
846 worktreeBranchName: "",
847 }),
848 });
849 localResendBusy.current = false;
850 if (launched._tag !== "Success") return;
851 navigation.dispatch(
852 StackActions.replace("Thread", {
853 environmentId: String(selectedThread.environmentId),
854 threadId: metadata.threadId,
855 }),
856 );
857 };
858 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
859 if (selectedThreadCreation === null) {
860 return awaitingBootstrapTurn
861 ? { kind: "preparing", preparingWorktree: true, serverOwned: true }
862 : null;
863 }
864 if (selectedThreadCreation.outcome?.kind === "failed") {
865 return {
866 kind: "failed",
867 reason: selectedThreadCreation.outcome.reason,
868 onEditTask: handleEditFailedCreation,
869 };
870 }
871 return {
872 kind: "preparing",
873 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
874 serverOwned: false,
875 };
876 })();
877 if (!environmentId || !threadId) {
878 return <OpeningThreadLoadingScreen />;
879 }
880
881 if (!selectedThread) {
882 return <OpeningThreadLoadingScreen />;
883 }
884
885 // A queued creation renders as ready content: its prompt is the whole
886 // conversation until the server creates the thread. The subscription's
887 // not-found error for that window is expected, not a load failure.
888 const contentPresentation =
889 creationState !== null
890 ? { kind: "ready" as const }
891 : projectThreadContentPresentation({
892 hasDetail: selectedThreadDetail !== null,
893 detailError: Option.getOrNull(selectedThreadDetailState.error),
894 detailDeleted: selectedThreadDetailState.status === "deleted",
895 connectionState: routeConnectionState,
896 });
897 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
898 const renderThreadRouteBody = () => (
899 <>
900 <GitActionProgressOverlay
901 progress={gitActionProgress}
902 onDismiss={dismissGitActionResult}
903 onOpenPullRequest={openPullRequest}
904 />
905
906 <>
907 <ThreadScreenBinding
908 header={
909 <ThreadHeader
910 title={selectedThread.title}
911 subtitle={headerSubtitle}
912 headerColor={headerColor}
913 usesNativeHeaderGlass={usesNativeHeaderGlass}
914 gitControls={threadGitControlProps}
915 hasThreadCwd={selectedThreadCwd !== null}
916 hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
917 fileInspectorSupported={fileInspector.supported}
918 inspectorMode={inspectorMode}
919 onToggleInspector={handleToggleInspector}
920 onOpenGitInspector={handleOpenGitInspector}
921 onOpenFilesInspector={handleOpenFilesInspector}
922 onReturnToThread={props.onReturnToThread}
923 />
924 }
925 canOperateThread={canOperateThread}
926 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
927 selectedThreadDetailRef={selectedThreadDetailRef}
928 contentPresentation={contentPresentation}
929 screenTone={connectionTone(routeConnectionState)}
930 connectionError={routeConnectionError}
931 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
932 feedbackSubmissions={composer.feedbackSubmissions}
933 onDismissFeedback={composer.dismissFeedback}
934 selectedThreadFeed={composer.selectedThreadFeed}
935 pendingHandoff={composer.pendingHandoff}
936 activityRun={composer.selectedThreadActivityRun}
937 activeWorkStartedAt={
938 creationState?.kind === "preparing" ||
939 (worktreeSetup !== null && setupTurnStartedAt === null)
940 ? null
941 : composer.activeWorkStartedAt
942 }
943 isCompacting={composer.isCompacting}
944 runlessWorkActive={composer.runlessWorkActive}
945 providerSubagentStatus={composer.providerSubagentStatus}
946 creationState={creationState}
947 setupWorkingStartedAt={
948 composer.activeWorkStartedAt !== null &&
949 worktreeSetupSnapshot !== null &&
950 composer.selectedThreadFeed.filter(
951 (entry) => entry.type === "message" && entry.message.role === "user",
952 ).length <= 1
953 ? composer.activeWorkStartedAt
954 : null
955 }
956 worktreeSetup={
957 worktreeSetup
958 ? {
959 snapshot: worktreeSetup,
960 turnStartedAt: setupTurnStartedAt,
961 working: composer.activeWorkStartedAt !== null,
962 turnStarted: setupTurnStartedAt !== null,
963 onCancel: handleCancelWorktreeSetup,
964 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
965 }
966 : null
967 }
968 activePendingApproval={requests.activePendingApproval}
969 activePendingApprovals={requests.activePendingApprovals}
970 respondingApprovalId={requests.respondingApprovalId}
971 activePendingUserInput={requests.activePendingUserInput}
972 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
973 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
974 respondingUserInputId={requests.respondingUserInputId}
975 connectionStateLabel={routeConnectionState}
976 threadSyncStatus={selectedThreadDetailState.status}
977 historyControls={historyControls}
978 activeThreadBusy={composer.activeThreadBusy}
979 canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null}
980 queuedRunEdit={composer.queuedRunEdit}
981 composerDraftKey={composer.composerDraftKey}
982 followUpBehavior={composer.followUpBehavior}
983 canSteerActiveTurn={composer.canSteerActiveTurn}
984 isSavingQueuedEdit={composer.isSavingQueuedEdit}
985 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
986 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
987 environmentId={selectedThread.environmentId}
988 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
989 threadCwd={selectedThreadCwd}
990 selectedThreadQueueCount={composer.selectedThreadQueueCount}
991 queuedMessages={
992 selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"
993 ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]
994 : composer.selectedThreadQueuedMessages
995 }
996 dispatchingMessageId={composer.dispatchingQueuedMessageId}
997 layoutVariant={layout.variant}
998 usesAutomaticContentInsets={usesNativeHeaderGlass}
999 onOpenConnectionEditor={handleOpenConnectionEditor}
1000 onChangeDraftMessage={composer.onChangeDraftMessage}
1001 onPickDraftMedia={composer.onPickDraftMedia}
1002 onPickDraftFiles={composer.onPickDraftFiles}
1003 onNativePasteImages={composer.onNativePasteImages}
1004 onNativePasteText={composer.onNativePasteText}
1005 onRemoveDraftImage={composer.onRemoveDraftImage}
1006 serverConfig={serverConfig}
1007 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1008 onResumeQueue={composer.queueHeld ? handleResumeQueue : null}
1009 onSendMessage={composer.onSendMessage}
1010 onReconnectEnvironment={handleReconnectEnvironment}
1011 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1012 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
1013 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
1014 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1015 onRespondToApproval={requests.onRespondToApproval}
1016 onSelectUserInputOption={requests.onSelectUserInputOption}
1017 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1018 onSubmitUserInput={requests.onSubmitUserInput}
1019 onDismissUserInput={requests.onDismissUserInput}
1020 />
1021 </>
1022 </>
1023 );
1024
1025 return (
1026 <>
1027 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1028
1029 {renderThreadRouteBody()}
1030 </>
1031 );
1032}