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