Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadRouteScreen.tsx

1,119 lines42.6 KB

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