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