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

ThreadRouteScreen.tsx

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