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