Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadRouteScreen.tsx

1,088 lines40.3 KB

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 {
9 StackActions,
10 useFocusEffect,
11 useNavigation,
12 type StaticScreenProps,
13} from "@react-navigation/native";
14import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
15import * as Option from "effect/Option";
16import {
17 AuthOrchestrationOperateScope,
18 AuthTerminalOperateScope,
19 AuthTerminalReadScope,
20 DEFAULT_SERVER_SETTINGS,
21 EnvironmentId,
22 ThreadId,
23 type ProjectScript,
24} from "@t3tools/contracts";
25import {
26 projectScriptCwd,
27 projectScriptRuntimeEnv,
28 resolveProjectScripts,
29} from "@t3tools/shared/projectScripts";
30import { Platform, ScrollView, View } from "react-native";
31import { useSafeAreaInsets } from "react-native-safe-area-context";
32import { useConnectionsReady } from "../../state/workspace";
33import { useEnvironmentShellReadiness } from "../../state/shell";
34import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
35import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
36import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
37import { useEnvironmentQuery } from "../../state/query";
38import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
39import { vcsEnvironment } from "../../state/vcs";
40import { EmptyState } from "../../components/ui/EmptyState";
41import { LoadingScreen } from "../../components/LoadingScreen";
42import { scopedThreadKey } from "../../lib/scopedEntities";
43import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
44import { connectionTone } from "../connection/connectionTone";
45import {
46 useRemoteConnections,
47 useRemoteConnectionStatus,
48 useRemoteEnvironmentRuntime,
49} from "../../state/use-remote-environment-registry";
50import { useKnownTerminalSessions } from "../../state/use-terminal-session";
51import { uuidv4 } from "../../lib/uuid";
52import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
53import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
54import { useThreadSelection } from "../../state/use-thread-selection";
55import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
56import {
57 buildTerminalMenuSessions,
58 nextOpenTerminalId,
59 resolveProjectScriptTerminalId,
60} from "../terminal/terminalMenu";
61import {
62 resolvePreferredThreadWorktreePath,
63 stagePendingTerminalLaunch,
64} from "../terminal/terminalLaunchContext";
65import { terminalDebugLog } from "../terminal/terminalDebugLog";
66import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
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 } 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 useWorkspaceListNavigation,
95} from "../workspace/useAndroidWorkspaceNavigation";
96​
97interface ThreadInspectorSelection {
98 readonly routeThreadIdentity: string | null;
99 readonly mode: ThreadInspectorMode;
101​
102function InspectorPaneRoleActivation() {
103 useAdaptiveWorkspacePaneRole("inspector");
104 return null;
106​
107function firstRouteParam(value: string | string[] | undefined): string | null {
108 const first = Array.isArray(value) ? value[0] : value;
109 return first === undefined || first.trim().length === 0 ? null : first;
111​
112function ThreadPane(props: { readonly children: ReactNode }) {
113 return (
114 <View className="flex-1 bg-screen android:overflow-hidden android:rounded-t-[28px] android:bg-thread-canvas">
115 {props.children}
116 </View>
117 );
119​
120function ThreadRouteFallbackLayout(props: { readonly children: ReactNode }) {
121 const returnToList = useWorkspaceListNavigation("threads");
122 const { layout } = useAdaptiveWorkspaceLayout();
123 const { themeVariables } = useAppearancePreferences();
124 if (Platform.OS !== "android") return props.children;
125​
126 return (
127 <>
128 <AppBar
129 title="Thread"
130 options={{ contentStyle: { backgroundColor: themeVariables["--color-header"] } }}
131 onBack={layout.usesSplitView ? undefined : returnToList}
132 hideBottomBorder
133 />
134 <ThreadPane>{props.children}</ThreadPane>
135 </>
136 );
138​
139function OpeningThreadLoadingScreen() {
140 return (
141 <ThreadRouteFallbackLayout>
142 <LoadingScreen
143 message="Opening thread…"
144 messagePlacement="above-spinner"
145 embedded={Platform.OS === "android"}
146 />
147 </ThreadRouteFallbackLayout>
148 );
150​
151type ThreadRouteScreenRouteProps = StaticScreenProps<{
152 readonly environmentId: string;
153 readonly threadId: string;
154 readonly prompt?: string | string[];
155}>;
156​
157interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
158 readonly onReturnToThread?: () => void;
159 readonly renderInspector?: (headerInset: number) => ReactNode;
161​
162function ThreadUnavailableScreen(props: {
163 readonly actionLabel: string;
164 readonly onAction: () => void;
165}) {
166 return (
167 <ThreadRouteFallbackLayout>
168 <ScrollView
169 contentInsetAdjustmentBehavior="automatic"
170 contentContainerStyle={{
171 flexGrow: 1,
172 justifyContent: "center",
173 paddingHorizontal: 24,
174 paddingVertical: 32,
175 }}
176 className="bg-screen flex-1 android:bg-transparent"
177 >
178 <EmptyState
179 title="Thread unavailable"
180 detail="This thread is not available in the current mobile snapshot."
181 actionLabel={props.actionLabel}
182 onAction={props.onAction}
183 />
184 </ScrollView>
185 </ThreadRouteFallbackLayout>
186 );
188​
189export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
190 useAndroidWorkspaceBack("threads");
191 const connectionsReady = useConnectionsReady();
192 const { connectionState } = useRemoteConnectionStatus();
193 const { selectedThread } = useThreadSelection();
194 const params = props.route.params;
195 const environmentIdRaw = firstRouteParam(params.environmentId);
196 const threadIdRaw = firstRouteParam(params.threadId);
197 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
198 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
199 const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
200 const { onReconnectEnvironment } = useRemoteConnections();
201 const navigation = useNavigation();
202 const routeConnectionState =
203 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
204 const routeThreadKey =
205 environmentId !== null && threadIdRaw !== null
206 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
207 : null;
208 const selectedThreadKey =
209 selectedThread === null
210 ? null
211 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
212 const selectedThreadDetailState = useSelectedThreadDetailState();
213 useThreadPromptLink(params, routeThreadKey);
214​
215 if (environmentId === null || threadIdRaw === null) {
216 return <OpeningThreadLoadingScreen />;
217 }
218​
219 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
220 return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
221 }
222​
223 const stillHydrating = threadRouteIsHydrating({
224 isLoadingConnections: !connectionsReady,
225 connectionState: routeConnectionState,
226 shellStatus: routeEnvironmentShellState.status,
227 shellHasError: routeEnvironmentShellState.hasError,
228 detailStatus: selectedThreadDetailState.status,
229 detailHasError: Option.isSome(selectedThreadDetailState.error),
230 });
231​
232 if (stillHydrating) {
233 return <OpeningThreadLoadingScreen />;
234 }
235​
236 return (
237 <ThreadUnavailableScreen
238 actionLabel={
239 routeEnvironmentRuntime === null ? "Manage environments" : "Reconnect environment"
240 }
241 onAction={() => {
242 if (routeEnvironmentRuntime !== null) {
243 onReconnectEnvironment(environmentId);
244 return;
245 }
246 navigation.navigate("SettingsSheet", {
247 screen: "SettingsContent",
248 params: { screen: "SettingsEnvironments" },
249 });
250 }}
251 />
252 );
254​
255function ThreadRouteContent(
256 props: ThreadRouteScreenProps & {
257 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
258 },
259) {
260 const { themeVariables } = useAppearancePreferences();
261 const headerColor = themeVariables["--color-header"];
262 const { fileInspector, layout, panes, showAuxiliaryPane, toggleAuxiliaryPane } =
263 useAdaptiveWorkspaceLayout();
264 const { connectionState } = useRemoteConnectionStatus();
265 const { onReconnectEnvironment } = useRemoteConnections();
266 const {
267 selectedThread,
268 selectedThreadCreation,
269 selectedThreadDetailRef,
270 selectedThreadProject,
271 selectedEnvironmentConnection,
272 } = useThreadSelection();
273 const canOperateThread = useEnvironmentScope(
274 selectedThread?.environmentId ?? null,
275 AuthOrchestrationOperateScope,
276 );
277 const canReadTerminal = useEnvironmentScope(
278 selectedThread?.environmentId ?? null,
279 AuthTerminalReadScope,
280 );
281 const canOperateTerminal = useEnvironmentScope(
282 selectedThread?.environmentId ?? null,
283 AuthTerminalOperateScope,
284 );
285 const selectedThreadDetailState = props.selectedThreadDetailState;
286 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
287 const { selectedThreadCwd } = useSelectedThreadWorktree();
288 const composer = useThreadComposerState();
289 const gitState = useSelectedThreadGitState();
290 const gitActions = useSelectedThreadGitActions();
291 const requests = useSelectedThreadRequests();
292 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
293 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
294 label: "load earlier thread history",
295 reportFailure: false,
296 });
297 const historyControls = useMemo(() => {
298 const history = selectedThreadDetailState.history;
299 if (!selectedThread) {
300 return undefined;
301 }
302 if (!history.hasMoreHistory && history.error === null) {
303 return undefined;
304 }
305 return {
306 hasMoreHistory: history.hasMoreHistory,
307 loading: history.loading,
308 error: history.error,
309 onLoadEarlier: () => {
310 void loadEarlierHistory({
311 environmentId: selectedThread.environmentId,
312 input: { threadId: selectedThread.id },
313 });
314 },
315 };
316 }, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]);
317 const navigation = useNavigation();
318 const openPullRequest = useOpenPullRequest();
319 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
320 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
321 const mergeBackRun =
322 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
323 const mergeBackBusyRef = useRef(false);
324 const handleMergeBack = useCallback(async () => {
325 if (
326 mergeBackBusyRef.current ||
327 !selectedThread ||
328 mergeBackTargetThreadId === null ||
329 mergeBackRun === null
330 ) {
331 return;
332 }
333 mergeBackBusyRef.current = true;
334 try {
335 const result = await mergeBack({
336 environmentId: selectedThread.environmentId,
337 input: {
338 sourceThreadId: selectedThread.id,
339 targetThreadId: mergeBackTargetThreadId,
340 runId: mergeBackRun.id,
341 creationSource: "mobile",
342 },
343 });
344 if (result._tag !== "Success") return;
345 navigation.navigate("Thread", {
346 environmentId: selectedThread.environmentId,
347 threadId: mergeBackTargetThreadId,
348 });
349 } finally {
350 mergeBackBusyRef.current = false;
351 }
352 }, [mergeBack, mergeBackRun, mergeBackTargetThreadId, navigation, selectedThread]);
353 const params = props.route.params;
354 const environmentIdRaw = firstRouteParam(params.environmentId);
355 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
356 const threadId = firstRouteParam(params.threadId);
357 const routeThreadIdentity =
358 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
359 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
360 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
361 );
362 const inspectorMode = (() => {
363 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
364 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
365 return null;
366 }
367 return inspectorSelection.mode;
368 }
369 return null;
370 })();
371 useEffect(() => {
372 if (
373 fileInspector.supported &&
374 selectedThreadCwd === null &&
375 inspectorMode === null &&
376 panes.auxiliaryPaneVisible
377 ) {
378 toggleAuxiliaryPane();
379 }
380 }, [
381 fileInspector.supported,
382 inspectorMode,
383 panes.auxiliaryPaneVisible,
384 selectedThreadCwd,
385 toggleAuxiliaryPane,
386 ]);
387​
388 useEffect(() => {
389 setInspectorSelection((current) => {
390 if (props.renderInspector === undefined) {
391 if (current === null || current.mode === "route") {
392 return null;
393 }
394 return { ...current, routeThreadIdentity };
395 }
396​
397 if (current === null || current.mode === "route") {
398 return { routeThreadIdentity, mode: "route" };
399 }
400​
401 return { ...current, routeThreadIdentity };
402 });
403 }, [props.renderInspector, routeThreadIdentity]);
404​
405 useFocusEffect(
406 useCallback(() => {
407 return () => {
408 if (props.renderInspector === undefined) {
409 setInspectorSelection(null);
410 }
411 };
412 }, [props.renderInspector]),
413 );
414 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
415 const routeConnectionState =
416 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
417 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
418 const selectedThreadWithDraftSettings = useMemo(
419 () =>
420 selectedThread
421 ? {
422 ...selectedThread,
423 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
424 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
425 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
426 }
427 : null,
428 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
429 );
430​
431 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
432 const headerSubtitle = [
433 selectedThreadProject?.title ?? null,
434 selectedEnvironmentConnection?.environmentLabel ?? null,
435 ]
436 .filter(Boolean)
437 .join(" · ");
438 const gitStatus = useEnvironmentQuery(
439 selectedThread !== null && selectedThreadCwd !== null
440 ? vcsEnvironment.status({
441 environmentId: selectedThread.environmentId,
442 input: { cwd: selectedThreadCwd },
443 })
444 : null,
445 );
446 const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
447 environmentId: selectedThread?.environmentId ?? null,
448 threadId: selectedThread?.id ?? null,
449 });
450 const terminalMenuSessions = useMemo(
451 () =>
452 buildTerminalMenuSessions({
453 knownSessions: knownTerminalSessions ?? [],
454 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
455 }),
456 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
457 );
458 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
459 const handleReconnectEnvironment = useCallback(() => {
460 if (!environmentId) {
461 return;
462 }
463 onReconnectEnvironment(environmentId);
464 }, [environmentId, onReconnectEnvironment]);
465​
466 const gitActionProgressTarget = useMemo(
467 () => ({
468 environmentId: selectedThread?.environmentId ?? null,
469 cwd: selectedThreadCwd,
470 }),
471 [selectedThread?.environmentId, selectedThreadCwd],
472 );
473 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
474​
475 const handleOpenGitInspector = useCallback(() => {
476 if (!fileInspector.supported) {
477 if (selectedThread === null) {
478 return;
479 }
480 navigation.navigate("GitOverview", {
481 environmentId: String(selectedThread.environmentId),
482 threadId: String(selectedThread.id),
483 });
484 return;
485 }
486 setInspectorSelection({ routeThreadIdentity, mode: "git" });
487 showAuxiliaryPane("inspector");
488 }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
489 const handleOpenFilesInspector = useCallback(() => {
490 if (selectedThread === null || selectedThreadCwd === null) {
491 return;
492 }
493 if (!fileInspector.supported) {
494 navigation.navigate("ThreadFiles", {
495 environmentId: String(selectedThread.environmentId),
496 threadId: String(selectedThread.id),
497 });
498 return;
499 }
500 setInspectorSelection({
501 routeThreadIdentity,
502 mode: props.renderInspector === undefined ? "files" : "route",
503 });
504 showAuxiliaryPane("inspector");
505 }, [
506 fileInspector.supported,
507 navigation,
508 props.renderInspector,
509 routeThreadIdentity,
510 selectedThread,
511 selectedThreadCwd,
512 showAuxiliaryPane,
513 ]);
514 const inspectorToggleActionRef = useRef({
515 inspectorMode,
516 openFilesInspector: handleOpenFilesInspector,
517 toggleAuxiliaryPane,
518 });
519 inspectorToggleActionRef.current = {
520 inspectorMode,
521 openFilesInspector: handleOpenFilesInspector,
522 toggleAuxiliaryPane,
523 };
524 const handleToggleInspector = useCallback(() => {
525 const action = inspectorToggleActionRef.current;
526 if (action.inspectorMode === null) {
527 action.openFilesInspector();
528 return;
529 }
530 action.toggleAuxiliaryPane();
531 }, []);
532 const handleSelectInspectorFile = useCallback(
533 (path: string) => {
534 if (selectedThread === null) {
535 return;
536 }
537 const params = {
538 environmentId: String(selectedThread.environmentId),
539 threadId: String(selectedThread.id),
540 path: path.split("/").filter((segment) => segment.length > 0),
541 };
542 if (fileInspector.supported) {
543 navigation.navigate("ThreadFile", params);
544 return;
545 }
546 navigation.navigate("ThreadFile", params);
547 },
548 [fileInspector.supported, navigation, selectedThread],
549 );
550 const safeAreaInsets = useSafeAreaInsets();
551 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
552 const GitInspector = useCallback(
553 () => (
554 <GitOverviewSheet
555 headerInset={inspectorHeaderInset}
556 presentation="inspector"
557 route={{ params: props.route.params }}
558 />
559 ),
560 [inspectorHeaderInset, props.route.params],
561 );
562 const FilesInspector = useCallback(
563 () =>
564 selectedThread !== null && selectedThreadCwd !== null ? (
565 <ThreadFileNavigatorPane
566 cwd={selectedThreadCwd}
567 environmentId={selectedThread.environmentId}
568 headerInset={inspectorHeaderInset}
569 projectName={selectedThreadProject?.title ?? "Files"}
570 selectedPath={null}
571 onSelectFile={handleSelectInspectorFile}
572 />
573 ) : null,
574 [
575 handleSelectInspectorFile,
576 inspectorHeaderInset,
577 selectedThread,
578 selectedThreadCwd,
579 selectedThreadProject?.title,
580 ],
581 );
582 const RouteInspector = useCallback(
583 () => props.renderInspector?.(inspectorHeaderInset),
584 [inspectorHeaderInset, props.renderInspector],
585 );
586 const renderInspectorStack = useCallback(
587 () =>
588 inspectorMode === null ? null : (
589 <ThreadInspectorContentStack
590 renderFiles={FilesInspector}
591 renderGit={GitInspector}
592 mode={inspectorMode}
593 resetKeys={[routeThreadIdentity, selectedThreadCwd]}
594 renderRoute={props.renderInspector ? RouteInspector : undefined}
595 />
596 ),
597 [
598 FilesInspector,
599 GitInspector,
600 RouteInspector,
601 inspectorMode,
602 props.renderInspector,
603 routeThreadIdentity,
604 selectedThreadCwd,
605 ],
606 );
607 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
608 useRegisterWorkspaceInspector(activeInspectorRenderer);
609​
610 const handleOpenConnectionEditor = useCallback(() => {
611 void navigation.navigate("Connections");
612 }, [navigation]);
613 const handleStopThread = useCallback(() => {
614 if (
615 !selectedThread ||
616 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
617 composer.interruptibleRunId === null
618 ) {
619 return;
620 }
621 return interruptThreadTurn({
622 environmentId: selectedThread.environmentId,
623 input: {
624 threadId: selectedThread.id,
625 runId: composer.interruptibleRunId,
626 },
627 });
628 }, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
629​
630 const handleOpenTerminal = useCallback(
631 (nextTerminalId?: string | null) => {
632 terminalDebugLog("terminal-menu:open-existing", {
633 terminalId: nextTerminalId ?? null,
634 hasThread: Boolean(selectedThread),
635 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
636 });
637​
638 if (
639 !selectedThread ||
640 !selectedThreadProject?.workspaceRoot ||
641 (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
642 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
643 ) {
644 return;
645 }
646​
647 void navigation.navigate("ThreadTerminal", {
648 environmentId: String(selectedThread.environmentId),
649 threadId: String(selectedThread.id),
650 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
651 });
652 },
653 [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
654 );
655​
656 const handleOpenNewTerminal = useCallback(() => {
657 terminalDebugLog("terminal-menu:open-new", {
658 hasThread: Boolean(selectedThread),
659 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
660 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
661 });
662​
663 if (
664 !selectedThread ||
665 !selectedThreadProject?.workspaceRoot ||
666 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
667 ) {
668 return;
669 }
670​
671 const nextId = nextOpenTerminalId({
672 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
673 ...(knownTerminalSessions === null ||
674 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
675 ? { uniqueSuffix: uuidv4() }
676 : {}),
677 });
678 void navigation.navigate("ThreadTerminal", {
679 environmentId: String(selectedThread.environmentId),
680 threadId: String(selectedThread.id),
681 terminalId: nextId,
682 });
683 }, [
684 knownTerminalSessions,
685 navigation,
686 selectedThread,
687 selectedThreadProject?.workspaceRoot,
688 terminalMenuSessions,
689 ]);
690​
691 const handleRunProjectScript = useCallback(
692 async (script: ProjectScript) => {
693 terminalDebugLog("project-script:press", {
694 scriptId: script.id,
695 command: script.command,
696 hasThread: Boolean(selectedThread),
697 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
698 });
699​
700 if (
701 !selectedThread ||
702 !selectedThreadProject?.workspaceRoot ||
703 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
704 ) {
705 terminalDebugLog("project-script:abort", {
706 scriptId: script.id,
707 reason: "no-thread-workspace-or-terminal-access",
708 });
709 return;
710 }
711​
712 const targetTerminalId = resolveProjectScriptTerminalId({
713 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
714 ...(knownTerminalSessions === null ||
715 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
716 ? { uniqueSuffix: uuidv4() }
717 : {}),
718 hasRunningTerminal: terminalMenuSessions.some(
719 (session) => session.status === "running" || session.status === "starting",
720 ),
721 });
722 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
723 threadShellWorktreePath: selectedThread.worktreePath ?? null,
724 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
725 });
726 const cwd = projectScriptCwd({
727 project: { cwd: selectedThreadProject.workspaceRoot },
728 worktreePath: preferredWorktreePath,
729 });
730 const env = projectScriptRuntimeEnv({
731 project: { cwd: selectedThreadProject.workspaceRoot },
732 worktreePath: preferredWorktreePath,
733 });
734 stagePendingTerminalLaunch({
735 target: {
736 environmentId: selectedThread.environmentId,
737 threadId: selectedThread.id,
738 terminalId: targetTerminalId,
739 },
740 launch: {
741 cwd,
742 worktreePath: preferredWorktreePath,
743 env,
744 initialInput: `${script.command}\r`,
745 },
746 });
747 terminalDebugLog("project-script:staged", {
748 scriptId: script.id,
749 terminalId: targetTerminalId,
750 cwd,
751 worktreePath: preferredWorktreePath,
752 });
753​
754 void navigation.navigate("ThreadTerminal", {
755 environmentId: String(selectedThread.environmentId),
756 threadId: String(selectedThread.id),
757 terminalId: targetTerminalId,
758 });
759 },
760 [
761 navigation,
762 selectedThread,
763 selectedThreadDetailWorktreePath,
764 selectedThreadProject,
765 terminalMenuSessions,
766 knownTerminalSessions,
767 ],
768 );
769 const threadGitControlProps = {
770 environmentId: environmentIdRaw ?? "",
771 threadId: threadId ?? "",
772 auxiliaryPaneControl:
773 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
774 ? {
775 accessibilityLabel: "Toggle inspector",
776 onPress: handleToggleInspector,
777 }
778 : undefined,
779 onOpenFilesInspector:
780 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
781 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
782 onMergeBack:
783 mergeBackTargetThreadId !== null && mergeBackRun !== null
784 ? () => void handleMergeBack()
785 : undefined,
786 currentBranch: selectedThread?.branch ?? null,
787 gitStatus: gitStatus.data,
788 gitOperationLabel: gitState.gitOperationLabel,
789 canOpenTerminal:
790 Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
791 canOperateTerminal,
792 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
793 projectScripts: selectedThreadProject
794 ? resolveProjectScripts(
795 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
796 selectedThreadProject,
797 )
798 : [],
799 terminalSessions: terminalMenuSessions,
800 showDirectFileControl: layout.usesSplitView,
801 onOpenTerminal: handleOpenTerminal,
802 onOpenNewTerminal: handleOpenNewTerminal,
803 onRunProjectScript: handleRunProjectScript,
804 onPull: gitActions.onPullSelectedThreadBranch,
805 onRunAction: gitActions.onRunSelectedThreadGitAction,
806 };
807 const handleEditFailedCreation = useCallback(async () => {
808 const creation = selectedThreadCreation?.message;
809 if (!creation?.creation || routeThreadIdentity === null) {
810 return;
811 }
812 // The drain restored the prompt and attachments into the recovery draft
813 // the rejected creation owns. Open that draft by id: without it the sheet
814 // mints a fresh empty one and the restored content is unreachable.
815 try {
816 await recoverFailedThreadDraft(creation);
817 } catch (error) {
818 Dialog.alert(
819 "Could not restore draft",
820 error instanceof Error ? error.message : String(error),
821 );
822 return;
823 }
824 clearPendingThreadCreationOutcome(routeThreadIdentity);
825 navigation.dispatch(
826 StackActions.replace("NewTaskSheet", {
827 screen: "NewTaskDraft",
828 params: {
829 draftId: restoredNewTaskDraftKey(creation.messageId),
830 environmentId: String(creation.environmentId),
831 projectId: String(creation.creation.projectId),
832 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
833 },
834 }),
835 );
836 }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
837 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
838 const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({
839 environmentId: selectedThread?.environmentId ?? null,
840 threadId: selectedThread?.id ?? null,
841 preparing:
842 composer.selectedThreadActivityRun?.status === "preparing" ||
843 selectedThread?.runtime?.status === "preparing" ||
844 selectedThread?.worktreePath != null ||
845 (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
846 selectedThreadCreation.outcome == null),
847 turnStarted: setupTurnStartedAt !== null,
848 followUpSent:
849 composer.selectedThreadFeed.filter(
850 (entry) => entry.type === "message" && entry.message.role === "user",
851 ).length +
852 composer.selectedThreadQueueCount >
853 1,
854 });
855 const awaitingBootstrapTurn =
856 worktreeSetup !== null
857 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
858 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
859 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
860 const handleCancelWorktreeSetup = useCallback(() => {
861 if (!selectedThread) return;
862 void cancelWorktreeSetup({
863 environmentId: selectedThread.environmentId,
864 input: { threadId: selectedThread.id },
865 });
866 }, [cancelWorktreeSetup, selectedThread]);
867 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
868 const localResendBusy = useRef(false);
869 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
870 const handleWorkLocally = useCallback(async () => {
871 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
872 return;
873 localResendBusy.current = true;
874 try {
875 const result = await cancelWorktreeSetup({
876 environmentId: selectedThread.environmentId,
877 input: { threadId: selectedThread.id },
878 });
879 if (result._tag !== "Success" || !result.value.cancelled) return;
880 // V2 accepts the launch before setup runs, so cancellation never rejects
881 // the original outbox delivery. Reuse the server-owned prompt and uploads.
882 const metadata = makeTurnCommandMetadata();
883 const launched = await startLocalThread({
884 environmentId: selectedThread.environmentId,
885 input: buildProjectThreadStartTurnInput({
886 ...metadata,
887 projectId: selectedThread.projectId,
888 projectCwd: selectedThreadProject.workspaceRoot,
889 text: setupMessage.text,
890 ...(setupMessage.context ? { context: setupMessage.context } : {}),
891 uploadedAttachments: setupMessage.attachments,
892 modelSelection: selectedThread.modelSelection,
893 runtimeMode: selectedThread.runtimeMode,
894 interactionMode: selectedThread.interactionMode,
895 workspaceMode: "local",
896 branch: null,
897 worktreePath: null,
898 startFromOrigin: false,
899 worktreeBranchName: "",
900 }),
901 });
902 if (launched._tag !== "Success") return;
903 navigation.dispatch(
904 StackActions.replace("Thread", {
905 environmentId: String(selectedThread.environmentId),
906 threadId: metadata.threadId,
907 }),
908 );
909 } finally {
910 localResendBusy.current = false;
911 }
912 }, [
913 cancelWorktreeSetup,
914 navigation,
915 selectedThread,
916 selectedThreadProject,
917 setupMessage,
918 startLocalThread,
919 ]);
920 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
921 if (selectedThreadCreation === null) {
922 return awaitingBootstrapTurn
923 ? { kind: "preparing", preparingWorktree: true, serverOwned: true }
924 : null;
925 }
926 if (selectedThreadCreation.outcome?.kind === "failed") {
927 return {
928 kind: "failed",
929 reason: selectedThreadCreation.outcome.reason,
930 onEditTask: handleEditFailedCreation,
931 };
932 }
933 return {
934 kind: "preparing",
935 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
936 serverOwned: false,
937 };
938 })();
939 if (!environmentId || !threadId) {
940 return <OpeningThreadLoadingScreen />;
941 }
942​
943 if (!selectedThread) {
944 return <OpeningThreadLoadingScreen />;
945 }
946​
947 // A queued creation renders as ready content: its prompt is the whole
948 // conversation until the server creates the thread. The subscription's
949 // not-found error for that window is expected, not a load failure.
950 const contentPresentation =
951 creationState !== null
952 ? { kind: "ready" as const }
953 : projectThreadContentPresentation({
954 hasDetail: selectedThreadDetail !== null,
955 detailError: Option.getOrNull(selectedThreadDetailState.error),
956 detailDeleted: selectedThreadDetailState.status === "deleted",
957 connectionState: routeConnectionState,
958 });
959 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
960 const renderThreadRouteBody = () => (
961 <>
962 <GitActionProgressOverlay
963 progress={gitActionProgress}
964 onDismiss={dismissGitActionResult}
965 onOpenPullRequest={openPullRequest}
966 />
967​
968 <ThreadPane>
969 <ThreadDetailScreen
970 canOperateThread={canOperateThread}
971 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
972 selectedThreadDetailRef={selectedThreadDetailRef}
973 contentPresentation={contentPresentation}
974 screenTone={connectionTone(routeConnectionState)}
975 connectionError={routeConnectionError}
976 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
977 feedbackSubmissions={composer.feedbackSubmissions}
978 onDismissFeedback={composer.dismissFeedback}
979 selectedThreadFeed={composer.selectedThreadFeed}
980 pendingHandoff={composer.pendingHandoff}
981 activityRun={composer.selectedThreadActivityRun}
982 activeWorkStartedAt={
983 creationState?.kind === "preparing" ||
984 (worktreeSetup !== null && setupTurnStartedAt === null)
985 ? null
986 : composer.activeWorkStartedAt
987 }
988 isCompacting={composer.isCompacting}
989 runlessWorkActive={composer.runlessWorkActive}
990 providerSubagentStatus={composer.providerSubagentStatus}
991 creationState={creationState}
992 setupWorkingStartedAt={
993 composer.activeWorkStartedAt !== null &&
994 worktreeSetupSnapshot !== null &&
995 composer.selectedThreadFeed.filter(
996 (entry) => entry.type === "message" && entry.message.role === "user",
997 ).length <= 1
998 ? composer.activeWorkStartedAt
999 : null
1001 worktreeSetup={
1002 worktreeSetup
1003 ? {
1004 snapshot: worktreeSetup,
1005 turnStartedAt: setupTurnStartedAt,
1006 working: composer.activeWorkStartedAt !== null,
1007 turnStarted: setupTurnStartedAt !== null,
1008 onCancel: handleCancelWorktreeSetup,
1009 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
1011 : null
1013 activePendingApproval={requests.activePendingApproval}
1014 respondingApprovalId={requests.respondingApprovalId}
1015 activePendingUserInput={requests.activePendingUserInput}
1016 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1017 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1018 respondingUserInputId={requests.respondingUserInputId}
1019 draftMessage={composer.draftMessage}
1020 draftAttachments={composer.draftAttachments}
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={composer.selectedThreadQueuedMessages}
1038 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1039 layoutVariant={layout.variant}
1040 usesAutomaticContentInsets={usesNativeHeaderGlass}
1041 onOpenConnectionEditor={handleOpenConnectionEditor}
1042 onChangeDraftMessage={composer.onChangeDraftMessage}
1043 onPickDraftMedia={composer.onPickDraftMedia}
1044 onPickDraftFiles={composer.onPickDraftFiles}
1045 onNativePasteImages={composer.onNativePasteImages}
1046 onNativePasteText={composer.onNativePasteText}
1047 onRemoveDraftImage={composer.onRemoveDraftImage}
1048 serverConfig={serverConfig}
1049 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1050 onSendMessage={composer.onSendMessage}
1051 onReconnectEnvironment={handleReconnectEnvironment}
1052 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1053 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
1054 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
1055 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1056 onRespondToApproval={requests.onRespondToApproval}
1057 onSelectUserInputOption={requests.onSelectUserInputOption}
1058 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1059 onSubmitUserInput={requests.onSubmitUserInput}
1060 onDismissUserInput={requests.onDismissUserInput}
1061 />
1062 </ThreadPane>
1063 </>
1064 );
1065​
1066 return (
1067 <>
1068 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1069 <ThreadHeader
1070 title={selectedThread.title}
1071 subtitle={headerSubtitle}
1072 headerColor={headerColor}
1073 usesNativeHeaderGlass={usesNativeHeaderGlass}
1074 gitControls={threadGitControlProps}
1075 hasThreadCwd={selectedThreadCwd !== null}
1076 hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
1077 fileInspectorSupported={fileInspector.supported}
1078 inspectorMode={inspectorMode}
1079 onToggleInspector={handleToggleInspector}
1080 onOpenGitInspector={handleOpenGitInspector}
1081 onOpenFilesInspector={handleOpenFilesInspector}
1082 onReturnToThread={props.onReturnToThread}
1083 />
1084​
1085 {renderThreadRouteBody()}
1086 </>
1087 );