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