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