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

ThreadRouteScreen.tsx

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