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

ThreadRouteScreen.tsx

1,076 lines40.2 KB

1import { NativeStackScreenOptions } from "../../native/StackHeader";
2import {
3 StackActions,
4 useFocusEffect,
5 useNavigation,
6 type StaticScreenProps,
7} from "@react-navigation/native";
8import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
9import * as Option from "effect/Option";
10import {
11 DEFAULT_SERVER_SETTINGS,
12 EnvironmentId,
13 ThreadId,
14 type ProjectScript,
15} from "@t3tools/contracts";
16import {
17 projectScriptCwd,
18 projectScriptRuntimeEnv,
19 resolveProjectScripts,
20} from "@t3tools/shared/projectScripts";
21import { Alert, Platform, ScrollView, View } from "react-native";
22import { useSafeAreaInsets } from "react-native-safe-area-context";
23import { useConnectionsReady } from "../../state/workspace";
24import { useEnvironmentShellReadiness } from "../../state/shell";
25import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
26import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
27import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
28import { useEnvironmentQuery } from "../../state/query";
29import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
30import { vcsEnvironment } from "../../state/vcs";
31​
32import { EmptyState } from "../../components/EmptyState";
33import {
34 AndroidScreenHeader,
35 type AndroidHeaderAction,
36} from "../../components/AndroidScreenHeader";
37import { LoadingScreen } from "../../components/LoadingScreen";
38import { scopedThreadKey } from "../../lib/scopedEntities";
39import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
40import { connectionTone } from "../connection/connectionTone";
41​
42import {
43 useRemoteConnections,
44 useRemoteConnectionStatus,
45 useRemoteEnvironmentRuntime,
46} from "../../state/use-remote-environment-registry";
47import { useKnownTerminalSessions } from "../../state/use-terminal-session";
48import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
49import { useThreadSelection } from "../../state/use-thread-selection";
50import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
51import {
52 buildTerminalMenuSessions,
53 nextOpenTerminalId,
54 resolveProjectScriptTerminalId,
55} from "../terminal/terminalMenu";
56import {
57 resolvePreferredThreadWorktreePath,
58 stagePendingTerminalLaunch,
59} from "../terminal/terminalLaunchContext";
60import { terminalDebugLog } from "../terminal/terminalDebugLog";
61import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
62import {
63 ThreadGitControls,
64 useThreadGitCenterHeaderItems,
65 useThreadGitRightHeaderItems,
66} from "./ThreadGitControls";
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 { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
85import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
86import {
87 ThreadInspectorContentStack,
88 type ThreadInspectorMode,
89} from "./thread-inspector-content-stack";
90import { threadRouteIsHydrating } from "./thread-route-hydration";
91​
92interface ThreadInspectorSelection {
93 readonly routeThreadIdentity: string | null;
94 readonly mode: ThreadInspectorMode;
96​
97type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;
98​
99function InspectorPaneRoleActivation() {
100 useAdaptiveWorkspacePaneRole("inspector");
101 return null;
103​
104function firstRouteParam(value: string | string[] | undefined): string | null {
105 if (Array.isArray(value)) {
106 return value[0] ?? null;
107 }
108​
109 return value ?? null;
111​
112function OpeningThreadLoadingScreen() {
113 return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
115​
116type ThreadRouteScreenRouteProps = StaticScreenProps<{
117 readonly environmentId: string;
118 readonly threadId: string;
119}>;
120​
121interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
122 readonly onReturnToThread?: () => void;
123 readonly renderInspector?: (headerInset: number) => ReactNode;
125​
126/** Shows recovery only after the target route has reached a terminal unavailable state. */
127function ThreadUnavailableScreen(props: {
128 readonly actionLabel: string;
129 readonly onAction: () => void;
130}) {
131 return (
132 <ScrollView
133 contentInsetAdjustmentBehavior="automatic"
134 contentContainerStyle={{
135 flexGrow: 1,
136 justifyContent: "center",
137 paddingHorizontal: 24,
138 paddingVertical: 32,
139 }}
140 className="bg-screen flex-1"
141 >
142 <EmptyState
143 title="Thread unavailable"
144 detail="This thread is not available in the current mobile snapshot."
145 actionLabel={props.actionLabel}
146 onAction={props.onAction}
147 />
148 </ScrollView>
149 );
151​
152export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
153 const connectionsReady = useConnectionsReady();
154 const { connectionState } = useRemoteConnectionStatus();
155 const { selectedThread } = useThreadSelection();
156 const params = props.route.params;
157 const environmentIdRaw = firstRouteParam(params.environmentId);
158 const threadIdRaw = firstRouteParam(params.threadId);
159 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
160 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
161 const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
162 const { onReconnectEnvironment } = useRemoteConnections();
163 const navigation = useNavigation();
164 const routeConnectionState =
165 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
166 const routeThreadKey =
167 environmentId !== null && threadIdRaw !== null
168 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
169 : null;
170 const selectedThreadKey =
171 selectedThread === null
172 ? null
173 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
174 const selectedThreadDetailState = useSelectedThreadDetailState();
175​
176 if (environmentId === null || threadIdRaw === null) {
177 return <OpeningThreadLoadingScreen />;
178 }
179​
180 // Render the full thread chrome (header, feed, composer) as soon as the
181 // thread SHELL is known — no blocking on message detail. The feed shows a
182 // loading placeholder while messages fetch, the floating pill above the
183 // composer reports loading/syncing, and the composer's connection pill
184 // reports connecting/reconnecting status.
185 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
186 return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
187 }
188​
189 const stillHydrating = threadRouteIsHydrating({
190 isLoadingConnections: !connectionsReady,
191 connectionState: routeConnectionState,
192 shellStatus: routeEnvironmentShellState.status,
193 shellHasError: routeEnvironmentShellState.hasError,
194 detailStatus: selectedThreadDetailState.status,
195 detailHasError: Option.isSome(selectedThreadDetailState.error),
196 });
197​
198 if (stillHydrating) {
199 return <OpeningThreadLoadingScreen />;
200 }
201​
202 return (
203 <ThreadUnavailableScreen
204 actionLabel={
205 routeEnvironmentRuntime === null ? "Manage environments" : "Reconnect environment"
206 }
207 onAction={() => {
208 if (routeEnvironmentRuntime !== null) {
209 onReconnectEnvironment(environmentId);
210 return;
211 }
212 navigation.navigate("SettingsSheet", {
213 screen: "SettingsContent",
214 params: { screen: "SettingsEnvironments" },
215 });
216 }}
217 />
218 );
220​
221function ThreadRouteContent(
222 props: ThreadRouteScreenProps & {
223 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
224 },
225) {
226 const { materialYouStyleLayoutActive, themeVariables } = useAppearancePreferences();
227 const headerColor = themeVariables["--color-header"];
228 const {
229 fileInspector,
230 layout,
231 panes,
232 showAuxiliaryPane,
233 toggleAuxiliaryPane,
234 togglePrimarySidebar,
235 } = useAdaptiveWorkspaceLayout();
236 const { connectionState } = useRemoteConnectionStatus();
237 const { onReconnectEnvironment } = useRemoteConnections();
238 const {
239 selectedThread,
240 selectedThreadCreation,
241 selectedThreadProject,
242 selectedEnvironmentConnection,
243 } = useThreadSelection();
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 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 Files={FilesInspector}
558 Git={GitInspector}
559 mode={inspectorMode}
560 Route={props.renderInspector ? RouteInspector : undefined}
561 />
562 ),
563 [FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector],
564 );
565 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
566 // Hand the inspector to the workspace so it renders beside the navigator,
567 // outside this screen's native header — the terminal/git/files toolbar
568 // stays anchored to the chat pane instead of floating above the inspector.
569 useRegisterWorkspaceInspector(activeInspectorRenderer);
570​
571 const handleOpenConnectionEditor = useCallback(() => {
572 void navigation.navigate("Connections");
573 }, [navigation]);
574 const handleStopThread = useCallback(() => {
575 if (!selectedThread || composer.interruptibleRunId === null) {
576 return;
577 }
578 return interruptThreadTurn({
579 environmentId: selectedThread.environmentId,
580 input: {
581 threadId: selectedThread.id,
582 runId: composer.interruptibleRunId,
583 },
584 });
585 }, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
586​
587 const handleOpenTerminal = useCallback(
588 (nextTerminalId?: string | null) => {
589 terminalDebugLog("terminal-menu:open-existing", {
590 terminalId: nextTerminalId ?? null,
591 hasThread: Boolean(selectedThread),
592 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
593 });
594​
595 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
596 return;
597 }
598​
599 void navigation.navigate("ThreadTerminal", {
600 environmentId: String(selectedThread.environmentId),
601 threadId: String(selectedThread.id),
602 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
603 });
604 },
605 [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
606 );
607​
608 const handleOpenNewTerminal = useCallback(() => {
609 terminalDebugLog("terminal-menu:open-new", {
610 hasThread: Boolean(selectedThread),
611 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
612 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
613 });
614​
615 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
616 return;
617 }
618​
619 const nextId = nextOpenTerminalId({
620 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
621 });
622 void navigation.navigate("ThreadTerminal", {
623 environmentId: String(selectedThread.environmentId),
624 threadId: String(selectedThread.id),
625 terminalId: nextId,
626 });
627 }, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
628​
629 const handleRunProjectScript = useCallback(
630 async (script: ProjectScript) => {
631 terminalDebugLog("project-script:press", {
632 scriptId: script.id,
633 command: script.command,
634 hasThread: Boolean(selectedThread),
635 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
636 });
637​
638 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
639 terminalDebugLog("project-script:abort", {
640 scriptId: script.id,
641 reason: "no-thread-or-workspace",
642 });
643 return;
644 }
645​
646 const targetTerminalId = resolveProjectScriptTerminalId({
647 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
648 hasRunningTerminal: terminalMenuSessions.some(
649 (session) => session.status === "running" || session.status === "starting",
650 ),
651 });
652 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
653 threadShellWorktreePath: selectedThread.worktreePath ?? null,
654 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
655 });
656 const cwd = projectScriptCwd({
657 project: { cwd: selectedThreadProject.workspaceRoot },
658 worktreePath: preferredWorktreePath,
659 });
660 const env = projectScriptRuntimeEnv({
661 project: { cwd: selectedThreadProject.workspaceRoot },
662 worktreePath: preferredWorktreePath,
663 });
664 stagePendingTerminalLaunch({
665 target: {
666 environmentId: selectedThread.environmentId,
667 threadId: selectedThread.id,
668 terminalId: targetTerminalId,
669 },
670 launch: {
671 cwd,
672 worktreePath: preferredWorktreePath,
673 env,
674 initialInput: `${script.command}\r`,
675 },
676 });
677 terminalDebugLog("project-script:staged", {
678 scriptId: script.id,
679 terminalId: targetTerminalId,
680 cwd,
681 worktreePath: preferredWorktreePath,
682 });
683​
684 void navigation.navigate("ThreadTerminal", {
685 environmentId: String(selectedThread.environmentId),
686 threadId: String(selectedThread.id),
687 terminalId: targetTerminalId,
688 });
689 },
690 [
691 navigation,
692 selectedThread,
693 selectedThreadDetailWorktreePath,
694 selectedThreadProject,
695 terminalMenuSessions,
696 ],
697 );
698 const threadGitControlProps = {
699 environmentId: environmentIdRaw ?? "",
700 threadId: threadId ?? "",
701 auxiliaryPaneControl:
702 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
703 ? {
704 accessibilityLabel: "Toggle inspector",
705 onPress: handleToggleInspector,
706 }
707 : undefined,
708 onOpenFilesInspector:
709 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
710 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
711 onMergeBack:
712 mergeBackTargetThreadId !== null && mergeBackRun !== null
713 ? () => void handleMergeBack()
714 : undefined,
715 currentBranch: selectedThread?.branch ?? null,
716 gitStatus: gitStatus.data,
717 gitOperationLabel: gitState.gitOperationLabel,
718 canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
719 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
720 projectScripts: selectedThreadProject
721 ? resolveProjectScripts(
722 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
723 selectedThreadProject,
724 )
725 : [],
726 terminalSessions: terminalMenuSessions,
727 showDirectFileControl: layout.usesSplitView,
728 onOpenTerminal: handleOpenTerminal,
729 onOpenNewTerminal: handleOpenNewTerminal,
730 onRunProjectScript: handleRunProjectScript,
731 onPull: gitActions.onPullSelectedThreadBranch,
732 onRunAction: gitActions.onRunSelectedThreadGitAction,
733 };
734 const threadCenterHeaderItems = useThreadGitCenterHeaderItems(threadGitControlProps);
735 const compactRightHeaderItems = useThreadGitRightHeaderItems(threadGitControlProps);
736 const splitLeftHeaderItems = useMemo<NativeHeaderItems>(
737 () => [
738 {
739 // Match Mail's split-view detail toolbar: the first detail action sits
740 // inside the content pane, not flush against the sidebar divider.
741 spacing: 18,
742 type: "spacing" as const,
743 },
744 ...(props.onReturnToThread
745 ? [
746 withNativeGlassHeaderItem({
747 accessibilityLabel: "Return to chat",
748 icon: { name: "chevron.left", type: "sfSymbol" as const },
749 identifier: "thread-left-return",
750 onPress: props.onReturnToThread,
751 type: "button" as const,
752 }),
753 ]
754 : []),
755 withNativeGlassHeaderItem({
756 accessibilityLabel: panes.primarySidebarVisible
757 ? "Maximize content"
758 : "Show thread sidebar",
759 icon: {
760 name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",
761 type: "sfSymbol" as const,
762 },
763 identifier: "thread-left-sidebar",
764 onPress: togglePrimarySidebar,
765 type: "button" as const,
766 }),
767 withNativeGlassHeaderItem({
768 accessibilityLabel: "New task",
769 icon: { name: "square.and.pencil", type: "sfSymbol" as const },
770 identifier: "thread-left-new-task",
771 onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),
772 type: "button" as const,
773 }),
774 ],
775 [panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
776 );
777 const androidHeaderActions = useMemo<ReadonlyArray<AndroidHeaderAction>>(() => {
778 if (Platform.OS !== "android") return [];
779​
780 const actions: AndroidHeaderAction[] = [];
781 if (props.onReturnToThread) {
782 actions.push({
783 accessibilityLabel: "Return to chat",
784 icon: "chevron.left",
785 onPress: props.onReturnToThread,
786 });
787 }
788 if (selectedThreadCwd !== null) {
789 actions.push({
790 accessibilityLabel: "Open files",
791 icon: "folder",
792 onPress: handleOpenFilesInspector,
793 });
794 }
795 if (selectedThreadProject?.workspaceRoot) {
796 actions.push({
797 accessibilityLabel: "Open terminal",
798 icon: "terminal",
799 onPress: () => handleOpenTerminal(null),
800 });
801 }
802 actions.push({
803 accessibilityLabel: "Open git controls",
804 icon: "point.topleft.down.curvedto.point.bottomright.up",
805 onPress: handleOpenGitInspector,
806 });
807 if (mergeBackTargetThreadId !== null && mergeBackRun !== null) {
808 actions.push({
809 accessibilityLabel: "Merge back to source",
810 icon: "arrow.triangle.merge",
811 onPress: () => void handleMergeBack(),
812 });
813 }
814 if (fileInspector.supported && selectedThreadCwd !== null) {
815 actions.push({
816 accessibilityLabel: "Toggle inspector",
817 icon: "sidebar.right",
818 onPress: handleToggleInspector,
819 });
820 }
821 return actions;
822 }, [
823 fileInspector.supported,
824 handleMergeBack,
825 handleOpenFilesInspector,
826 handleOpenTerminal,
827 handleOpenGitInspector,
828 handleToggleInspector,
829 mergeBackRun,
830 mergeBackTargetThreadId,
831 props.onReturnToThread,
832 selectedThreadCwd,
833 selectedThreadProject?.workspaceRoot,
834 ]);
835​
836 const handleEditFailedCreation = useCallback(async () => {
837 const creation = selectedThreadCreation?.message;
838 if (!creation?.creation || routeThreadIdentity === null) {
839 return;
840 }
841 // The drain restored the prompt and attachments into the recovery draft
842 // the rejected creation owns. Open that draft by id: without it the sheet
843 // mints a fresh empty one and the restored content is unreachable.
844 try {
845 await recoverFailedThreadDraft(creation);
846 } catch (error) {
847 Alert.alert(
848 "Could not restore draft",
849 error instanceof Error ? error.message : String(error),
850 );
851 return;
852 }
853 clearPendingThreadCreationOutcome(routeThreadIdentity);
854 navigation.dispatch(
855 StackActions.replace("NewTaskSheet", {
856 screen: "NewTaskDraft",
857 params: {
858 draftId: restoredNewTaskDraftKey(creation.messageId),
859 environmentId: String(creation.environmentId),
860 projectId: String(creation.creation.projectId),
861 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
862 },
863 }),
864 );
865 }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
866 const awaitingBootstrapTurn =
867 selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false;
868 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
869 if (selectedThreadCreation === null) {
870 return awaitingBootstrapTurn ? { kind: "preparing", preparingWorktree: true } : null;
871 }
872 if (selectedThreadCreation.outcome?.kind === "failed") {
873 return {
874 kind: "failed",
875 reason: selectedThreadCreation.outcome.reason,
876 onEditTask: handleEditFailedCreation,
877 };
878 }
879 return {
880 kind: "preparing",
881 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
882 };
883 })();
884 // Deep links / cold starts land with Thread as the ONLY route, where the
885 // native back button does not render. Provide an explicit Home escape for
886 // that case; when history exists the native back button is used instead.
887 const canGoBack = navigation.canGoBack();
888 const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
889 () => [
890 withNativeGlassHeaderItem({
891 accessibilityLabel: "Go to threads list",
892 icon: { name: "list.bullet", type: "sfSymbol" as const },
893 identifier: "thread-left-home",
894 onPress: () => navigation.dispatch(StackActions.replace("Home")),
895 type: "button" as const,
896 }),
897 ],
898 [navigation],
899 );
900​
901 if (!environmentId || !threadId) {
902 return <OpeningThreadLoadingScreen />;
903 }
904​
905 if (!selectedThread) {
906 return <OpeningThreadLoadingScreen />;
907 }
908​
909 // A queued creation renders as ready content: its prompt is the whole
910 // conversation until the server creates the thread. The subscription's
911 // not-found error for that window is expected, not a load failure.
912 const contentPresentation =
913 creationState !== null
914 ? { kind: "ready" as const }
915 : projectThreadContentPresentation({
916 hasDetail: selectedThreadDetail !== null,
917 detailError: Option.getOrNull(selectedThreadDetailState.error),
918 detailDeleted: selectedThreadDetailState.status === "deleted",
919 connectionState: routeConnectionState,
920 });
921 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
922 const renderThreadRouteBody = (showActionControls: boolean) => (
923 <>
924 <ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
925​
926 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
927​
928 <View
929 className={materialYouStyleLayoutActive ? "flex-1 bg-thread-canvas" : "flex-1 bg-screen"}
930 style={
931 materialYouStyleLayoutActive
932 ? {
933 borderTopLeftRadius: 28,
934 borderTopRightRadius: 28,
935 marginRight: layout.usesSplitView ? 8 : 0,
936 overflow: "hidden",
937 }
938 : undefined
939 }
940 >
941 <ThreadDetailScreen
942 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
943 contentPresentation={contentPresentation}
944 screenTone={connectionTone(routeConnectionState)}
945 connectionError={routeConnectionError}
946 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
947 feedbackSubmissions={composer.feedbackSubmissions}
948 onDismissFeedback={composer.dismissFeedback}
949 selectedThreadFeed={composer.selectedThreadFeed}
950 activityRun={composer.selectedThreadActivityRun}
951 activeWorkStartedAt={composer.activeWorkStartedAt}
952 isCompacting={composer.isCompacting}
953 creationState={creationState}
954 activePendingApproval={requests.activePendingApproval}
955 respondingApprovalId={requests.respondingApprovalId}
956 activePendingUserInput={requests.activePendingUserInput}
957 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
958 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
959 respondingUserInputId={requests.respondingUserInputId}
960 draftMessage={composer.draftMessage}
961 draftAttachments={composer.draftAttachments}
962 connectionStateLabel={routeConnectionState}
963 threadSyncStatus={selectedThreadDetailState.status}
964 historyControls={historyControls}
965 activeThreadBusy={composer.activeThreadBusy}
966 canStopThread={composer.interruptibleRunId !== null}
967 queuedRunEdit={composer.queuedRunEdit}
968 composerDraftKey={composer.composerDraftKey}
969 followUpBehavior={composer.followUpBehavior}
970 canSteerActiveTurn={composer.canSteerActiveTurn}
971 isSavingQueuedEdit={composer.isSavingQueuedEdit}
972 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
973 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
974 environmentId={selectedThread.environmentId}
975 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
976 threadCwd={selectedThreadCwd}
977 selectedThreadQueueCount={composer.selectedThreadQueueCount}
978 queuedMessages={composer.selectedThreadQueuedMessages}
979 dispatchingMessageId={composer.dispatchingQueuedMessageId}
980 layoutVariant={layout.variant}
981 usesAutomaticContentInsets={usesNativeHeaderGlass}
982 onOpenConnectionEditor={handleOpenConnectionEditor}
983 onChangeDraftMessage={composer.onChangeDraftMessage}
984 onPickDraftMedia={composer.onPickDraftMedia}
985 onPickDraftFiles={composer.onPickDraftFiles}
986 onNativePasteImages={composer.onNativePasteImages}
987 onNativePasteText={composer.onNativePasteText}
988 onRemoveDraftImage={composer.onRemoveDraftImage}
989 serverConfig={serverConfig}
990 onStopThread={handleStopThread}
991 onSendMessage={composer.onSendMessage}
992 onReconnectEnvironment={handleReconnectEnvironment}
993 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
994 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
995 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
996 onRespondToApproval={requests.onRespondToApproval}
997 onSelectUserInputOption={requests.onSelectUserInputOption}
998 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
999 onSubmitUserInput={requests.onSubmitUserInput}
1000 onDismissUserInput={requests.onDismissUserInput}
1001 />
1002 </View>
1003 </>
1004 );
1005​
1006 return (
1007 <>
1008 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1009 <NativeStackScreenOptions
1010 optionsVersion={threadGitControlProps.projectScripts}
1011 options={{
1012 // Android draws its own in-flow header (AndroidScreenHeader below);
1013 // the native stack header stays iOS-only.
1014 headerShown: Platform.OS !== "android",
1015 headerTitle: selectedThread.title,
1016 headerTitleStyle: usesNativeHeaderGlass
1017 ? {
1018 fontSize: 17,
1019 fontWeight: "800",
1021 : undefined,
1022 title: selectedThread.title,
1023 headerBackVisible: !layout.usesSplitView,
1024 // Compact uses the NATIVE back button when a previous route exists;
1025 // deep links / cold starts get an explicit Home button instead.
1026 // Split view always uses its custom left items.
1027 unstable_headerLeftItems:
1028 Platform.OS === "ios"
1029 ? layout.usesSplitView
1030 ? () => splitLeftHeaderItems
1031 : canGoBack
1032 ? undefined
1033 : () => compactHomeHeaderItems
1034 : undefined,
1035 // Search lives in the persistent sidebar, so the split header keeps
1036 // the git controls on the RIGHT (no center items — center space is
1037 // reserved for future breadcrumbs/status).
1038 unstable_headerRightItems:
1039 Platform.OS === "ios"
1040 ? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
1041 : undefined,
1042 unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
1043 contentStyle:
1044 Platform.OS === "android" && materialYouStyleLayoutActive
1045 ? { backgroundColor: headerColor }
1046 : undefined,
1047 }}
1048 />
1049​
1050 {Platform.OS === "android" ? (
1051 <AndroidScreenHeader
1052 title={selectedThread.title}
1053 subtitle={headerSubtitle}
1054 onBack={
1055 layout.usesSplitView
1056 ? undefined
1057 : () => {
1058 // A deep link or cold start has no previous route; Home is the way out.
1059 // Read the history at press time: it changes without re-rendering this screen.
1060 if (navigation.canGoBack()) navigation.goBack();
1061 else navigation.dispatch(StackActions.replace("Home"));
1064 actions={androidHeaderActions}
1065 hideBottomBorder={materialYouStyleLayoutActive}
1066 />
1067 ) : null}
1068​
1069 {/* Android surfaces the git/files/inspector actions in its in-flow
1070 header above, so the fallback action toolbar stays iOS-only. */}
1071 {renderThreadRouteBody(
1072 Platform.OS !== "android" && !layout.usesSplitView && !usesNativeHeaderGlass,
1073 )}
1074 </>
1075 );