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 { 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;
140}
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 );
162}
163
164function OpeningThreadLoadingScreen() {
165 const gt = useGT();
166 return (
167 <ThreadRouteFallbackLayout>
168 <LoadingScreen message={gt("Opening thread…")} messagePlacement="above-spinner" embedded />
169 </ThreadRouteFallbackLayout>
170 );
171}
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;
185}
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 );
213}
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 />;
238}
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 );
253}
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 );
360}
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(gitActionProgressTarget);
593
594 const handleOpenGitInspector = () => {
595 navigation.setParams({ inspector: undefined });
596 setChosenInspectorMode("git");
597 showInspector();
598 };
599 const handleOpenFilesInspector = () => {
600 if (selectedThread === null || selectedThreadCwd === null) {
601 return;
602 }
603 navigation.setParams({ inspector: undefined });
604 setChosenInspectorMode(props.renderInspector === undefined ? "files" : "route");
605 showInspector();
606 };
607 const handleSelectInspectorFile = (path: string) => {
608 if (selectedThread === null) {
609 return;
610 }
611 const params = {
612 environmentId: String(selectedThread.environmentId),
613 threadId: String(selectedThread.id),
614 path: path.split("/").filter((segment) => segment.length > 0),
615 };
616 navigation.navigate("ThreadFile", params);
617 };
618 const renderGitInspector = () => (
619 <GitOverviewSheet
620 presentation="inspector"
621 route={{ params: { environmentId: environmentId!, threadId: threadId! } }}
622 />
623 );
624 const renderFilesInspector = () =>
625 selectedThread !== null && selectedThreadCwd !== null ? (
626 <InspectorSheetContext.Consumer>
627 {(closeInspectorSheet) => (
628 <ThreadFileNavigatorPane
629 cwd={selectedThreadCwd}
630 environmentId={selectedThread.environmentId}
631 projectName={selectedThreadProject?.title ?? gt("Files")}
632 selectedPath={null}
633 onSelectFile={(path) =>
634 closeInspectorSheet
635 ? closeInspectorSheet(() => handleSelectInspectorFile(path))
636 : handleSelectInspectorFile(path)
637 }
638 />
639 )}
640 </InspectorSheetContext.Consumer>
641 ) : null;
642 const renderPreviewInspector = () =>
643 previewTarget ? (
644 <ThreadInspectorPreviewWhileVisible
645 target={previewTarget}
646 renderThread={(screen) => <ThreadRouteScreen {...screen} />}
647 onClose={toggleAuxiliaryPane}
648 onOpen={(inspector) => {
649 if (
650 inspector.type === "thread" &&
651 inspector.environmentId === environmentId &&
652 inspector.threadId === threadId
653 ) {
654 toggleAuxiliaryPane();
655 return;
656 }
657 navigation.setParams({ inspector });
658 }}
659 />
660 ) : null;
661 const inspectorContent: InspectorContent | null =
662 inspectorMode === null
663 ? null
664 : {
665 active: inspectorMode,
666 resetKeys: [routeThreadIdentity, selectedThreadCwd],
667 panes: [
668 ...(inspectorMode === "preview"
669 ? [
670 {
671 key: "preview",
672 render: renderPreviewInspector,
673 },
674 ]
675 : []),
676 { key: "files", render: renderFilesInspector, prewarm: true },
677 { key: "git", render: renderGitInspector, prewarm: true },
678 ...(props.renderInspector ? [{ key: "route", render: props.renderInspector }] : []),
679 ],
680 };
681
682 const handleOpenConnectionEditor = () => {
683 void navigation.navigate("Connections");
684 };
685 const handleStopThread = () => {
686 if (
687 !selectedThread ||
688 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
689 composer.interruptibleRunId === null
690 ) {
691 return;
692 }
693 return interruptThreadTurn({
694 environmentId: selectedThread.environmentId,
695 input: {
696 threadId: selectedThread.id,
697 runId: composer.interruptibleRunId,
698 },
699 });
700 };
701
702 const handleResumeQueue = async () => {
703 if (!selectedThread) return;
704 const result = await resumeThread({
705 thread: selectedThread,
706 resumableRunId: composer.resumableRunId,
707 queueHeld: composer.queueHeld,
708 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
709 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
710 modelSelection: composer.modelSelection,
711 messageId: MessageId.make(uuidv4()),
712 createdAt: new Date().toISOString(),
713 setRuntimeMode: setThreadRuntimeMode,
714 setInteractionMode: setThreadInteractionMode,
715 startTurn: continueThreadRun,
716 resumeQueue: resumeThreadQueue,
717 });
718 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
719 const error = squashAtomCommandFailure(result);
720 Dialog.alert(
721 gt("Could not resume thread"),
722 errorDisplayMessage(error, m) ?? gt("Try again."),
723 );
724 }
725 };
726
727 const handleOpenTerminal = (nextTerminalId?: string | null) => {
728 if (
729 !selectedThread ||
730 !selectedThreadProject?.workspaceRoot ||
731 (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
732 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
733 ) {
734 return;
735 }
736
737 void navigation.navigate("ThreadTerminal", {
738 environmentId: String(selectedThread.environmentId),
739 threadId: String(selectedThread.id),
740 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
741 });
742 };
743
744 const handleOpenNewTerminal = () => {
745 if (
746 !selectedThread ||
747 !selectedThreadProject?.workspaceRoot ||
748 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
749 ) {
750 return;
751 }
752
753 const nextId = nextOpenTerminalId({
754 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
755 ...(knownTerminalSessions === null ||
756 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
757 ? { uniqueSuffix: uuidv4() }
758 : {}),
759 });
760 void navigation.navigate("ThreadTerminal", {
761 environmentId: String(selectedThread.environmentId),
762 threadId: String(selectedThread.id),
763 terminalId: nextId,
764 });
765 };
766
767 const handleRunProjectScript = async (script: ProjectScript) => {
768 if (
769 !selectedThread ||
770 !selectedThreadProject?.workspaceRoot ||
771 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
772 ) {
773 return;
774 }
775
776 const targetTerminalId = resolveProjectScriptTerminalId({
777 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
778 ...(knownTerminalSessions === null ||
779 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
780 ? { uniqueSuffix: uuidv4() }
781 : {}),
782 hasRunningTerminal: terminalMenuSessions.some(
783 (session) => session.status === "running" || session.status === "starting",
784 ),
785 });
786 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
787 threadShellWorktreePath: selectedThread.worktreePath ?? null,
788 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
789 });
790 const cwd = projectScriptCwd({
791 project: { cwd: selectedThreadProject.workspaceRoot },
792 worktreePath: preferredWorktreePath,
793 });
794 const env = projectScriptRuntimeEnv({
795 project: { cwd: selectedThreadProject.workspaceRoot },
796 worktreePath: preferredWorktreePath,
797 });
798 stagePendingTerminalLaunch({
799 target: {
800 environmentId: selectedThread.environmentId,
801 threadId: selectedThread.id,
802 terminalId: targetTerminalId,
803 },
804 launch: {
805 cwd,
806 worktreePath: preferredWorktreePath,
807 env,
808 initialInput: projectScriptTerminalInput(script.command),
809 stopOnSettle: script.stopOnSettle ?? false,
810 },
811 });
812
813 void navigation.navigate("ThreadTerminal", {
814 environmentId: String(selectedThread.environmentId),
815 threadId: String(selectedThread.id),
816 terminalId: targetTerminalId,
817 });
818 };
819 const threadGitControlProps = {
820 environmentId: environmentIdRaw ?? "",
821 threadId: threadId ?? "",
822 onOpenFilesInspector: selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
823 onOpenGitInspector: handleOpenGitInspector,
824 onMergeBack:
825 mergeBackTargetThreadId !== null && mergeBackRun !== null
826 ? () => void handleMergeBack()
827 : undefined,
828 currentBranch: selectedThread?.branch ?? null,
829 gitStatus: gitStatus.data,
830 gitOperationLabel: gitState.gitOperationLabel,
831 canOpenTerminal:
832 Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
833 canOperateTerminal,
834 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
835 projectScripts: selectedThreadProject
836 ? resolveProjectScripts(
837 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
838 selectedThreadProject,
839 )
840 : [],
841 terminalSessions: terminalMenuSessions,
842 onOpenTerminal: handleOpenTerminal,
843 onOpenNewTerminal: handleOpenNewTerminal,
844 onRunProjectScript: handleRunProjectScript,
845 onPull: gitActions.onPullSelectedThreadBranch,
846 onRunAction: gitActions.onRunSelectedThreadGitAction,
847 };
848 const handleEditFailedCreation = async () => {
849 const creation = selectedThreadCreation?.message;
850 if (!creation?.creation || routeThreadIdentity === null) {
851 return;
852 }
853 // Open recovery by draft id or the sheet creates an empty draft and strands restored content.
854 try {
855 await recoverFailedThreadDraft(creation);
856 } catch (error) {
857 Dialog.alert(gt("Could not restore draft"), errorDisplayMessage(error, m) ?? String(error));
858 return;
859 }
860 clearPendingThreadCreationOutcome(routeThreadIdentity);
861 navigation.dispatch(
862 StackActions.replace("Thread", {
863 draft: {
864 draftId: restoredNewTaskDraftKey(creation.messageId),
865 environmentId: String(creation.environmentId),
866 projectId: String(creation.creation.projectId),
867 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
868 },
869 }),
870 );
871 };
872 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
873 const { visible: worktreeSetup } = useWorktreeSetup({
874 environmentId: selectedThread?.environmentId ?? null,
875 threadId: selectedThread?.id ?? null,
876 preparing:
877 composer.selectedThreadActivityRun?.status === "preparing" ||
878 selectedThread?.runtime?.status === "preparing" ||
879 selectedThread?.worktreePath != null ||
880 (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
881 selectedThreadCreation.outcome == null),
882 runs: selectedThreadDetail?.runs ?? [],
883 followUpSent:
884 composer.selectedThreadFeed.filter(
885 (entry) => entry.type === "message" && entry.message.role === "user",
886 ).length +
887 composer.selectedThreadQueueCount >
888 1,
889 });
890 const awaitingBootstrapTurn =
891 worktreeSetup !== null
892 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
893 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
894 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
895 const handleCancelWorktreeSetup = () => {
896 if (!selectedThread) return;
897 void cancelWorktreeSetup({
898 environmentId: selectedThread.environmentId,
899 input: { threadId: selectedThread.id },
900 });
901 };
902 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
903 const localResendBusy = useRef(false);
904 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
905 const handleWorkLocally = async () => {
906 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
907 return;
908 localResendBusy.current = true;
909 const result = await cancelWorktreeSetup({
910 environmentId: selectedThread.environmentId,
911 input: { threadId: selectedThread.id },
912 });
913 if (result._tag !== "Success" || !result.value.cancelled) {
914 localResendBusy.current = false;
915 return;
916 }
917 // V2 accepts launch before setup; cancellation cannot reject that delivery, so reuse server-owned prompt and uploads.
918 const metadata = makeTurnCommandMetadata();
919 const launched = await startLocalThread({
920 environmentId: selectedThread.environmentId,
921 input: buildProjectThreadStartTurnInput({
922 ...metadata,
923 projectId: selectedThread.projectId,
924 projectCwd: selectedThreadProject.workspaceRoot,
925 text: setupMessage.text,
926 titleText: selectedThread.title,
927 ...(setupMessage.context ? { context: setupMessage.context } : {}),
928 uploadedAttachments: setupMessage.attachments,
929 modelSelection: selectedThread.modelSelection,
930 runtimeMode: selectedThread.runtimeMode,
931 interactionMode: selectedThread.interactionMode,
932 workspaceMode: "local",
933 branch: null,
934 worktreePath: null,
935 startFromOrigin: false,
936 worktreeBranchName: "",
937 }),
938 });
939 localResendBusy.current = false;
940 if (launched._tag !== "Success") return;
941 navigation.dispatch(
942 StackActions.replace("Thread", {
943 environmentId: String(selectedThread.environmentId),
944 threadId: metadata.threadId,
945 }),
946 );
947 };
948 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
949 if (selectedThreadCreation === null) {
950 return awaitingBootstrapTurn
951 ? { kind: "preparing", preparingWorktree: true, serverOwned: true }
952 : null;
953 }
954 if (selectedThreadCreation.outcome?.kind === "failed") {
955 return {
956 kind: "failed",
957 reason: selectedThreadCreation.outcome.reason,
958 onEditTask: handleEditFailedCreation,
959 };
960 }
961 return {
962 kind: "preparing",
963 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
964 serverOwned: false,
965 };
966 })();
967 // Queued creation displays its prompt before server creation; temporary not-found is expected.
968 const contentPresentation =
969 creationState !== null
970 ? { kind: "ready" as const }
971 : projectThreadContentPresentation({
972 hasDetail: selectedThreadDetail !== null,
973 detailError: Option.getOrNull(selectedThreadDetailState.error),
974 detailDeleted: selectedThreadDetailState.status === "deleted",
975 connectionState: routeConnectionState,
976 resolve: m,
977 });
978 const connectionRetrying =
979 routeConnectionState === "connecting" || routeConnectionState === "reconnecting";
980 // Connection failures survive retries and app suspension.
981 const retryConnectionError = useDelayedStatus(
982 `${environmentId}:${connectionRetrying && routeConnectionError !== null}`,
983 connectionRetrying ? routeConnectionError : null,
984 RECONNECT_ERROR_DELAY_MS,
985 );
986 const connectionStatusLabel = connectionRetryLabel(
987 {
988 connectionError: retryConnectionError,
989 connectionState: routeConnectionState,
990 connectionAwaitingApproval: routeEnvironmentRuntime?.connectionAwaitingApproval === true,
991 },
992 m,
993 );
994 // A thread this client is creating has nothing older to sync.
995 const threadSyncLabel =
996 creationState === null
997 ? threadSyncStatusLabel(
998 selectedThreadDetailState.status,
999 contentPresentation.kind,
1000 Option.isSome(selectedThreadDetailState.error),
1001 m,
1002 )
1003 : null;
1004 // Transient states go in the header subtitle so the composer's status slot doesn't jump.
1005 const threadStatusLabel = useDelayedStatus(
1006 selectedThread === null ? "" : scopedThreadKey(selectedThread.environmentId, selectedThread.id),
1007 connectionStatusLabel !== null ? connectionStatusLabel : threadSyncLabel,
1008 );
1009 const inspectorHeader = props.inspectorPresentation ? (
1010 <ThreadInspectorHeader
1011 title={selectedThread?.title ?? gt("Thread")}
1012 subtitle={threadStatusLabel ?? undefined}
1013 {...props.inspectorPresentation}
1014 />
1015 ) : null;
1016 if (!environmentId || !threadId || !selectedThread) {
1017 return (
1018 <>
1019 {inspectorHeader}
1020 <OpeningThreadLoadingScreen />
1021 </>
1022 );
1023 }
1024
1025 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
1026 const renderThreadRouteBody = () => (
1027 <>
1028 <GitActionProgressOverlay
1029 progress={gitActionProgress}
1030 onDismiss={dismissGitActionResult}
1031 onOpenPullRequest={openPullRequest}
1032 />
1033
1034 <>
1035 <ThreadScreenBinding
1036 header={
1037 props.inspectorPresentation ? null : (
1038 <ThreadHeader
1039 title={selectedThread.title}
1040 subtitle={threadStatusLabel ?? headerSubtitle}
1041 gitControls={threadGitControlProps}
1042 hasThreadCwd={selectedThreadCwd !== null}
1043 inspectorMode={inspectorMode}
1044 onOpenFilesInspector={handleOpenFilesInspector}
1045 onReturnToThread={props.onReturnToThread}
1046 />
1047 )
1048 }
1049 canOperateThread={canOperateThread}
1050 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
1051 selectedThreadDetailRef={selectedThreadDetailRef}
1052 contentPresentation={contentPresentation}
1053 screenTone={connectionTone(
1054 routeConnectionState,
1055 routeEnvironmentRuntime?.connectionAwaitingApproval === true,
1056 m,
1057 )}
1058 connectionError={routeConnectionError}
1059 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
1060 feedbackSubmissions={composer.feedbackSubmissions}
1061 onDismissFeedback={composer.dismissFeedback}
1062 selectedThreadFeed={composer.selectedThreadFeed}
1063 pendingHandoff={composer.pendingHandoff}
1064 activityRun={composer.selectedThreadActivityRun}
1065 activeWorkStartedAt={
1066 creationState?.kind === "preparing" ||
1067 (worktreeSetup !== null && setupTurnStartedAt === null)
1068 ? null
1069 : composer.activeWorkStartedAt
1070 }
1071 isCompacting={composer.isCompacting}
1072 compactBeforeSend={composer.compactBeforeSend}
1073 runlessWorkActive={composer.runlessWorkActive}
1074 extensionStatuses={composer.extensionStatuses}
1075 providerSubagentStatus={composer.providerSubagentStatus}
1076 creationState={creationState}
1077 worktreeSetup={
1078 worktreeSetup
1079 ? {
1080 snapshot: worktreeSetup,
1081 turnStarted: setupTurnStartedAt !== null,
1082 onCancel: handleCancelWorktreeSetup,
1083 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
1084 }
1085 : null
1086 }
1087 activePendingApproval={requests.activePendingApproval}
1088 activePendingApprovals={requests.activePendingApprovals}
1089 respondingApprovalId={requests.respondingApprovalId}
1090 activePendingUserInput={requests.activePendingUserInput}
1091 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1092 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1093 respondingUserInputId={requests.respondingUserInputId}
1094 connectionStateLabel={routeConnectionState}
1095 historyControls={historyControls}
1096 activeThreadBusy={composer.activeThreadBusy}
1097 canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null}
1098 queuedRunEdit={composer.queuedRunEdit}
1099 composerDraftKey={composer.composerDraftKey}
1100 followUpBehavior={composer.followUpBehavior}
1101 canSteerActiveTurn={composer.canSteerActiveTurn}
1102 isSavingQueuedEdit={composer.isSavingQueuedEdit}
1103 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
1104 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
1105 environmentId={selectedThread.environmentId}
1106 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1107 threadCwd={selectedThreadCwd}
1108 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1109 queuedMessages={
1110 selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"
1111 ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]
1112 : composer.selectedThreadQueuedMessages
1113 }
1114 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1115 layoutVariant={layout.variant}
1116 usesAutomaticContentInsets={usesNativeHeaderGlass}
1117 onOpenConnectionEditor={handleOpenConnectionEditor}
1118 onChangeDraftMessage={composer.onChangeDraftMessage}
1119 onPickDraftMedia={composer.onPickDraftMedia}
1120 onPickDraftFiles={composer.onPickDraftFiles}
1121 onNativePasteImages={composer.onNativePasteImages}
1122 onNativePasteText={composer.onNativePasteText}
1123 onRemoveDraftImage={composer.onRemoveDraftImage}
1124 serverConfig={serverConfig}
1125 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1126 onResumeQueue={composer.canResume ? handleResumeQueue : null}
1127 onSendMessage={composer.onSendMessage}
1128 offersSideChat={composer.sideChatUnavailableReason === null}
1129 onSendCommand={composer.onSendCommand}
1130 onReconnectEnvironment={handleReconnectEnvironment}
1131 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1132 onRespondToApproval={requests.onRespondToApproval}
1133 onSelectUserInputOption={requests.onSelectUserInputOption}
1134 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1135 onSubmitUserInput={requests.onSubmitUserInput}
1136 onDismissUserInput={requests.onDismissUserInput}
1137 />
1138 </>
1139 </>
1140 );
1141
1142 return (
1143 <>
1144 {inspectorHeader}
1145 {!props.inspectorPresentation && inspectorContent ? (
1146 <Inspector
1147 // A route's own inspector (files) opens once per thread; going back keeps the user's choice.
1148 revealKey={
1149 props.renderInspector !== undefined && selectedThreadCwd !== null
1150 ? (routeThreadIdentity ?? undefined)
1151 : undefined
1152 }
1153 content={inspectorContent}
1154 />
1155 ) : null}
1156
1157 {renderThreadRouteBody()}
1158 </>
1159 );
1160}
1161
1162export function FullscreenThreadRouteScreen(
1163 props: StaticScreenProps<{
1164 readonly environmentId: string;
1165 readonly threadId: string;
1166 }>,
1167) {
1168 const navigation = useNavigation();
1169 return (
1170 <InspectorContentScope>
1171 <ThreadRouteScreen
1172 route={props.route}
1173 inspectorPresentation={{ onClose: () => navigation.goBack() }}
1174 />
1175 </InspectorContentScope>
1176 );
1177}
1178
1179/** Reads the pane state itself, so a sidebar toggle doesn't re-render the whole thread screen. */
1180function ThreadInspectorPreviewWhileVisible(props: Parameters<typeof ThreadInspectorPreview>[0]) {
1181 const { panes } = useWorkspacePaneState();
1182 return panes.auxiliaryPaneVisible ? <ThreadInspectorPreview {...props} /> : null;
1183}