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

ThreadRouteScreen.tsx

1,179 lines45.4 KB

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