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

ThreadRouteScreen.tsx

1,189 lines45.6 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 threadSyncStatusLabel,
109} from "./threadContentPresentation";
110import {
111 Inspector,
112 useAdaptiveWorkspaceLayout,
113 useWorkspacePaneState,
114} from "../layout/AdaptiveWorkspaceLayout";
115import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
116import { InspectorSheetContext } from "../layout/workspace-inspector-sheet";
117import type { InspectorContent } from "../layout/inspector-panes";
118import {
119 threadDetailErrorIsCurrent,
120 threadRouteIsHydrating,
121 threadRouteOpensDraft,
122} from "./thread-route-hydration";
123import { ThreadHeader } from "./ThreadHeader";
124import { resumeThread } from "./resume-thread";
125import {
126 useAndroidWorkspaceBack,
127 useWorkspaceBackNavigation,
128} from "../layout/workspace/useAndroidWorkspaceNavigation";
129import { openSettings } from "../settings/settings-navigation";
130import { ThreadInspectorHeader, type ThreadInspectorPresentation } from "./thread-inspector-header";
131import { InspectorContentScope, ThreadInspectorPreview } from "./thread-inspector-preview";
132import { useStartSideChat } from "./useStartSideChat";
133import { useThreadStatusAnnouncements } from "./useThreadStatusAnnouncements";
134import type { ThreadInspectorMode, ThreadInspectorTarget } from "./thread-inspector-navigation";
135import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
136​
137function firstRouteParam(value: string | string[] | undefined): string | null {
138 const first = Array.isArray(value) ? value[0] : value;
139 return first === undefined || first.trim().length === 0 ? null : first;
141​
142const RECONNECT_ERROR_DELAY_MS = 5_000;
143​
144// The inspector pane's bar belongs to ThreadInspectorHeader; the fallback must not draw its own.
145const InspectorHeaderShownContext = createContext(false);
146​
147function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) {
148 const gt = useGT();
149 const goBack = useWorkspaceBackNavigation();
150 const inspectorHeaderShown = use(InspectorHeaderShownContext);
151 return (
152 <ThreadScreenFallback
153 header={
154 inspectorHeaderShown ? undefined : (
155 <AppBar title={gt("Thread")} onBackToList={goBack} hideBottomBorder />
156 )
157 }
158 >
159 {props.children}
160 </ThreadScreenFallback>
161 );
163​
164function OpeningThreadLoadingScreen() {
165 const gt = useGT();
166 return (
167 <ThreadRouteFallbackLayout>
168 <LoadingScreen message={gt("Opening thread…")} messagePlacement="above-spinner" embedded />
169 </ThreadRouteFallbackLayout>
170 );
172​
173type ThreadRouteScreenRouteProps = StaticScreenProps<{
174 readonly environmentId?: string;
175 readonly threadId?: string;
176 readonly draft?: NewTaskDraftRouteParams;
177 readonly inspector?: ThreadInspectorTarget;
178 readonly prompt?: string | string[];
179}>;
180​
181interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
182 readonly inspectorPresentation?: ThreadInspectorPresentation;
183 readonly onReturnToThread?: () => void;
184 readonly renderInspector?: () => ReactNode;
186​
187function ThreadUnavailableScreen(props: {
188 readonly actionLabel: string;
189 readonly onAction: () => void;
190}) {
191 const gt = useGT();
192 return (
193 <ThreadRouteFallbackLayout>
194 <ScrollView
195 contentInsetAdjustmentBehavior="automatic"
196 contentContainerStyle={{
197 flexGrow: 1,
198 justifyContent: "center",
199 paddingHorizontal: 24,
200 paddingVertical: 32,
201 }}
202 className="bg-screen flex-1 android:bg-transparent"
203 >
204 <EmptyState
205 title={gt("Thread unavailable")}
206 detail={gt("This thread is not available in the current mobile snapshot.")}
207 actionLabel={props.actionLabel}
208 onAction={props.onAction}
209 />
210 </ScrollView>
211 </ThreadRouteFallbackLayout>
212 );
214​
215/** A thread that can't load opens a new task in its environment instead of a dead end. */
216function UnavailableThreadDraftRedirect(props: { readonly environmentId: EnvironmentId }) {
217 const navigation = useNavigation();
218 const projects = useProjects();
219 const openDraft = useEffectEvent(() => {
220 const project = projects.find((candidate) => candidate.environmentId === props.environmentId);
221 navigation.dispatch(
222 StackActions.replace("Thread", {
223 draft: project
224 ? {
225 requestId: uuidv4(),
226 environmentId: String(project.environmentId),
227 projectId: String(project.id),
228 }
229 : { requestId: uuidv4() },
230 }),
231 );
232 });
233 // 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
234 useEffect(() => {
235 openDraft();
236 }, []);
237 return <OpeningThreadLoadingScreen />;
239​
240export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
241 return (
242 <ThreadScreenHost>
243 {props.route.params?.draft ? (
244 <NewTaskDraftRouteScreen
245 key={draftRouteIdentity(props.route.params.draft)}
246 route={{ ...props.route, params: props.route.params.draft }}
247 />
248 ) : (
249 <LiveThreadRouteController {...props} />
250 )}
251 </ThreadScreenHost>
252 );
254​
255function LiveThreadRouteController(props: ThreadRouteScreenProps) {
256 const gt = useGT();
257 useAndroidWorkspaceBack();
258 const connectionsReady = useConnectionsReady();
259 const { connectionState } = useRemoteConnectionStatus();
260 const { selectedThread } = useThreadSelection();
261 const params = props.route.params ?? {};
262 const environmentIdRaw = firstRouteParam(params.environmentId);
263 const threadIdRaw = firstRouteParam(params.threadId);
264 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
265 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
266 const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
267 const { onReconnectEnvironment } = useRemoteConnections();
268 const navigation = useNavigation();
269 const routeName = useRoute().name;
270 const routeConnectionState =
271 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
272 const routeThreadKey =
273 environmentId !== null && threadIdRaw !== null
274 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
275 : null;
276 const selectedThreadKey =
277 selectedThread === null
278 ? null
279 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
280 const selectedThreadDetailState = useSelectedThreadDetailState();
281 const detailError = selectedThreadDetailState.error;
282 const [errorBeforeConnected, setErrorBeforeConnected] = useState(() =>
283 routeConnectionState === "connected" ? Option.none<string>() : detailError,
284 );
285 if (routeConnectionState !== "connected" && errorBeforeConnected !== detailError) {
286 setErrorBeforeConnected(detailError);
287 }
288 const withInspectorHeader = (content: ReactNode) =>
289 props.inspectorPresentation ? (
290 <InspectorHeaderShownContext value>
291 <ThreadInspectorHeader
292 title={selectedThread?.title ?? gt("Thread")}
293 {...props.inspectorPresentation}
294 />
295 {content}
296 </InspectorHeaderShownContext>
297 ) : (
298 content
299 );
300​
301 if (environmentId === null || threadIdRaw === null) {
302 return withInspectorHeader(<OpeningThreadLoadingScreen />);
303 }
304​
305 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
306 // ThreadRouteContent draws its own inspector header so it can show the sync status.
307 return (
308 <InspectorHeaderShownContext value={props.inspectorPresentation !== undefined}>
309 <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />
310 </InspectorHeaderShownContext>
311 );
312 }
313​
314 const stillHydrating = threadRouteIsHydrating({
315 isLoadingConnections: !connectionsReady,
316 environmentRegistered: routeEnvironmentRuntime !== null,
317 localCacheRead:
318 routeEnvironmentShellState.cacheRead &&
319 selectedThreadDetailState !== EMPTY_ENVIRONMENT_THREAD_STATE,
320 connectionState: routeConnectionState,
321 shellStatus: routeEnvironmentShellState.status,
322 shellHasError: routeEnvironmentShellState.hasError,
323 detailStatus: selectedThreadDetailState.status,
324 detailHasError: threadDetailErrorIsCurrent({
325 connectionState: routeConnectionState,
326 error: detailError,
327 errorBeforeConnected,
328 }),
329 });
330​
331 if (stillHydrating) {
332 return withInspectorHeader(<OpeningThreadLoadingScreen />);
333 }
334​
335 if (
336 routeName === "Thread" &&
337 !props.inspectorPresentation &&
338 threadRouteOpensDraft({
339 connectionState: routeConnectionState,
340 detailStatus: selectedThreadDetailState.status,
341 })
342 ) {
343 return <UnavailableThreadDraftRedirect environmentId={environmentId} />;
344 }
345​
346 return withInspectorHeader(
347 <ThreadUnavailableScreen
348 actionLabel={
349 routeEnvironmentRuntime === null ? gt("Manage environments") : gt("Reconnect environment")
350 }
351 onAction={() => {
352 if (routeEnvironmentRuntime !== null) {
353 onReconnectEnvironment(environmentId);
354 return;
355 }
356 openSettings(navigation, "SettingsEnvironments");
357 }}
358 />,
359 );
361​
362function ThreadRouteContent(
363 props: ThreadRouteScreenProps & {
364 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
365 },
366) {
367 const gt = useGT();
368 const m = useMessages();
369 const { layout, showInspector, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
370 const { connectionState } = useRemoteConnectionStatus();
371 const { onReconnectEnvironment } = useRemoteConnections();
372 const {
373 selectedThread,
374 selectedThreadCreation,
375 selectedThreadDetailRef,
376 selectedThreadProject,
377 selectedEnvironmentConnection,
378 } = useThreadSelection();
379 useRememberThreadProject(selectedThreadProject);
380 const canOperateThread = useEnvironmentScope(
381 selectedThread?.environmentId ?? null,
382 AuthOrchestrationOperateScope,
383 );
384 const canReadTerminal = useEnvironmentScope(
385 selectedThread?.environmentId ?? null,
386 AuthTerminalReadScope,
387 );
388 const canOperateTerminal = useEnvironmentScope(
389 selectedThread?.environmentId ?? null,
390 AuthTerminalOperateScope,
391 );
392 const selectedThreadDetailState = props.selectedThreadDetailState;
393 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
394 const { selectedThreadCwd } = useSelectedThreadWorktree();
395 const startSideChat = useStartSideChat();
396 const composer = useThreadComposerState({ startSideChat });
397 const gitState = useSelectedThreadGitState();
398 const gitActions = useSelectedThreadGitActions();
399 const requests = useSelectedThreadRequests();
400 useThreadStatusAnnouncements({
401 threadKey:
402 selectedThread === null || isProviderNativeSubagentThread(selectedThread.source)
403 ? null
404 : scopedThreadKey(selectedThread.environmentId, selectedThread.id),
405 // A preview beside its host names its thread, so the two threads' statuses can't be confused.
406 subject:
407 props.inspectorPresentation !== undefined && "onMaximize" in props.inspectorPresentation
408 ? (selectedThread?.title ?? null)
409 : null,
410 approvalRequestId: requests.activePendingApproval?.requestId ?? null,
411 userInputRequestId: requests.activePendingUserInput?.requestId ?? null,
412 shellRequestId: selectedThread?.source.pendingRuntimeRequest?.id ?? null,
413 shellPendingUserInput: selectedThread?.hasPendingUserInput === true,
414 working: composer.activeWorkStartedAt !== null || composer.isCompacting,
415 run: composer.selectedThreadAnnouncedRun,
416 detailBehind: composer.selectedThreadDetailBehindShell,
417 });
418 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
419 const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, {
420 label: "resume queue",
421 reportFailure: false,
422 });
423 const continueThreadRun = useAtomCommand(threadEnvironment.startTurn, {
424 label: "continue thread",
425 reportFailure: false,
426 });
427 const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {
428 label: "set thread runtime mode",
429 reportFailure: false,
430 });
431 const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {
432 label: "set thread interaction mode",
433 reportFailure: false,
434 });
435 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
436 label: "load earlier thread history",
437 reportFailure: false,
438 });
439 const historyControls = (() => {
440 const history = selectedThreadDetailState.history;
441 if (!selectedThread) {
442 return undefined;
443 }
444 if (!history.hasMoreHistory && history.error === null) {
445 return undefined;
446 }
447 return {
448 hasMoreHistory: history.hasMoreHistory,
449 loading: history.loading,
450 error: history.error === null ? null : threadErrorText(history.error, m),
451 onLoadEarlier: () => {
452 void loadEarlierHistory({
453 environmentId: selectedThread.environmentId,
454 input: { threadId: selectedThread.id },
455 });
456 },
457 onLoadThrough: (throughEntryId: string) => {
458 void loadEarlierHistory({
459 environmentId: selectedThread.environmentId,
460 input: { threadId: selectedThread.id, throughEntryId },
461 });
462 },
463 };
464 })();
465 const navigation = useNavigation();
466 const selectDetail = useSelectWorkspaceDetail();
467 const openPullRequest = useOpenPullRequest();
468 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
469 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
470 const mergeBackRun =
471 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
472 const mergeBackBusyRef = useRef(false);
473 const handleMergeBack = async () => {
474 if (
475 mergeBackBusyRef.current ||
476 !selectedThread ||
477 mergeBackTargetThreadId === null ||
478 mergeBackRun === null
479 ) {
480 return;
481 }
482 mergeBackBusyRef.current = true;
483 const result = await mergeBack({
484 environmentId: selectedThread.environmentId,
485 input: {
486 sourceThreadId: selectedThread.id,
487 targetThreadId: mergeBackTargetThreadId,
488 runId: mergeBackRun.id,
489 creationSource: "mobile",
490 },
491 });
492 mergeBackBusyRef.current = false;
493 if (result._tag !== "Success") return;
494 selectDetail({
495 name: "Thread",
496 params: { environmentId: selectedThread.environmentId, threadId: mergeBackTargetThreadId },
497 });
498 };
499 const params = props.route.params ?? {};
500 const environmentIdRaw = firstRouteParam(params.environmentId);
501 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
502 const threadId = firstRouteParam(params.threadId);
503 const routeThreadIdentity =
504 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
505 // The chosen mode survives thread switches; "route" only applies while the route
506 // supplies an inspector, which is also the default whenever it does.
507 const [chosenInspectorMode, setChosenInspectorMode] = useState<ThreadInspectorMode | null>(null);
508 const previewTarget = props.inspectorPresentation ? undefined : params.inspector;
509 const inspectorMode = (() => {
510 if (previewTarget) return "preview";
511 const mode =
512 props.renderInspector === undefined
513 ? chosenInspectorMode === "route"
514 ? null
515 : chosenInspectorMode
516 : chosenInspectorMode === null || chosenInspectorMode === "route"
517 ? "route"
518 : chosenInspectorMode;
519 return mode === "files" && selectedThreadCwd === null ? null : mode;
520 })();
521 const revealPreview = useEffectEvent(() => showInspector());
522 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- opens the workspace navigator's inspector pane when route params bring a preview target
523 useEffect(() => {
524 if (previewTarget) revealPreview();
525 }, [previewTarget]);
526 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
527 const routeConnectionState =
528 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
529 const routeConnectionError = routeEnvironmentRuntime
530 ? runtimeConnectionErrorText(routeEnvironmentRuntime, m)
531 : null;
532 const selectedThreadWithDraftSettings = selectedThread
533 ? {
534 ...selectedThread,
535 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
536 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
537 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
538 }
539 : null;
540​
541 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
542 const delegatedFrom = selectedThread?.delegatedFrom ?? null;
543 const delegatedFromRef =
544 delegatedFrom === null
545 ? null
546 : scopeThreadRef(delegatedFrom.environmentId, delegatedFrom.threadId);
547 // The title it had at delegation, until this client sees the parent itself.
548 const delegatedFromThread = useThreadShell(delegatedFromRef);
549 const headerSubtitle = [
550 selectedThreadProject?.title ?? null,
551 selectedEnvironmentConnection?.environmentLabel ?? null,
552 // A linked environment's delegated task names its parent; other linked work its origin.
553 delegatedFrom !== null
554 ? gt("Subagent of {title}", { title: delegatedFromThread?.title ?? delegatedFrom.title })
555 : selectedThread?.linkOrigin
556 ? gt("From {origin}", { origin: selectedThread.linkOrigin.label })
557 : null,
558 ]
559 .filter(Boolean)
560 .join(" · ");
561 const gitStatus = useEnvironmentQuery(
562 selectedThread !== null && selectedThreadCwd !== null
563 ? vcsEnvironment.status({
564 environmentId: selectedThread.environmentId,
565 input: { cwd: selectedThreadCwd },
566 })
567 : null,
568 );
569 const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
570 environmentId: selectedThread?.environmentId ?? null,
571 threadId: selectedThread?.id ?? null,
572 });
573 const terminalMenuSessions = buildTerminalMenuSessions(
574 {
575 knownSessions: knownTerminalSessions ?? [],
576 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
577 },
578 m,
579 );
580 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
581 const handleReconnectEnvironment = () => {
582 if (!environmentId) {
583 return;
584 }
585 onReconnectEnvironment(environmentId);
586 };
587​
588 const gitActionProgressTarget = {
589 environmentId: selectedThread?.environmentId ?? null,
590 cwd: selectedThreadCwd,
591 };
592 const gitActionProgress = useGitActionProgress(
593 gitActionProgressTarget,
594 selectedThread === null
595 ? null
596 : { environmentId: selectedThread.environmentId, threadId: selectedThread.id },
597 );
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 ? { kind: "ready" as const }
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 const renderThreadRouteBody = () => (
1033 <>
1034 <GitActionProgressOverlay
1035 progress={gitActionProgress}
1036 onDismiss={dismissGitActionResult}
1037 onOpenPullRequest={openPullRequest}
1038 />
1039​
1040 <>
1041 <ThreadScreenBinding
1042 header={
1043 props.inspectorPresentation ? null : (
1044 <ThreadHeader
1045 title={selectedThread.title}
1046 subtitle={threadStatusLabel ?? headerSubtitle}
1047 gitControls={threadGitControlProps}
1048 hasThreadCwd={selectedThreadCwd !== null}
1049 inspectorMode={inspectorMode}
1050 onOpenFilesInspector={handleOpenFilesInspector}
1051 onReturnToThread={props.onReturnToThread}
1052 />
1055 canOperateThread={canOperateThread}
1056 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
1057 selectedThreadDetailRef={selectedThreadDetailRef}
1058 contentPresentation={contentPresentation}
1059 screenTone={connectionTone(
1060 routeConnectionState,
1061 routeEnvironmentRuntime?.connectionAwaitingApproval === true,
1062 m,
1063 )}
1064 connectionError={routeConnectionError}
1065 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
1066 feedbackSubmissions={composer.feedbackSubmissions}
1067 onDismissFeedback={composer.dismissFeedback}
1068 selectedThreadFeed={composer.selectedThreadFeed}
1069 pendingHandoff={composer.pendingHandoff}
1070 activityRun={composer.selectedThreadActivityRun}
1071 activeWorkStartedAt={
1072 creationState?.kind === "preparing" ||
1073 (worktreeSetup !== null && setupTurnStartedAt === null)
1074 ? null
1075 : composer.activeWorkStartedAt
1077 isCompacting={composer.isCompacting}
1078 compactBeforeSend={composer.compactBeforeSend}
1079 runlessWorkActive={composer.runlessWorkActive}
1080 extensionStatuses={composer.extensionStatuses}
1081 providerSubagentStatus={composer.providerSubagentStatus}
1082 creationState={creationState}
1083 worktreeSetup={
1084 worktreeSetup
1085 ? {
1086 snapshot: worktreeSetup,
1087 turnStarted: setupTurnStartedAt !== null,
1088 onCancel: handleCancelWorktreeSetup,
1089 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
1091 : null
1093 activePendingApproval={requests.activePendingApproval}
1094 activePendingApprovals={requests.activePendingApprovals}
1095 respondingApprovalId={requests.respondingApprovalId}
1096 activePendingUserInput={requests.activePendingUserInput}
1097 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1098 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1099 respondingUserInputId={requests.respondingUserInputId}
1100 connectionStateLabel={routeConnectionState}
1101 historyControls={historyControls}
1102 activeThreadBusy={composer.activeThreadBusy}
1103 canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null}
1104 queuedRunEdit={composer.queuedRunEdit}
1105 composerDraftKey={composer.composerDraftKey}
1106 followUpBehavior={composer.followUpBehavior}
1107 canSteerActiveTurn={composer.canSteerActiveTurn}
1108 isSavingQueuedEdit={composer.isSavingQueuedEdit}
1109 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
1110 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
1111 environmentId={selectedThread.environmentId}
1112 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1113 threadCwd={selectedThreadCwd}
1114 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1115 queuedMessages={
1116 selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"
1117 ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]
1118 : composer.selectedThreadQueuedMessages
1120 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1121 layoutVariant={layout.variant}
1122 usesAutomaticContentInsets={usesNativeHeaderGlass}
1123 onOpenConnectionEditor={handleOpenConnectionEditor}
1124 onChangeDraftMessage={composer.onChangeDraftMessage}
1125 onPickDraftMedia={composer.onPickDraftMedia}
1126 onPickDraftFiles={composer.onPickDraftFiles}
1127 onNativePasteImages={composer.onNativePasteImages}
1128 onNativePasteText={composer.onNativePasteText}
1129 onRemoveDraftImage={composer.onRemoveDraftImage}
1130 serverConfig={serverConfig}
1131 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1132 onResumeQueue={composer.canResume ? handleResumeQueue : null}
1133 onSendMessage={composer.onSendMessage}
1134 offersSideChat={composer.sideChatUnavailableReason === null}
1135 onSendCommand={composer.onSendCommand}
1136 onReconnectEnvironment={handleReconnectEnvironment}
1137 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1138 onRespondToApproval={requests.onRespondToApproval}
1139 onSelectUserInputOption={requests.onSelectUserInputOption}
1140 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1141 onSubmitUserInput={requests.onSubmitUserInput}
1142 onDismissUserInput={requests.onDismissUserInput}
1143 />
1144 </>
1145 </>
1146 );
1147​
1148 return (
1149 <>
1150 {inspectorHeader}
1151 {!props.inspectorPresentation && inspectorContent ? (
1152 <Inspector
1153 // A route's own inspector (files) opens once per thread; going back keeps the user's choice.
1154 revealKey={
1155 props.renderInspector !== undefined && selectedThreadCwd !== null
1156 ? (routeThreadIdentity ?? undefined)
1157 : undefined
1159 content={inspectorContent}
1160 />
1161 ) : null}
1162​
1163 {renderThreadRouteBody()}
1164 </>
1165 );
1167​
1168export function FullscreenThreadRouteScreen(
1169 props: StaticScreenProps<{
1170 readonly environmentId: string;
1171 readonly threadId: string;
1172 }>,
1173) {
1174 const navigation = useNavigation();
1175 return (
1176 <InspectorContentScope>
1177 <ThreadRouteScreen
1178 route={props.route}
1179 inspectorPresentation={{ onClose: () => navigation.goBack() }}
1180 />
1181 </InspectorContentScope>
1182 );
1184​
1185/** Reads the pane state itself, so a sidebar toggle doesn't re-render the whole thread screen. */
1186function ThreadInspectorPreviewWhileVisible(props: Parameters<typeof ThreadInspectorPreview>[0]) {
1187 const { panes } = useWorkspacePaneState();
1188 return panes.auxiliaryPaneVisible ? <ThreadInspectorPreview {...props} /> : null;