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

ThreadRouteScreen.tsx

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