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

ThreadRouteScreen.tsx

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