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