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