Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import { useOpenPullRequest } from "../../native/useOpenPullRequest";
3import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
4import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
5import { useWorktreeSetup } from "./use-worktree-setup";
6import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
7import { AppBar } from "../../components/ui/AppBar";
8import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
9import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
10import * as Option from "effect/Option";
11import {
12 AuthOrchestrationOperateScope,
13 AuthTerminalOperateScope,
14 AuthTerminalReadScope,
15 DEFAULT_SERVER_SETTINGS,
16 EnvironmentId,
17 ThreadId,
18 type ProjectScript,
19} from "@t3tools/contracts";
20import {
21 projectScriptCwd,
22 projectScriptRuntimeEnv,
23 projectScriptTerminalInput,
24 resolveProjectScripts,
25} from "@t3tools/shared/projectScripts";
26import { Platform } from "react-native";
27import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
28import { useSafeAreaInsets } from "react-native-safe-area-context";
29import { useConnectionsReady } from "../../state/workspace";
30import { useEnvironmentShellReadiness } from "../../state/shell";
31import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
32import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
33import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
34import { useEnvironmentQuery } from "../../state/query";
35import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
36import { vcsEnvironment } from "../../state/vcs";
37import { EmptyState } from "../../components/ui/EmptyState";
38import { LoadingScreen } from "../../components/LoadingScreen";
39import { scopedThreadKey } from "../../lib/scopedEntities";
40import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
41import { connectionTone } from "../connection/connectionTone";
42import {
43 useRemoteConnections,
44 useRemoteConnectionStatus,
45 useRemoteEnvironmentRuntime,
46} from "../../state/use-remote-environment-registry";
47import { useKnownTerminalSessions } from "../../state/use-terminal-session";
48import { uuidv4 } from "../../lib/uuid";
49import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
50import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
51import { useThreadSelection } from "../../state/use-thread-selection";
52import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
53import {
54 buildTerminalMenuSessions,
55 nextOpenTerminalId,
56 resolveProjectScriptTerminalId,
57} from "../terminal/terminalMenu";
58import {
59 resolvePreferredThreadWorktreePath,
60 stagePendingTerminalLaunch,
61} from "../terminal/terminalLaunchContext";
62import { terminalDebugLog } from "../terminal/terminalDebugLog";
63import type { ThreadDetailScreenProps } from "./ThreadDetailScreen";
64import { ThreadScreenBinding, ThreadScreenFallback, ThreadScreenHost } from "./ThreadScreenHost";
65import { draftRouteIdentity } from "./thread-route-state";
66import { NewTaskDraftRouteScreen, type NewTaskDraftRouteParams } from "./NewTaskDraftRouteScreen";
67import { GitOverviewSheet } from "./git/GitOverviewSheet";
68import { useAtomCommand } from "../../state/use-atom-command";
69import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
70import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
71import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
72import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
73import { useThreadComposerState } from "../../state/use-thread-composer-state";
74import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
75import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
76import { threadEnvironment, useThreadFamily } from "../../state/threads";
77import { projectThreadContentPresentation } from "./threadContentPresentation";
78import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
79import {
80 useAdaptiveWorkspaceLayout,
81 useAdaptiveWorkspacePaneRole,
82 useRegisterWorkspaceInspector,
83} from "../layout/AdaptiveWorkspaceLayout";
84import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
85import {
86 ThreadInspectorContentStack,
87 type ThreadInspectorMode,
88} from "./thread-inspector-content-stack";
89import { threadRouteIsHydrating } from "./thread-route-hydration";
90import { useThreadPromptLink } from "../prompt-links/useThreadPromptLink";
91import { ThreadHeader } from "./ThreadHeader";
92import {
93 useAndroidWorkspaceBack,
94 useWorkspaceBackNavigation,
95} from "../workspace/useAndroidWorkspaceNavigation";
96import { openSettings } from "../settings/settings-navigation";
97import {
98 InspectorContentScope,
99 ThreadInspectorHeader,
100 ThreadInspectorPreview,
101 type ThreadInspectorPresentation,
102} from "./thread-inspector-preview";
103import type { ThreadInspectorTarget } from "./thread-inspector-navigation";
104import { useSelectWorkspaceDetail } from "../workspace/useSelectWorkspaceDetail";
105
106interface ThreadInspectorSelection {
107 readonly routeThreadIdentity: string | null;
108 readonly mode: ThreadInspectorMode;
109}
110
111function InspectorPaneRoleActivation() {
112 useAdaptiveWorkspacePaneRole("inspector");
113 return null;
114}
115
116function firstRouteParam(value: string | string[] | undefined): string | null {
117 const first = Array.isArray(value) ? value[0] : value;
118 return first === undefined || first.trim().length === 0 ? null : first;
119}
120
121function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) {
122 const goBack = useWorkspaceBackNavigation("threads");
123 const { layout } = useAdaptiveWorkspaceLayout();
124 const { themeVariables } = useAppearancePreferences();
125 if (Platform.OS !== "android")
126 return <ThreadScreenFallback>{props.children}</ThreadScreenFallback>;
127
128 return (
129 <>
130 <AppBar
131 title="Thread"
132 options={{ contentStyle: { backgroundColor: themeVariables["--color-header"] } }}
133 onBack={layout.usesSplitView ? undefined : goBack}
134 hideBottomBorder
135 />
136 <ThreadScreenFallback>{props.children}</ThreadScreenFallback>
137 </>
138 );
139}
140
141function OpeningThreadLoadingScreen() {
142 return (
143 <ThreadRouteFallbackLayout>
144 <LoadingScreen
145 message="Opening thread…"
146 messagePlacement="above-spinner"
147 embedded={Platform.OS === "android"}
148 />
149 </ThreadRouteFallbackLayout>
150 );
151}
152
153type ThreadRouteScreenRouteProps = StaticScreenProps<{
154 readonly environmentId?: string;
155 readonly threadId?: string;
156 readonly draft?: NewTaskDraftRouteParams;
157 readonly inspector?: ThreadInspectorTarget;
158 readonly prompt?: string | string[];
159}>;
160
161interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
162 readonly inspectorPresentation?: ThreadInspectorPresentation;
163 readonly onReturnToThread?: () => void;
164 readonly renderInspector?: (headerInset: number) => ReactNode;
165}
166
167function ThreadUnavailableScreen(props: {
168 readonly actionLabel: string;
169 readonly onAction: () => void;
170}) {
171 return (
172 <ThreadRouteFallbackLayout>
173 <ScrollView
174 contentInsetAdjustmentBehavior="automatic"
175 contentContainerStyle={{
176 flexGrow: 1,
177 justifyContent: "center",
178 paddingHorizontal: 24,
179 paddingVertical: 32,
180 }}
181 className="bg-screen flex-1 android:bg-transparent"
182 >
183 <EmptyState
184 title="Thread unavailable"
185 detail="This thread is not available in the current mobile snapshot."
186 actionLabel={props.actionLabel}
187 onAction={props.onAction}
188 />
189 </ScrollView>
190 </ThreadRouteFallbackLayout>
191 );
192}
193
194export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
195 return (
196 <ThreadScreenHost>
197 {props.route.params?.draft ? (
198 <NewTaskDraftRouteScreen
199 key={draftRouteIdentity(props.route.params.draft)}
200 route={{ ...props.route, params: props.route.params.draft }}
201 />
202 ) : (
203 <LiveThreadRouteController {...props} />
204 )}
205 </ThreadScreenHost>
206 );
207}
208
209function LiveThreadRouteController(props: ThreadRouteScreenProps) {
210 useAndroidWorkspaceBack("threads");
211 const connectionsReady = useConnectionsReady();
212 const { connectionState } = useRemoteConnectionStatus();
213 const { selectedThread } = useThreadSelection();
214 // Subagent rows, the open child's own row and its ancestors come from the family when the
215 // shell leaves idle children out.
216 useThreadFamily(
217 selectedThread?.environmentId ?? null,
218 selectedThread?.lineage.rootThreadId ?? null,
219 );
220 const params = props.route.params ?? {};
221 const environmentIdRaw = firstRouteParam(params.environmentId);
222 const threadIdRaw = firstRouteParam(params.threadId);
223 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
224 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
225 const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
226 const { onReconnectEnvironment } = useRemoteConnections();
227 const navigation = useNavigation();
228 const routeConnectionState =
229 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
230 const routeThreadKey =
231 environmentId !== null && threadIdRaw !== null
232 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
233 : null;
234 const selectedThreadKey =
235 selectedThread === null
236 ? null
237 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
238 const selectedThreadDetailState = useSelectedThreadDetailState();
239 useThreadPromptLink(params, routeThreadKey);
240 const withInspectorHeader = (content: ReactNode) => (
241 <>
242 {props.inspectorPresentation ? (
243 <ThreadInspectorHeader
244 title={selectedThread?.title ?? "Thread"}
245 {...props.inspectorPresentation}
246 />
247 ) : null}
248 {content}
249 </>
250 );
251
252 if (environmentId === null || threadIdRaw === null) {
253 return withInspectorHeader(<OpeningThreadLoadingScreen />);
254 }
255
256 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
257 return withInspectorHeader(
258 <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />,
259 );
260 }
261
262 const stillHydrating = threadRouteIsHydrating({
263 isLoadingConnections: !connectionsReady,
264 connectionState: routeConnectionState,
265 shellStatus: routeEnvironmentShellState.status,
266 shellHasError: routeEnvironmentShellState.hasError,
267 detailStatus: selectedThreadDetailState.status,
268 detailHasError: Option.isSome(selectedThreadDetailState.error),
269 });
270
271 if (stillHydrating) {
272 return withInspectorHeader(<OpeningThreadLoadingScreen />);
273 }
274
275 return withInspectorHeader(
276 <ThreadUnavailableScreen
277 actionLabel={
278 routeEnvironmentRuntime === null ? "Manage environments" : "Reconnect environment"
279 }
280 onAction={() => {
281 if (routeEnvironmentRuntime !== null) {
282 onReconnectEnvironment(environmentId);
283 return;
284 }
285 openSettings(navigation, "SettingsEnvironments");
286 }}
287 />,
288 );
289}
290
291function ThreadRouteContent(
292 props: ThreadRouteScreenProps & {
293 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
294 },
295) {
296 const { themeVariables } = useAppearancePreferences();
297 const headerColor = themeVariables["--color-header"];
298 const { fileInspector, layout, panes, showAuxiliaryPane, toggleAuxiliaryPane } =
299 useAdaptiveWorkspaceLayout();
300 const { connectionState } = useRemoteConnectionStatus();
301 const { onReconnectEnvironment } = useRemoteConnections();
302 const {
303 selectedThread,
304 selectedThreadCreation,
305 selectedThreadDetailRef,
306 selectedThreadProject,
307 selectedEnvironmentConnection,
308 } = useThreadSelection();
309 const canOperateThread = useEnvironmentScope(
310 selectedThread?.environmentId ?? null,
311 AuthOrchestrationOperateScope,
312 );
313 const canReadTerminal = useEnvironmentScope(
314 selectedThread?.environmentId ?? null,
315 AuthTerminalReadScope,
316 );
317 const canOperateTerminal = useEnvironmentScope(
318 selectedThread?.environmentId ?? null,
319 AuthTerminalOperateScope,
320 );
321 const selectedThreadDetailState = props.selectedThreadDetailState;
322 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
323 const { selectedThreadCwd } = useSelectedThreadWorktree();
324 const composer = useThreadComposerState();
325 const gitState = useSelectedThreadGitState();
326 const gitActions = useSelectedThreadGitActions();
327 const requests = useSelectedThreadRequests();
328 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
329 const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue");
330 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
331 label: "load earlier thread history",
332 reportFailure: false,
333 });
334 const historyControls = (() => {
335 const history = selectedThreadDetailState.history;
336 if (!selectedThread) {
337 return undefined;
338 }
339 if (!history.hasMoreHistory && history.error === null) {
340 return undefined;
341 }
342 return {
343 hasMoreHistory: history.hasMoreHistory,
344 loading: history.loading,
345 error: history.error,
346 onLoadEarlier: () => {
347 void loadEarlierHistory({
348 environmentId: selectedThread.environmentId,
349 input: { threadId: selectedThread.id },
350 });
351 },
352 onLoadThrough: (throughEntryId: string) => {
353 void loadEarlierHistory({
354 environmentId: selectedThread.environmentId,
355 input: { threadId: selectedThread.id, throughEntryId },
356 });
357 },
358 };
359 })();
360 const navigation = useNavigation();
361 const selectDetail = useSelectWorkspaceDetail();
362 const openPullRequest = useOpenPullRequest();
363 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
364 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
365 const mergeBackRun =
366 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
367 const mergeBackBusyRef = useRef(false);
368 const handleMergeBack = async () => {
369 if (
370 mergeBackBusyRef.current ||
371 !selectedThread ||
372 mergeBackTargetThreadId === null ||
373 mergeBackRun === null
374 ) {
375 return;
376 }
377 mergeBackBusyRef.current = true;
378 const result = await mergeBack({
379 environmentId: selectedThread.environmentId,
380 input: {
381 sourceThreadId: selectedThread.id,
382 targetThreadId: mergeBackTargetThreadId,
383 runId: mergeBackRun.id,
384 creationSource: "mobile",
385 },
386 });
387 mergeBackBusyRef.current = false;
388 if (result._tag !== "Success") return;
389 selectDetail({
390 name: "Thread",
391 params: { environmentId: selectedThread.environmentId, threadId: mergeBackTargetThreadId },
392 });
393 };
394 const params = props.route.params ?? {};
395 const environmentIdRaw = firstRouteParam(params.environmentId);
396 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
397 const threadId = firstRouteParam(params.threadId);
398 const routeThreadIdentity =
399 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
400 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
401 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
402 );
403 const previewTarget = props.inspectorPresentation ? undefined : params.inspector;
404 const inspectorMode = (() => {
405 if (previewTarget) return "preview";
406 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
407 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
408 return null;
409 }
410 return inspectorSelection.mode;
411 }
412 return null;
413 })();
414 useEffect(() => {
415 if (
416 props.inspectorPresentation === undefined &&
417 fileInspector.supported &&
418 selectedThreadCwd === null &&
419 inspectorMode === null &&
420 panes.auxiliaryPaneVisible
421 ) {
422 toggleAuxiliaryPane();
423 }
424 }, [
425 fileInspector.supported,
426 inspectorMode,
427 panes.auxiliaryPaneVisible,
428 props.inspectorPresentation,
429 selectedThreadCwd,
430 toggleAuxiliaryPane,
431 ]);
432
433 useEffect(() => {
434 // oxlint-disable-next-line react/set-state-in-effect -- Inspector selection follows route ownership but keeps an inspector the user opened.
435 setInspectorSelection((current) => {
436 if (props.renderInspector === undefined) {
437 if (current === null || current.mode === "route") {
438 return null;
439 }
440 return { ...current, routeThreadIdentity };
441 }
442
443 if (current === null || current.mode === "route") {
444 return { routeThreadIdentity, mode: "route" };
445 }
446
447 return { ...current, routeThreadIdentity };
448 });
449 }, [props.renderInspector, routeThreadIdentity]);
450
451 const revealPreview = useEffectEvent(() => showAuxiliaryPane("inspector"));
452 useEffect(() => {
453 if (previewTarget) revealPreview();
454 }, [previewTarget]);
455 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
456 const routeConnectionState =
457 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
458 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
459 const selectedThreadWithDraftSettings = selectedThread
460 ? {
461 ...selectedThread,
462 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
463 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
464 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
465 }
466 : null;
467
468 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
469 const headerSubtitle = [
470 selectedThreadProject?.title ?? null,
471 selectedEnvironmentConnection?.environmentLabel ?? null,
472 ]
473 .filter(Boolean)
474 .join(" · ");
475 const gitStatus = useEnvironmentQuery(
476 selectedThread !== null && selectedThreadCwd !== null
477 ? vcsEnvironment.status({
478 environmentId: selectedThread.environmentId,
479 input: { cwd: selectedThreadCwd },
480 })
481 : null,
482 );
483 const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
484 environmentId: selectedThread?.environmentId ?? null,
485 threadId: selectedThread?.id ?? null,
486 });
487 const terminalMenuSessions = buildTerminalMenuSessions({
488 knownSessions: knownTerminalSessions ?? [],
489 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
490 });
491 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
492 const handleReconnectEnvironment = () => {
493 if (!environmentId) {
494 return;
495 }
496 onReconnectEnvironment(environmentId);
497 };
498
499 const gitActionProgressTarget = {
500 environmentId: selectedThread?.environmentId ?? null,
501 cwd: selectedThreadCwd,
502 };
503 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
504
505 const handleOpenGitInspector = () => {
506 if (!fileInspector.supported) {
507 if (selectedThread === null) {
508 return;
509 }
510 navigation.navigate("GitOverview", {
511 environmentId: String(selectedThread.environmentId),
512 threadId: String(selectedThread.id),
513 });
514 return;
515 }
516 navigation.setParams({ inspector: undefined });
517 setInspectorSelection({ routeThreadIdentity, mode: "git" });
518 showAuxiliaryPane("inspector");
519 };
520 const handleOpenFilesInspector = () => {
521 if (selectedThread === null || selectedThreadCwd === null) {
522 return;
523 }
524 if (!fileInspector.supported) {
525 navigation.navigate("ThreadFiles", {
526 environmentId: String(selectedThread.environmentId),
527 threadId: String(selectedThread.id),
528 });
529 return;
530 }
531 navigation.setParams({ inspector: undefined });
532 setInspectorSelection({
533 routeThreadIdentity,
534 mode: props.renderInspector === undefined ? "files" : "route",
535 });
536 showAuxiliaryPane("inspector");
537 };
538 const handleToggleInspector = () => {
539 if (inspectorMode === null) {
540 handleOpenFilesInspector();
541 return;
542 }
543 toggleAuxiliaryPane();
544 };
545 const handleSelectInspectorFile = (path: string) => {
546 if (selectedThread === null) {
547 return;
548 }
549 const params = {
550 environmentId: String(selectedThread.environmentId),
551 threadId: String(selectedThread.id),
552 path: path.split("/").filter((segment) => segment.length > 0),
553 };
554 if (fileInspector.supported) {
555 navigation.navigate("ThreadFile", params);
556 return;
557 }
558 navigation.navigate("ThreadFile", params);
559 };
560 const safeAreaInsets = useSafeAreaInsets();
561 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
562 const renderGitInspector = () => (
563 <GitOverviewSheet
564 headerInset={inspectorHeaderInset}
565 presentation="inspector"
566 route={{ params: { environmentId: environmentId!, threadId: threadId! } }}
567 />
568 );
569 const renderFilesInspector = () =>
570 selectedThread !== null && selectedThreadCwd !== null ? (
571 <ThreadFileNavigatorPane
572 cwd={selectedThreadCwd}
573 environmentId={selectedThread.environmentId}
574 headerInset={inspectorHeaderInset}
575 projectName={selectedThreadProject?.title ?? "Files"}
576 selectedPath={null}
577 onSelectFile={handleSelectInspectorFile}
578 />
579 ) : null;
580 const renderRouteInspector = () => props.renderInspector?.(inspectorHeaderInset);
581 const renderPreviewInspector = () =>
582 previewTarget && panes.auxiliaryPaneVisible ? (
583 <ThreadInspectorPreview
584 target={previewTarget}
585 renderThread={(screen) => <ThreadRouteScreen {...screen} />}
586 onClose={toggleAuxiliaryPane}
587 onOpen={(inspector) => {
588 if (
589 inspector.type === "thread" &&
590 inspector.environmentId === environmentId &&
591 inspector.threadId === threadId
592 ) {
593 toggleAuxiliaryPane();
594 return;
595 }
596 navigation.setParams({ inspector });
597 }}
598 />
599 ) : null;
600 const renderInspectorStack = () =>
601 inspectorMode === null ? null : (
602 <ThreadInspectorContentStack
603 renderPreview={renderPreviewInspector}
604 renderFiles={renderFilesInspector}
605 renderGit={renderGitInspector}
606 mode={inspectorMode}
607 resetKeys={[routeThreadIdentity, selectedThreadCwd]}
608 renderRoute={props.renderInspector ? renderRouteInspector : undefined}
609 />
610 );
611 const activeInspectorRenderer =
612 props.inspectorPresentation || inspectorMode === null ? undefined : renderInspectorStack;
613 useRegisterWorkspaceInspector(activeInspectorRenderer);
614
615 const handleOpenConnectionEditor = () => {
616 void navigation.navigate("Connections");
617 };
618 const handleStopThread = () => {
619 if (
620 !selectedThread ||
621 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
622 composer.interruptibleRunId === null
623 ) {
624 return;
625 }
626 return interruptThreadTurn({
627 environmentId: selectedThread.environmentId,
628 input: {
629 threadId: selectedThread.id,
630 runId: composer.interruptibleRunId,
631 },
632 });
633 };
634
635 const handleResumeQueue = async () => {
636 if (!selectedThread) return;
637 await resumeThreadQueue({
638 environmentId: selectedThread.environmentId,
639 input: { threadId: selectedThread.id },
640 });
641 };
642
643 const handleOpenTerminal = (nextTerminalId?: string | null) => {
644 terminalDebugLog("terminal-menu:open-existing", {
645 terminalId: nextTerminalId ?? null,
646 hasThread: Boolean(selectedThread),
647 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
648 });
649
650 if (
651 !selectedThread ||
652 !selectedThreadProject?.workspaceRoot ||
653 (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
654 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
655 ) {
656 return;
657 }
658
659 void navigation.navigate("ThreadTerminal", {
660 environmentId: String(selectedThread.environmentId),
661 threadId: String(selectedThread.id),
662 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
663 });
664 };
665
666 const handleOpenNewTerminal = () => {
667 terminalDebugLog("terminal-menu:open-new", {
668 hasThread: Boolean(selectedThread),
669 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
670 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
671 });
672
673 if (
674 !selectedThread ||
675 !selectedThreadProject?.workspaceRoot ||
676 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
677 ) {
678 return;
679 }
680
681 const nextId = nextOpenTerminalId({
682 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
683 ...(knownTerminalSessions === null ||
684 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
685 ? { uniqueSuffix: uuidv4() }
686 : {}),
687 });
688 void navigation.navigate("ThreadTerminal", {
689 environmentId: String(selectedThread.environmentId),
690 threadId: String(selectedThread.id),
691 terminalId: nextId,
692 });
693 };
694
695 const handleRunProjectScript = async (script: ProjectScript) => {
696 terminalDebugLog("project-script:press", {
697 scriptId: script.id,
698 command: script.command,
699 hasThread: Boolean(selectedThread),
700 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
701 });
702
703 if (
704 !selectedThread ||
705 !selectedThreadProject?.workspaceRoot ||
706 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
707 ) {
708 terminalDebugLog("project-script:abort", {
709 scriptId: script.id,
710 reason: "no-thread-workspace-or-terminal-access",
711 });
712 return;
713 }
714
715 const targetTerminalId = resolveProjectScriptTerminalId({
716 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
717 ...(knownTerminalSessions === null ||
718 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
719 ? { uniqueSuffix: uuidv4() }
720 : {}),
721 hasRunningTerminal: terminalMenuSessions.some(
722 (session) => session.status === "running" || session.status === "starting",
723 ),
724 });
725 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
726 threadShellWorktreePath: selectedThread.worktreePath ?? null,
727 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
728 });
729 const cwd = projectScriptCwd({
730 project: { cwd: selectedThreadProject.workspaceRoot },
731 worktreePath: preferredWorktreePath,
732 });
733 const env = projectScriptRuntimeEnv({
734 project: { cwd: selectedThreadProject.workspaceRoot },
735 worktreePath: preferredWorktreePath,
736 });
737 stagePendingTerminalLaunch({
738 target: {
739 environmentId: selectedThread.environmentId,
740 threadId: selectedThread.id,
741 terminalId: targetTerminalId,
742 },
743 launch: {
744 cwd,
745 worktreePath: preferredWorktreePath,
746 env,
747 initialInput: projectScriptTerminalInput(script.command),
748 },
749 });
750 terminalDebugLog("project-script:staged", {
751 scriptId: script.id,
752 terminalId: targetTerminalId,
753 cwd,
754 worktreePath: preferredWorktreePath,
755 });
756
757 void navigation.navigate("ThreadTerminal", {
758 environmentId: String(selectedThread.environmentId),
759 threadId: String(selectedThread.id),
760 terminalId: targetTerminalId,
761 });
762 };
763 const threadGitControlProps = {
764 environmentId: environmentIdRaw ?? "",
765 threadId: threadId ?? "",
766 auxiliaryPaneControl:
767 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
768 ? {
769 accessibilityLabel: "Toggle inspector",
770 onPress: handleToggleInspector,
771 }
772 : undefined,
773 onOpenFilesInspector:
774 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
775 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
776 onMergeBack:
777 mergeBackTargetThreadId !== null && mergeBackRun !== null
778 ? () => void handleMergeBack()
779 : undefined,
780 currentBranch: selectedThread?.branch ?? null,
781 gitStatus: gitStatus.data,
782 gitOperationLabel: gitState.gitOperationLabel,
783 canOpenTerminal:
784 Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
785 canOperateTerminal,
786 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
787 projectScripts: selectedThreadProject
788 ? resolveProjectScripts(
789 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
790 selectedThreadProject,
791 )
792 : [],
793 terminalSessions: terminalMenuSessions,
794 showDirectFileControl: layout.usesSplitView,
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 headerColor={headerColor}
958 usesNativeHeaderGlass={usesNativeHeaderGlass}
959 gitControls={threadGitControlProps}
960 hasThreadCwd={selectedThreadCwd !== null}
961 hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
962 fileInspectorSupported={fileInspector.supported}
963 inspectorMode={inspectorMode}
964 onToggleInspector={handleToggleInspector}
965 onOpenGitInspector={handleOpenGitInspector}
966 onOpenFilesInspector={handleOpenFilesInspector}
967 onReturnToThread={props.onReturnToThread}
968 />
969 )
970 }
971 canOperateThread={canOperateThread}
972 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
973 selectedThreadDetailRef={selectedThreadDetailRef}
974 contentPresentation={contentPresentation}
975 screenTone={connectionTone(routeConnectionState)}
976 connectionError={routeConnectionError}
977 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
978 feedbackSubmissions={composer.feedbackSubmissions}
979 onDismissFeedback={composer.dismissFeedback}
980 selectedThreadFeed={composer.selectedThreadFeed}
981 pendingHandoff={composer.pendingHandoff}
982 activityRun={composer.selectedThreadActivityRun}
983 activeWorkStartedAt={
984 creationState?.kind === "preparing" ||
985 (worktreeSetup !== null && setupTurnStartedAt === null)
986 ? null
987 : composer.activeWorkStartedAt
988 }
989 isCompacting={composer.isCompacting}
990 runlessWorkActive={composer.runlessWorkActive}
991 providerSubagentStatus={composer.providerSubagentStatus}
992 creationState={creationState}
993 setupWorkingStartedAt={
994 composer.activeWorkStartedAt !== null &&
995 worktreeSetupSnapshot !== null &&
996 composer.selectedThreadFeed.filter(
997 (entry) => entry.type === "message" && entry.message.role === "user",
998 ).length <= 1
999 ? composer.activeWorkStartedAt
1000 : null
1001 }
1002 worktreeSetup={
1003 worktreeSetup
1004 ? {
1005 snapshot: worktreeSetup,
1006 turnStartedAt: setupTurnStartedAt,
1007 working: composer.activeWorkStartedAt !== null,
1008 turnStarted: setupTurnStartedAt !== null,
1009 onCancel: handleCancelWorktreeSetup,
1010 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
1011 }
1012 : null
1013 }
1014 activePendingApproval={requests.activePendingApproval}
1015 activePendingApprovals={requests.activePendingApprovals}
1016 respondingApprovalId={requests.respondingApprovalId}
1017 activePendingUserInput={requests.activePendingUserInput}
1018 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1019 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1020 respondingUserInputId={requests.respondingUserInputId}
1021 connectionStateLabel={routeConnectionState}
1022 threadSyncStatus={selectedThreadDetailState.status}
1023 historyControls={historyControls}
1024 activeThreadBusy={composer.activeThreadBusy}
1025 canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null}
1026 queuedRunEdit={composer.queuedRunEdit}
1027 composerDraftKey={composer.composerDraftKey}
1028 followUpBehavior={composer.followUpBehavior}
1029 canSteerActiveTurn={composer.canSteerActiveTurn}
1030 isSavingQueuedEdit={composer.isSavingQueuedEdit}
1031 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
1032 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
1033 environmentId={selectedThread.environmentId}
1034 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1035 threadCwd={selectedThreadCwd}
1036 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1037 queuedMessages={
1038 selectedThreadCreation && selectedThreadCreation.outcome?.kind !== "delivered"
1039 ? [selectedThreadCreation.message, ...composer.selectedThreadQueuedMessages]
1040 : composer.selectedThreadQueuedMessages
1041 }
1042 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1043 layoutVariant={layout.variant}
1044 usesAutomaticContentInsets={usesNativeHeaderGlass}
1045 onOpenConnectionEditor={handleOpenConnectionEditor}
1046 onChangeDraftMessage={composer.onChangeDraftMessage}
1047 onPickDraftMedia={composer.onPickDraftMedia}
1048 onPickDraftFiles={composer.onPickDraftFiles}
1049 onNativePasteImages={composer.onNativePasteImages}
1050 onNativePasteText={composer.onNativePasteText}
1051 onRemoveDraftImage={composer.onRemoveDraftImage}
1052 serverConfig={serverConfig}
1053 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1054 onResumeQueue={composer.queueHeld ? handleResumeQueue : null}
1055 onSendMessage={composer.onSendMessage}
1056 onReconnectEnvironment={handleReconnectEnvironment}
1057 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1058 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
1059 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
1060 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1061 onRespondToApproval={requests.onRespondToApproval}
1062 onSelectUserInputOption={requests.onSelectUserInputOption}
1063 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1064 onSubmitUserInput={requests.onSubmitUserInput}
1065 onDismissUserInput={requests.onDismissUserInput}
1066 />
1067 </>
1068 </>
1069 );
1070
1071 return (
1072 <>
1073 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1074
1075 {renderThreadRouteBody()}
1076 </>
1077 );
1078}
1079
1080export function FullscreenThreadRouteScreen(
1081 props: StaticScreenProps<{
1082 readonly environmentId: string;
1083 readonly threadId: string;
1084 }>,
1085) {
1086 const navigation = useNavigation();
1087 return (
1088 <InspectorContentScope>
1089 <ThreadRouteScreen
1090 route={props.route}
1091 inspectorPresentation={{ onClose: () => navigation.goBack() }}
1092 />
1093 </InspectorContentScope>
1094 );
1095}