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 };
330 })();
331 const navigation = useNavigation();
332 const openPullRequest = useOpenPullRequest();
333 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
334 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
335 const mergeBackRun =
336 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
337 const mergeBackBusyRef = useRef(false);
338 const handleMergeBack = async () => {
339 if (
340 mergeBackBusyRef.current ||
341 !selectedThread ||
342 mergeBackTargetThreadId === null ||
343 mergeBackRun === null
344 ) {
345 return;
346 }
347 mergeBackBusyRef.current = true;
348 const result = await mergeBack({
349 environmentId: selectedThread.environmentId,
350 input: {
351 sourceThreadId: selectedThread.id,
352 targetThreadId: mergeBackTargetThreadId,
353 runId: mergeBackRun.id,
354 creationSource: "mobile",
355 },
356 });
357 mergeBackBusyRef.current = false;
358 if (result._tag !== "Success") return;
359 navigation.navigate("Thread", {
360 environmentId: selectedThread.environmentId,
361 threadId: mergeBackTargetThreadId,
362 });
363 };
364 const params = props.route.params ?? {};
365 const environmentIdRaw = firstRouteParam(params.environmentId);
366 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
367 const threadId = firstRouteParam(params.threadId);
368 const routeThreadIdentity =
369 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
370 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
371 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
372 );
373 const inspectorMode = (() => {
374 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
375 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
376 return null;
377 }
378 return inspectorSelection.mode;
379 }
380 return null;
381 })();
382 useEffect(() => {
383 if (
384 fileInspector.supported &&
385 selectedThreadCwd === null &&
386 inspectorMode === null &&
387 panes.auxiliaryPaneVisible
388 ) {
389 toggleAuxiliaryPane();
390 }
391 }, [
392 fileInspector.supported,
393 inspectorMode,
394 panes.auxiliaryPaneVisible,
395 selectedThreadCwd,
396 toggleAuxiliaryPane,
397 ]);
398
399 useEffect(() => {
400 setInspectorSelection((current) => {
401 if (props.renderInspector === undefined) {
402 if (current === null || current.mode === "route") {
403 return null;
404 }
405 return { ...current, routeThreadIdentity };
406 }
407
408 if (current === null || current.mode === "route") {
409 return { routeThreadIdentity, mode: "route" };
410 }
411
412 return { ...current, routeThreadIdentity };
413 });
414 }, [props.renderInspector, routeThreadIdentity]);
415
416 useFocusEffect(() => {
417 return () => {
418 if (props.renderInspector === undefined) {
419 setInspectorSelection(null);
420 }
421 };
422 });
423 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
424 const routeConnectionState =
425 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
426 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
427 const selectedThreadWithDraftSettings = selectedThread
428 ? {
429 ...selectedThread,
430 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
431 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
432 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
433 }
434 : null;
435
436 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
437 const headerSubtitle = [
438 selectedThreadProject?.title ?? null,
439 selectedEnvironmentConnection?.environmentLabel ?? null,
440 ]
441 .filter(Boolean)
442 .join(" · ");
443 const gitStatus = useEnvironmentQuery(
444 selectedThread !== null && selectedThreadCwd !== null
445 ? vcsEnvironment.status({
446 environmentId: selectedThread.environmentId,
447 input: { cwd: selectedThreadCwd },
448 })
449 : null,
450 );
451 const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
452 environmentId: selectedThread?.environmentId ?? null,
453 threadId: selectedThread?.id ?? null,
454 });
455 const terminalMenuSessions = buildTerminalMenuSessions({
456 knownSessions: knownTerminalSessions ?? [],
457 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
458 });
459 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
460 const handleReconnectEnvironment = () => {
461 if (!environmentId) {
462 return;
463 }
464 onReconnectEnvironment(environmentId);
465 };
466
467 const gitActionProgressTarget = {
468 environmentId: selectedThread?.environmentId ?? null,
469 cwd: selectedThreadCwd,
470 };
471 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
472
473 const handleOpenGitInspector = () => {
474 if (!fileInspector.supported) {
475 if (selectedThread === null) {
476 return;
477 }
478 navigation.navigate("GitOverview", {
479 environmentId: String(selectedThread.environmentId),
480 threadId: String(selectedThread.id),
481 });
482 return;
483 }
484 setInspectorSelection({ routeThreadIdentity, mode: "git" });
485 showAuxiliaryPane("inspector");
486 };
487 const handleOpenFilesInspector = () => {
488 if (selectedThread === null || selectedThreadCwd === null) {
489 return;
490 }
491 if (!fileInspector.supported) {
492 navigation.navigate("ThreadFiles", {
493 environmentId: String(selectedThread.environmentId),
494 threadId: String(selectedThread.id),
495 });
496 return;
497 }
498 setInspectorSelection({
499 routeThreadIdentity,
500 mode: props.renderInspector === undefined ? "files" : "route",
501 });
502 showAuxiliaryPane("inspector");
503 };
504 const handleToggleInspector = () => {
505 if (inspectorMode === null) {
506 handleOpenFilesInspector();
507 return;
508 }
509 toggleAuxiliaryPane();
510 };
511 const handleSelectInspectorFile = (path: string) => {
512 if (selectedThread === null) {
513 return;
514 }
515 const params = {
516 environmentId: String(selectedThread.environmentId),
517 threadId: String(selectedThread.id),
518 path: path.split("/").filter((segment) => segment.length > 0),
519 };
520 if (fileInspector.supported) {
521 navigation.navigate("ThreadFile", params);
522 return;
523 }
524 navigation.navigate("ThreadFile", params);
525 };
526 const safeAreaInsets = useSafeAreaInsets();
527 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
528 const GitInspector = () => (
529 <GitOverviewSheet
530 headerInset={inspectorHeaderInset}
531 presentation="inspector"
532 route={{ params: { environmentId: environmentId!, threadId: threadId! } }}
533 />
534 );
535 const FilesInspector = () =>
536 selectedThread !== null && selectedThreadCwd !== null ? (
537 <ThreadFileNavigatorPane
538 cwd={selectedThreadCwd}
539 environmentId={selectedThread.environmentId}
540 headerInset={inspectorHeaderInset}
541 projectName={selectedThreadProject?.title ?? "Files"}
542 selectedPath={null}
543 onSelectFile={handleSelectInspectorFile}
544 />
545 ) : null;
546 const RouteInspector = () => props.renderInspector?.(inspectorHeaderInset);
547 const renderInspectorStack = () =>
548 inspectorMode === null ? null : (
549 <ThreadInspectorContentStack
550 renderFiles={FilesInspector}
551 renderGit={GitInspector}
552 mode={inspectorMode}
553 resetKeys={[routeThreadIdentity, selectedThreadCwd]}
554 renderRoute={props.renderInspector ? RouteInspector : undefined}
555 />
556 );
557 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
558 useRegisterWorkspaceInspector(activeInspectorRenderer);
559
560 const handleOpenConnectionEditor = () => {
561 void navigation.navigate("Connections");
562 };
563 const handleStopThread = () => {
564 if (
565 !selectedThread ||
566 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
567 composer.interruptibleRunId === null
568 ) {
569 return;
570 }
571 return interruptThreadTurn({
572 environmentId: selectedThread.environmentId,
573 input: {
574 threadId: selectedThread.id,
575 runId: composer.interruptibleRunId,
576 },
577 });
578 };
579
580 const handleResumeQueue = async () => {
581 if (!selectedThread) return;
582 await resumeThreadQueue({
583 environmentId: selectedThread.environmentId,
584 input: { threadId: selectedThread.id },
585 });
586 };
587
588 const handleOpenTerminal = (nextTerminalId?: string | null) => {
589 terminalDebugLog("terminal-menu:open-existing", {
590 terminalId: nextTerminalId ?? null,
591 hasThread: Boolean(selectedThread),
592 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
593 });
594
595 if (
596 !selectedThread ||
597 !selectedThreadProject?.workspaceRoot ||
598 (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
599 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
600 ) {
601 return;
602 }
603
604 void navigation.navigate("ThreadTerminal", {
605 environmentId: String(selectedThread.environmentId),
606 threadId: String(selectedThread.id),
607 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
608 });
609 };
610
611 const handleOpenNewTerminal = () => {
612 terminalDebugLog("terminal-menu:open-new", {
613 hasThread: Boolean(selectedThread),
614 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
615 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
616 });
617
618 if (
619 !selectedThread ||
620 !selectedThreadProject?.workspaceRoot ||
621 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
622 ) {
623 return;
624 }
625
626 const nextId = nextOpenTerminalId({
627 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
628 ...(knownTerminalSessions === null ||
629 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
630 ? { uniqueSuffix: uuidv4() }
631 : {}),
632 });
633 void navigation.navigate("ThreadTerminal", {
634 environmentId: String(selectedThread.environmentId),
635 threadId: String(selectedThread.id),
636 terminalId: nextId,
637 });
638 };
639
640 const handleRunProjectScript = async (script: ProjectScript) => {
641 terminalDebugLog("project-script:press", {
642 scriptId: script.id,
643 command: script.command,
644 hasThread: Boolean(selectedThread),
645 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
646 });
647
648 if (
649 !selectedThread ||
650 !selectedThreadProject?.workspaceRoot ||
651 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
652 ) {
653 terminalDebugLog("project-script:abort", {
654 scriptId: script.id,
655 reason: "no-thread-workspace-or-terminal-access",
656 });
657 return;
658 }
659
660 const targetTerminalId = resolveProjectScriptTerminalId({
661 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
662 ...(knownTerminalSessions === null ||
663 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
664 ? { uniqueSuffix: uuidv4() }
665 : {}),
666 hasRunningTerminal: terminalMenuSessions.some(
667 (session) => session.status === "running" || session.status === "starting",
668 ),
669 });
670 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
671 threadShellWorktreePath: selectedThread.worktreePath ?? null,
672 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
673 });
674 const cwd = projectScriptCwd({
675 project: { cwd: selectedThreadProject.workspaceRoot },
676 worktreePath: preferredWorktreePath,
677 });
678 const env = projectScriptRuntimeEnv({
679 project: { cwd: selectedThreadProject.workspaceRoot },
680 worktreePath: preferredWorktreePath,
681 });
682 stagePendingTerminalLaunch({
683 target: {
684 environmentId: selectedThread.environmentId,
685 threadId: selectedThread.id,
686 terminalId: targetTerminalId,
687 },
688 launch: {
689 cwd,
690 worktreePath: preferredWorktreePath,
691 env,
692 initialInput: projectScriptTerminalInput(script.command),
693 },
694 });
695 terminalDebugLog("project-script:staged", {
696 scriptId: script.id,
697 terminalId: targetTerminalId,
698 cwd,
699 worktreePath: preferredWorktreePath,
700 });
701
702 void navigation.navigate("ThreadTerminal", {
703 environmentId: String(selectedThread.environmentId),
704 threadId: String(selectedThread.id),
705 terminalId: targetTerminalId,
706 });
707 };
708 const threadGitControlProps = {
709 environmentId: environmentIdRaw ?? "",
710 threadId: threadId ?? "",
711 auxiliaryPaneControl:
712 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
713 ? {
714 accessibilityLabel: "Toggle inspector",
715 onPress: handleToggleInspector,
716 }
717 : undefined,
718 onOpenFilesInspector:
719 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
720 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
721 onMergeBack:
722 mergeBackTargetThreadId !== null && mergeBackRun !== null
723 ? () => void handleMergeBack()
724 : undefined,
725 currentBranch: selectedThread?.branch ?? null,
726 gitStatus: gitStatus.data,
727 gitOperationLabel: gitState.gitOperationLabel,
728 canOpenTerminal:
729 Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
730 canOperateTerminal,
731 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
732 projectScripts: selectedThreadProject
733 ? resolveProjectScripts(
734 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
735 selectedThreadProject,
736 )
737 : [],
738 terminalSessions: terminalMenuSessions,
739 showDirectFileControl: layout.usesSplitView,
740 onOpenTerminal: handleOpenTerminal,
741 onOpenNewTerminal: handleOpenNewTerminal,
742 onRunProjectScript: handleRunProjectScript,
743 onPull: gitActions.onPullSelectedThreadBranch,
744 onRunAction: gitActions.onRunSelectedThreadGitAction,
745 };
746 const handleEditFailedCreation = async () => {
747 const creation = selectedThreadCreation?.message;
748 if (!creation?.creation || routeThreadIdentity === null) {
749 return;
750 }
751 // The drain restored the prompt and attachments into the recovery draft
752 // the rejected creation owns. Open that draft by id: without it the sheet
753 // mints a fresh empty one and the restored content is unreachable.
754 try {
755 await recoverFailedThreadDraft(creation);
756 } catch (error) {
757 Dialog.alert(
758 "Could not restore draft",
759 error instanceof Error ? error.message : String(error),
760 );
761 return;
762 }
763 clearPendingThreadCreationOutcome(routeThreadIdentity);
764 navigation.dispatch(
765 StackActions.replace("Thread", {
766 draft: {
767 draftId: restoredNewTaskDraftKey(creation.messageId),
768 environmentId: String(creation.environmentId),
769 projectId: String(creation.creation.projectId),
770 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
771 },
772 }),
773 );
774 };
775 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
776 const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({
777 environmentId: selectedThread?.environmentId ?? null,
778 threadId: selectedThread?.id ?? null,
779 preparing:
780 composer.selectedThreadActivityRun?.status === "preparing" ||
781 selectedThread?.runtime?.status === "preparing" ||
782 selectedThread?.worktreePath != null ||
783 (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
784 selectedThreadCreation.outcome == null),
785 turnStarted: setupTurnStartedAt !== null,
786 followUpSent:
787 composer.selectedThreadFeed.filter(
788 (entry) => entry.type === "message" && entry.message.role === "user",
789 ).length +
790 composer.selectedThreadQueueCount >
791 1,
792 });
793 const awaitingBootstrapTurn =
794 worktreeSetup !== null
795 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
796 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
797 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
798 const handleCancelWorktreeSetup = () => {
799 if (!selectedThread) return;
800 void cancelWorktreeSetup({
801 environmentId: selectedThread.environmentId,
802 input: { threadId: selectedThread.id },
803 });
804 };
805 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
806 const localResendBusy = useRef(false);
807 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
808 const handleWorkLocally = async () => {
809 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
810 return;
811 localResendBusy.current = true;
812 const result = await cancelWorktreeSetup({
813 environmentId: selectedThread.environmentId,
814 input: { threadId: selectedThread.id },
815 });
816 if (result._tag !== "Success" || !result.value.cancelled) {
817 localResendBusy.current = false;
818 return;
819 }
820 // V2 accepts the launch before setup runs, so cancellation never rejects
821 // the original outbox delivery. Reuse the server-owned prompt and uploads.
822 const metadata = makeTurnCommandMetadata();
823 const launched = await startLocalThread({
824 environmentId: selectedThread.environmentId,
825 input: buildProjectThreadStartTurnInput({
826 ...metadata,
827 projectId: selectedThread.projectId,
828 projectCwd: selectedThreadProject.workspaceRoot,
829 text: setupMessage.text,
830 titleText: selectedThread.title,
831 ...(setupMessage.context ? { context: setupMessage.context } : {}),
832 uploadedAttachments: setupMessage.attachments,
833 modelSelection: selectedThread.modelSelection,
834 runtimeMode: selectedThread.runtimeMode,
835 interactionMode: selectedThread.interactionMode,
836 workspaceMode: "local",
837 branch: null,
838 worktreePath: null,
839 startFromOrigin: false,
840 worktreeBranchName: "",
841 }),
842 });
843 localResendBusy.current = false;
844 if (launched._tag !== "Success") return;
845 navigation.dispatch(
846 StackActions.replace("Thread", {
847 environmentId: String(selectedThread.environmentId),
848 threadId: metadata.threadId,
849 }),
850 );
851 };
852 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
853 if (selectedThreadCreation === null) {
854 return awaitingBootstrapTurn
855 ? { kind: "preparing", preparingWorktree: true, serverOwned: true }
856 : null;
857 }
858 if (selectedThreadCreation.outcome?.kind === "failed") {
859 return {
860 kind: "failed",
861 reason: selectedThreadCreation.outcome.reason,
862 onEditTask: handleEditFailedCreation,
863 };
864 }
865 return {
866 kind: "preparing",
867 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
868 serverOwned: false,
869 };
870 })();
871 if (!environmentId || !threadId) {
872 return <OpeningThreadLoadingScreen />;
873 }
874
875 if (!selectedThread) {
876 return <OpeningThreadLoadingScreen />;
877 }
878
879 // A queued creation renders as ready content: its prompt is the whole
880 // conversation until the server creates the thread. The subscription's
881 // not-found error for that window is expected, not a load failure.
882 const contentPresentation =
883 creationState !== null
884 ? { kind: "ready" as const }
885 : projectThreadContentPresentation({
886 hasDetail: selectedThreadDetail !== null,
887 detailError: Option.getOrNull(selectedThreadDetailState.error),
888 detailDeleted: selectedThreadDetailState.status === "deleted",
889 connectionState: routeConnectionState,
890 });
891 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
892 const renderThreadRouteBody = () => (
893 <>
894 <GitActionProgressOverlay
895 progress={gitActionProgress}
896 onDismiss={dismissGitActionResult}
897 onOpenPullRequest={openPullRequest}
898 />
899
900 <>
901 <ThreadScreenBinding
902 header={
903 <ThreadHeader
904 title={selectedThread.title}
905 subtitle={headerSubtitle}
906 headerColor={headerColor}
907 usesNativeHeaderGlass={usesNativeHeaderGlass}
908 gitControls={threadGitControlProps}
909 hasThreadCwd={selectedThreadCwd !== null}
910 hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
911 fileInspectorSupported={fileInspector.supported}
912 inspectorMode={inspectorMode}
913 onToggleInspector={handleToggleInspector}
914 onOpenGitInspector={handleOpenGitInspector}
915 onOpenFilesInspector={handleOpenFilesInspector}
916 onReturnToThread={props.onReturnToThread}
917 />
918 }
919 canOperateThread={canOperateThread}
920 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
921 selectedThreadDetailRef={selectedThreadDetailRef}
922 contentPresentation={contentPresentation}
923 screenTone={connectionTone(routeConnectionState)}
924 connectionError={routeConnectionError}
925 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
926 feedbackSubmissions={composer.feedbackSubmissions}
927 onDismissFeedback={composer.dismissFeedback}
928 selectedThreadFeed={composer.selectedThreadFeed}
929 pendingHandoff={composer.pendingHandoff}
930 activityRun={composer.selectedThreadActivityRun}
931 activeWorkStartedAt={
932 creationState?.kind === "preparing" ||
933 (worktreeSetup !== null && setupTurnStartedAt === null)
934 ? null
935 : composer.activeWorkStartedAt
936 }
937 isCompacting={composer.isCompacting}
938 runlessWorkActive={composer.runlessWorkActive}
939 providerSubagentStatus={composer.providerSubagentStatus}
940 creationState={creationState}
941 setupWorkingStartedAt={
942 composer.activeWorkStartedAt !== null &&
943 worktreeSetupSnapshot !== null &&
944 composer.selectedThreadFeed.filter(
945 (entry) => entry.type === "message" && entry.message.role === "user",
946 ).length <= 1
947 ? composer.activeWorkStartedAt
948 : null
949 }
950 worktreeSetup={
951 worktreeSetup
952 ? {
953 snapshot: worktreeSetup,
954 turnStartedAt: setupTurnStartedAt,
955 working: composer.activeWorkStartedAt !== null,
956 turnStarted: setupTurnStartedAt !== null,
957 onCancel: handleCancelWorktreeSetup,
958 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
959 }
960 : null
961 }
962 activePendingApproval={requests.activePendingApproval}
963 activePendingApprovals={requests.activePendingApprovals}
964 respondingApprovalId={requests.respondingApprovalId}
965 activePendingUserInput={requests.activePendingUserInput}
966 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
967 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
968 respondingUserInputId={requests.respondingUserInputId}
969 connectionStateLabel={routeConnectionState}
970 threadSyncStatus={selectedThreadDetailState.status}
971 historyControls={historyControls}
972 activeThreadBusy={composer.activeThreadBusy}
973 canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null}
974 queuedRunEdit={composer.queuedRunEdit}
975 composerDraftKey={composer.composerDraftKey}
976 followUpBehavior={composer.followUpBehavior}
977 canSteerActiveTurn={composer.canSteerActiveTurn}
978 isSavingQueuedEdit={composer.isSavingQueuedEdit}
979 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
980 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
981 environmentId={selectedThread.environmentId}
982 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
983 threadCwd={selectedThreadCwd}
984 selectedThreadQueueCount={composer.selectedThreadQueueCount}
985 queuedMessages={
986 selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"
987 ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]
988 : composer.selectedThreadQueuedMessages
989 }
990 dispatchingMessageId={composer.dispatchingQueuedMessageId}
991 layoutVariant={layout.variant}
992 usesAutomaticContentInsets={usesNativeHeaderGlass}
993 onOpenConnectionEditor={handleOpenConnectionEditor}
994 onChangeDraftMessage={composer.onChangeDraftMessage}
995 onPickDraftMedia={composer.onPickDraftMedia}
996 onPickDraftFiles={composer.onPickDraftFiles}
997 onNativePasteImages={composer.onNativePasteImages}
998 onNativePasteText={composer.onNativePasteText}
999 onRemoveDraftImage={composer.onRemoveDraftImage}
1000 serverConfig={serverConfig}
1001 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1002 onResumeQueue={composer.queueHeld ? handleResumeQueue : null}
1003 onSendMessage={composer.onSendMessage}
1004 onReconnectEnvironment={handleReconnectEnvironment}
1005 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1006 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
1007 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
1008 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1009 onRespondToApproval={requests.onRespondToApproval}
1010 onSelectUserInputOption={requests.onSelectUserInputOption}
1011 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1012 onSubmitUserInput={requests.onSubmitUserInput}
1013 onDismissUserInput={requests.onDismissUserInput}
1014 />
1015 </>
1016 </>
1017 );
1018
1019 return (
1020 <>
1021 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1022
1023 {renderThreadRouteBody()}
1024 </>
1025 );
1026}