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

ThreadRouteScreen.tsx

1,049 lines40.2 KB

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