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