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

ThreadRouteScreen.tsx

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