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