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