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

ThreadRouteScreen.tsx

1,165 lines42.2 KB

1import { NativeStackScreenOptions } from "../../native/StackHeader";
2import {
3 StackActions,
4 useFocusEffect,
5 useIsFocused,
6 useNavigation,
7 type StaticScreenProps,
8} from "@react-navigation/native";
9import {
10 useCallback,
11 useEffect,
12 useMemo,
13 useRef,
14 useState,
15 useSyncExternalStore,
16 type ReactNode,
17} from "react";
18import * as Option from "effect/Option";
19import {
20 DEFAULT_SERVER_SETTINGS,
21 EnvironmentId,
22 ThreadId,
23 type ProjectScript,
24} from "@t3tools/contracts";
25import {
26 requestOlderThreadTurns,
27 threadHasOlderTurns,
28} from "@t3tools/client-runtime/state/threads";
29import {
30 projectScriptCwd,
31 projectScriptRuntimeEnv,
32 resolveProjectScripts,
33} from "@t3tools/shared/projectScripts";
34import { Alert, Platform, ScrollView, View } from "react-native";
35import { useSafeAreaInsets } from "react-native-safe-area-context";
36import { useWorkspaceState } from "../../state/workspace";
37import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
38import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
39import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
40import { useEnvironmentQuery } from "../../state/query";
41import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
42import { vcsEnvironment } from "../../state/vcs";
43​
44import { EmptyState } from "../../components/EmptyState";
45import {
46 AndroidScreenHeader,
47 type AndroidHeaderAction,
48} from "../../components/AndroidScreenHeader";
49import { LoadingScreen } from "../../components/LoadingScreen";
50import { scopedThreadKey } from "../../lib/scopedEntities";
51import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
52import { connectionTone } from "../connection/connectionTone";
53​
54import {
55 useRemoteConnections,
56 useRemoteConnectionStatus,
57 useRemoteEnvironmentRuntime,
58} from "../../state/use-remote-environment-registry";
59import { useKnownTerminalSessions } from "../../state/use-terminal-session";
60import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
61import { useThreadSelection } from "../../state/use-thread-selection";
62import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
63import {
64 buildTerminalMenuSessions,
65 nextOpenTerminalId,
66 resolveProjectScriptTerminalId,
67} from "../terminal/terminalMenu";
68import {
69 resolvePreferredThreadWorktreePath,
70 stagePendingTerminalLaunch,
71} from "../terminal/terminalLaunchContext";
72import { terminalDebugLog } from "../terminal/terminalDebugLog";
73import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
74import {
75 ThreadGitControls,
76 useThreadGitCenterHeaderItems,
77 useThreadGitRightHeaderItems,
78} from "./ThreadGitControls";
79import { GitOverviewSheet } from "./git/GitOverviewSheet";
80import { useAtomCommand } from "../../state/use-atom-command";
81import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
82import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
83import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
84import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
85import { useThreadComposerState } from "../../state/use-thread-composer-state";
86import { threadContextReachedLimit } from "../../state/contextLimit";
87import { threadEnvironment } from "../../state/threads";
88import { waitForComposerDraftsLoaded } from "../../state/use-composer-drafts";
89import {
90 prepareThreadHandoverDraft,
91 threadHandoverDraftImportId,
92} from "../../state/threadHandoverDraft";
93import { projectThreadContentPresentation } from "./threadContentPresentation";
94import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
95import {
96 useAdaptiveWorkspaceLayout,
97 useAdaptiveWorkspacePaneRole,
98 useRegisterWorkspaceInspector,
99} from "../layout/AdaptiveWorkspaceLayout";
100import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
101import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
102import {
103 ThreadInspectorContentStack,
104 type ThreadInspectorMode,
105} from "./thread-inspector-content-stack";
106​
107interface ThreadInspectorSelection {
108 readonly routeThreadIdentity: string | null;
109 readonly mode: ThreadInspectorMode;
111​
112type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;
113​
114interface MobileHandoverAttempt {
115 readonly handover: string;
116 readonly draftImportId: string;
118​
119const mobileHandoverAttempts = new Map<string, MobileHandoverAttempt>();
120const generatingMobileHandovers = new Set<string>();
121const mobileHandoverListeners = new Set<() => void>();
122const MAX_PENDING_MOBILE_HANDOVERS = 8;
123​
124function saveMobileHandoverAttempt(sourceThreadKey: string, attempt: MobileHandoverAttempt): void {
125 mobileHandoverAttempts.delete(sourceThreadKey);
126 mobileHandoverAttempts.set(sourceThreadKey, attempt);
127 while (mobileHandoverAttempts.size > MAX_PENDING_MOBILE_HANDOVERS) {
128 const oldestKey = mobileHandoverAttempts.keys().next().value;
129 if (oldestKey === undefined) break;
130 mobileHandoverAttempts.delete(oldestKey);
131 }
133​
134function notifyMobileHandoverListeners(): void {
135 for (const listener of mobileHandoverListeners) {
136 listener();
137 }
139​
140function subscribeMobileHandoverState(listener: () => void): () => void {
141 mobileHandoverListeners.add(listener);
142 return () => mobileHandoverListeners.delete(listener);
144​
145function mobileHandoverStateSnapshot(threadKey: string | null): string {
146 if (threadKey === null) return "";
147 return `${generatingMobileHandovers.has(threadKey)}:${mobileHandoverAttempts.has(threadKey)}`;
149​
150function InspectorPaneRoleActivation() {
151 useAdaptiveWorkspacePaneRole("inspector");
152 return null;
154​
155function firstRouteParam(value: string | string[] | undefined): string | null {
156 if (Array.isArray(value)) {
157 return value[0] ?? null;
158 }
159​
160 return value ?? null;
162​
163function OpeningThreadLoadingScreen() {
164 return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
166​
167type ThreadRouteScreenRouteProps = StaticScreenProps<{
168 readonly environmentId: string;
169 readonly threadId: string;
170}>;
171​
172interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
173 readonly onReturnToThread?: () => void;
174 readonly renderInspector?: (headerInset: number) => ReactNode;
176​
177function ThreadUnavailableScreen() {
178 return (
179 <ScrollView
180 contentInsetAdjustmentBehavior="automatic"
181 contentContainerStyle={{
182 flexGrow: 1,
183 justifyContent: "center",
184 paddingHorizontal: 24,
185 paddingVertical: 32,
186 }}
187 className="bg-screen flex-1"
188 >
189 <EmptyState
190 title="Thread unavailable"
191 detail="This thread is not available in the current mobile snapshot."
192 />
193 </ScrollView>
194 );
196​
197export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
198 const { state: workspaceState } = useWorkspaceState();
199 const { connectionState } = useRemoteConnectionStatus();
200 const { selectedThread } = useThreadSelection();
201 const params = props.route.params;
202 const environmentIdRaw = firstRouteParam(params.environmentId);
203 const threadIdRaw = firstRouteParam(params.threadId);
204 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
205 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
206 const routeConnectionState =
207 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
208 const routeThreadKey =
209 environmentId !== null && threadIdRaw !== null
210 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
211 : null;
212 const selectedThreadKey =
213 selectedThread === null
214 ? null
215 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
216 const selectedThreadDetailState = useSelectedThreadDetailState();
217​
218 if (environmentId === null || threadIdRaw === null) {
219 return <OpeningThreadLoadingScreen />;
220 }
221​
222 // Render the full thread chrome (header, feed, composer) as soon as the
223 // thread SHELL is known — no blocking on message detail. The feed shows a
224 // loading placeholder while messages fetch, the floating pill above the
225 // composer reports loading/syncing, and the composer's connection pill
226 // reports connecting/reconnecting status.
227 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
228 return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
229 }
230​
231 const stillHydrating =
232 workspaceState.isLoadingConnections ||
233 routeConnectionState === "connecting" ||
234 routeConnectionState === "reconnecting";
235​
236 if (stillHydrating) {
237 return <OpeningThreadLoadingScreen />;
238 }
239​
240 return <ThreadUnavailableScreen />;
242​
243function ThreadRouteContent(
244 props: ThreadRouteScreenProps & {
245 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
246 },
247) {
248 const { materialYouStyleLayoutActive, themeVariables } = useAppearancePreferences();
249 const headerColor = themeVariables["--color-header"];
250 const {
251 fileInspector,
252 layout,
253 panes,
254 showAuxiliaryPane,
255 toggleAuxiliaryPane,
256 togglePrimarySidebar,
257 } = useAdaptiveWorkspaceLayout();
258 const { connectionState } = useRemoteConnectionStatus();
259 const { onReconnectEnvironment } = useRemoteConnections();
260 const {
261 selectedThread,
262 selectedThreadCreation,
263 selectedThreadProject,
264 selectedEnvironmentConnection,
265 } = useThreadSelection();
266 const selectedThreadDetailState = props.selectedThreadDetailState;
267 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
268 // "Load earlier turns" header state for windowed (paginated) thread loads.
269 const loadEarlierTurns = useMemo(() => {
270 if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
271 return null;
272 }
273 return {
274 loading:
275 selectedThreadDetailState.page._tag === "Some" &&
276 selectedThreadDetailState.page.value.loadingOlder,
277 onLoadEarlier: () => {
278 requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
279 },
280 };
281 }, [selectedThread, selectedThreadDetailState]);
282 const { selectedThreadCwd, selectedThreadWorktreePath } = useSelectedThreadWorktree();
283 const composer = useThreadComposerState();
284 const gitState = useSelectedThreadGitState();
285 const gitActions = useSelectedThreadGitActions();
286 const requests = useSelectedThreadRequests();
287 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
288 const generateThreadHandover = useAtomCommand(threadEnvironment.generateHandover, {
289 reportFailure: false,
290 });
291 const navigation = useNavigation();
292 const isFocused = useIsFocused();
293 const params = props.route.params;
294 const environmentIdRaw = firstRouteParam(params.environmentId);
295 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
296 const threadId = firstRouteParam(params.threadId);
297 const routeThreadIdentity =
298 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
299 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
300 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
301 );
302 const inspectorMode = (() => {
303 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
304 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
305 return null;
306 }
307 return inspectorSelection.mode;
308 }
309 return null;
310 })();
311 useEffect(() => {
312 if (
313 fileInspector.supported &&
314 selectedThreadCwd === null &&
315 inspectorMode === null &&
316 panes.auxiliaryPaneVisible
317 ) {
318 toggleAuxiliaryPane();
319 }
320 }, [
321 fileInspector.supported,
322 inspectorMode,
323 panes.auxiliaryPaneVisible,
324 selectedThreadCwd,
325 toggleAuxiliaryPane,
326 ]);
327​
328 useEffect(() => {
329 setInspectorSelection((current) => {
330 if (props.renderInspector === undefined) {
331 if (current === null || current.mode === "route") {
332 return null;
333 }
334 return { ...current, routeThreadIdentity };
335 }
336​
337 if (current === null || current.mode === "route") {
338 return { routeThreadIdentity, mode: "route" };
339 }
340​
341 return { ...current, routeThreadIdentity };
342 });
343 }, [props.renderInspector, routeThreadIdentity]);
344​
345 useFocusEffect(
346 useCallback(() => {
347 return () => {
348 if (props.renderInspector === undefined) {
349 // Inspectors are contextual to this chat destination. Clear the
350 // hidden chat copy after a native push so returning from Files,
351 // Review, or Terminal cannot reserve an empty trailing pane.
352 setInspectorSelection(null);
353 }
354 };
355 }, [props.renderInspector]),
356 );
357 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
358 const routeConnectionState =
359 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
360 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
361 const selectedThreadWithDraftSettings = useMemo(
362 () =>
363 selectedThread
364 ? {
365 ...selectedThread,
366 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
367 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
368 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
369 }
370 : null,
371 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
372 );
373 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
374 const selectedHandoverKeyRef = useRef(
375 selectedThread
376 ? threadHandoverDraftImportId(selectedThread.environmentId, selectedThread.id)
377 : null,
378 );
379 selectedHandoverKeyRef.current = selectedThread
380 ? threadHandoverDraftImportId(selectedThread.environmentId, selectedThread.id)
381 : null;
382 const currentHandoverKey = selectedThread
383 ? threadHandoverDraftImportId(selectedThread.environmentId, selectedThread.id)
384 : null;
385 const handoverState = useSyncExternalStore(
386 subscribeMobileHandoverState,
387 () => mobileHandoverStateSnapshot(currentHandoverKey),
388 () => mobileHandoverStateSnapshot(currentHandoverKey),
389 );
390 const isGeneratingHandover = handoverState.startsWith("true:");
391 const mountedRef = useRef(true);
392 const isFocusedRef = useRef(isFocused);
393 isFocusedRef.current = isFocused;
394 useEffect(() => {
395 mountedRef.current = true;
396 return () => {
397 mountedRef.current = false;
398 };
399 }, []);
400 const handleGenerateHandover = useCallback(async () => {
401 if (
402 !selectedThread ||
403 !selectedThreadProject ||
404 !selectedThreadDetail ||
405 serverConfig?.environment.capabilities.threadHandoverGeneration !== true ||
406 currentHandoverKey === null
407 ) {
408 return;
409 }
410 const sourceThreadKey = currentHandoverKey;
411 if (generatingMobileHandovers.has(sourceThreadKey)) return;
412 generatingMobileHandovers.add(sourceThreadKey);
413 notifyMobileHandoverListeners();
414 try {
415 let attempt = mobileHandoverAttempts.get(sourceThreadKey);
416 if (attempt === undefined) {
417 const result = await generateThreadHandover({
418 environmentId: selectedThread.environmentId,
419 input: { threadId: selectedThread.id },
420 });
421 if (result._tag === "Failure") {
422 Alert.alert("Could not create handover", "Handover generation failed. Try again.");
423 return;
424 }
425 attempt = {
426 handover: result.value.handover,
427 draftImportId: threadHandoverDraftImportId(
428 selectedThread.environmentId,
429 selectedThread.id,
430 ),
431 };
432 saveMobileHandoverAttempt(sourceThreadKey, attempt);
433 notifyMobileHandoverListeners();
434 }
435 await waitForComposerDraftsLoaded();
436 if (
437 !mountedRef.current ||
438 !isFocusedRef.current ||
439 selectedHandoverKeyRef.current !== sourceThreadKey
440 ) {
441 return;
442 }
443​
444 const destinationDraftKey = await prepareThreadHandoverDraft({
445 environmentId: selectedThread.environmentId,
446 projectId: selectedThread.projectId,
447 importId: attempt.draftImportId,
448 handover: attempt.handover,
449 workspaceSelection: {
450 mode: "local",
451 branch: selectedThread.branch,
452 worktreePath: selectedThreadWorktreePath,
453 startFromOrigin: false,
454 },
455 });
456​
457 if (
458 !mountedRef.current ||
459 !isFocusedRef.current ||
460 selectedHandoverKeyRef.current !== sourceThreadKey
461 ) {
462 return;
463 }
464 navigation.navigate("NewTaskSheet", {
465 screen: "NewTaskDraft",
466 params: {
467 environmentId: String(selectedThread.environmentId),
468 projectId: String(selectedThread.projectId),
469 title: selectedThreadProject.title,
470 draftId: destinationDraftKey,
471 },
472 });
473 mobileHandoverAttempts.delete(sourceThreadKey);
474 notifyMobileHandoverListeners();
475 } catch (error) {
476 Alert.alert(
477 "Could not open handover",
478 error instanceof Error
479 ? error.message
480 : "The generated handover remains available to retry.",
481 );
482 } finally {
483 generatingMobileHandovers.delete(sourceThreadKey);
484 notifyMobileHandoverListeners();
485 }
486 }, [
487 currentHandoverKey,
488 generateThreadHandover,
489 isFocused,
490 navigation,
491 selectedThread,
492 selectedThreadDetail,
493 selectedThreadProject,
494 serverConfig?.environment.capabilities.threadHandoverGeneration,
495 selectedThreadWorktreePath,
496 ]);
497​
498 /* ─── Native header theming ──────────────────────────────────────── */
499 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
500 const headerSubtitle = [
501 selectedThreadProject?.title ?? null,
502 selectedEnvironmentConnection?.environmentLabel ?? null,
503 ]
504 .filter(Boolean)
505 .join(" · ");
506 /* ─── Git status for native header trigger ───────────────────────── */
507 const gitStatus = useEnvironmentQuery(
508 selectedThread !== null && selectedThreadCwd !== null
509 ? vcsEnvironment.status({
510 environmentId: selectedThread.environmentId,
511 input: { cwd: selectedThreadCwd },
512 })
513 : null,
514 );
515 const knownTerminalSessions = useKnownTerminalSessions({
516 environmentId: selectedThread?.environmentId ?? null,
517 threadId: selectedThread?.id ?? null,
518 });
519 const terminalMenuSessions = useMemo(
520 () =>
521 buildTerminalMenuSessions({
522 knownSessions: knownTerminalSessions,
523 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
524 }),
525 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
526 );
527 const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
528 const handleReconnectEnvironment = useCallback(() => {
529 if (!environmentId) {
530 return;
531 }
532 onReconnectEnvironment(environmentId);
533 }, [environmentId, onReconnectEnvironment]);
534​
535 /* ─── Git action progress (for overlay banner) ──────────────────── */
536 const gitActionProgressTarget = useMemo(
537 () => ({
538 environmentId: selectedThread?.environmentId ?? null,
539 cwd: selectedThreadCwd,
540 }),
541 [selectedThread?.environmentId, selectedThreadCwd],
542 );
543 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
544​
545 const handleOpenGitInspector = useCallback(() => {
546 if (!fileInspector.supported) {
547 if (selectedThread === null) {
548 return;
549 }
550 navigation.navigate("GitOverview", {
551 environmentId: String(selectedThread.environmentId),
552 threadId: String(selectedThread.id),
553 });
554 return;
555 }
556 setInspectorSelection({ routeThreadIdentity, mode: "git" });
557 showAuxiliaryPane("inspector");
558 }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
559 const handleOpenFilesInspector = useCallback(() => {
560 if (selectedThread === null || selectedThreadCwd === null) {
561 return;
562 }
563 if (!fileInspector.supported) {
564 navigation.navigate("ThreadFiles", {
565 environmentId: String(selectedThread.environmentId),
566 threadId: String(selectedThread.id),
567 });
568 return;
569 }
570 setInspectorSelection({
571 routeThreadIdentity,
572 mode: props.renderInspector === undefined ? "files" : "route",
573 });
574 showAuxiliaryPane("inspector");
575 }, [
576 fileInspector.supported,
577 navigation,
578 props.renderInspector,
579 routeThreadIdentity,
580 selectedThread,
581 selectedThreadCwd,
582 showAuxiliaryPane,
583 ]);
584 const inspectorToggleActionRef = useRef({
585 inspectorMode,
586 openFilesInspector: handleOpenFilesInspector,
587 toggleAuxiliaryPane,
588 });
589 inspectorToggleActionRef.current = {
590 inspectorMode,
591 openFilesInspector: handleOpenFilesInspector,
592 toggleAuxiliaryPane,
593 };
594 const handleToggleInspector = useCallback(() => {
595 const action = inspectorToggleActionRef.current;
596 if (action.inspectorMode === null) {
597 action.openFilesInspector();
598 return;
599 }
600 action.toggleAuxiliaryPane();
601 }, []);
602 const handleSelectInspectorFile = useCallback(
603 (path: string) => {
604 if (selectedThread === null) {
605 return;
606 }
607 const params = {
608 environmentId: String(selectedThread.environmentId),
609 threadId: String(selectedThread.id),
610 path: path.split("/").filter((segment) => segment.length > 0),
611 };
612 if (fileInspector.supported) {
613 navigation.navigate("ThreadFile", params);
614 return;
615 }
616 navigation.navigate("ThreadFile", params);
617 },
618 [fileInspector.supported, navigation, selectedThread],
619 );
620 // The workspace inspector column spans the full window height. On iOS the
621 // panes bring their own nested native headers (which underlap the status
622 // bar); elsewhere the pane content pads itself below the top inset.
623 const safeAreaInsets = useSafeAreaInsets();
624 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
625 const GitInspector = useCallback(
626 () => (
627 <GitOverviewSheet
628 headerInset={inspectorHeaderInset}
629 presentation="inspector"
630 route={{ params: props.route.params }}
631 />
632 ),
633 [inspectorHeaderInset, props.route.params],
634 );
635 const FilesInspector = useCallback(
636 () =>
637 selectedThread !== null && selectedThreadCwd !== null ? (
638 <ThreadFileNavigatorPane
639 cwd={selectedThreadCwd}
640 environmentId={selectedThread.environmentId}
641 headerInset={inspectorHeaderInset}
642 projectName={selectedThreadProject?.title ?? "Files"}
643 selectedPath={null}
644 onSelectFile={handleSelectInspectorFile}
645 />
646 ) : null,
647 [
648 handleSelectInspectorFile,
649 inspectorHeaderInset,
650 selectedThread,
651 selectedThreadCwd,
652 selectedThreadProject?.title,
653 ],
654 );
655 const RouteInspector = useCallback(
656 () => props.renderInspector?.(inspectorHeaderInset),
657 [inspectorHeaderInset, props.renderInspector],
658 );
659 const renderInspectorStack = useCallback(
660 () =>
661 inspectorMode === null ? null : (
662 <ThreadInspectorContentStack
663 Files={FilesInspector}
664 Git={GitInspector}
665 mode={inspectorMode}
666 Route={props.renderInspector ? RouteInspector : undefined}
667 />
668 ),
669 [FilesInspector, GitInspector, RouteInspector, inspectorMode, props.renderInspector],
670 );
671 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
672 // Hand the inspector to the workspace so it renders beside the navigator,
673 // outside this screen's native header — the terminal/git/files toolbar
674 // stays anchored to the chat pane instead of floating above the inspector.
675 useRegisterWorkspaceInspector(activeInspectorRenderer);
676​
677 const handleOpenConnectionEditor = useCallback(() => {
678 void navigation.navigate("Connections");
679 }, [navigation]);
680 const handleStopThread = useCallback(() => {
681 if (
682 !selectedThread ||
683 (selectedThread.session?.status !== "running" &&
684 selectedThread.session?.status !== "starting")
685 ) {
686 return;
687 }
688 return interruptThreadTurn({
689 environmentId: selectedThread.environmentId,
690 input: {
691 threadId: selectedThread.id,
692 ...(selectedThread.session.activeTurnId
693 ? { turnId: selectedThread.session.activeTurnId }
694 : {}),
695 },
696 });
697 }, [interruptThreadTurn, selectedThread]);
698​
699 const handleOpenTerminal = useCallback(
700 (nextTerminalId?: string | null) => {
701 terminalDebugLog("terminal-menu:open-existing", {
702 terminalId: nextTerminalId ?? null,
703 hasThread: Boolean(selectedThread),
704 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
705 });
706​
707 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
708 return;
709 }
710​
711 void navigation.navigate("ThreadTerminal", {
712 environmentId: String(selectedThread.environmentId),
713 threadId: String(selectedThread.id),
714 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
715 });
716 },
717 [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
718 );
719​
720 const handleOpenNewTerminal = useCallback(() => {
721 terminalDebugLog("terminal-menu:open-new", {
722 hasThread: Boolean(selectedThread),
723 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
724 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
725 });
726​
727 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
728 return;
729 }
730​
731 const nextId = nextOpenTerminalId({
732 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
733 });
734 void navigation.navigate("ThreadTerminal", {
735 environmentId: String(selectedThread.environmentId),
736 threadId: String(selectedThread.id),
737 terminalId: nextId,
738 });
739 }, [navigation, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
740​
741 const handleRunProjectScript = useCallback(
742 async (script: ProjectScript) => {
743 terminalDebugLog("project-script:press", {
744 scriptId: script.id,
745 command: script.command,
746 hasThread: Boolean(selectedThread),
747 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
748 });
749​
750 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
751 terminalDebugLog("project-script:abort", {
752 scriptId: script.id,
753 reason: "no-thread-or-workspace",
754 });
755 return;
756 }
757​
758 const targetTerminalId = resolveProjectScriptTerminalId({
759 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
760 hasRunningTerminal: terminalMenuSessions.some(
761 (session) => session.status === "running" || session.status === "starting",
762 ),
763 });
764 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
765 threadShellWorktreePath: selectedThread.worktreePath ?? null,
766 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
767 });
768 const cwd = projectScriptCwd({
769 project: { cwd: selectedThreadProject.workspaceRoot },
770 worktreePath: preferredWorktreePath,
771 });
772 const env = projectScriptRuntimeEnv({
773 project: { cwd: selectedThreadProject.workspaceRoot },
774 worktreePath: preferredWorktreePath,
775 });
776 stagePendingTerminalLaunch({
777 target: {
778 environmentId: selectedThread.environmentId,
779 threadId: selectedThread.id,
780 terminalId: targetTerminalId,
781 },
782 launch: {
783 cwd,
784 worktreePath: preferredWorktreePath,
785 env,
786 initialInput: `${script.command}\r`,
787 },
788 });
789 terminalDebugLog("project-script:staged", {
790 scriptId: script.id,
791 terminalId: targetTerminalId,
792 cwd,
793 worktreePath: preferredWorktreePath,
794 });
795​
796 void navigation.navigate("ThreadTerminal", {
797 environmentId: String(selectedThread.environmentId),
798 threadId: String(selectedThread.id),
799 terminalId: targetTerminalId,
800 });
801 },
802 [
803 navigation,
804 selectedThread,
805 selectedThreadDetailWorktreePath,
806 selectedThreadProject,
807 terminalMenuSessions,
808 ],
809 );
810 const threadGitControlProps = {
811 environmentId: environmentIdRaw ?? "",
812 threadId: threadId ?? "",
813 auxiliaryPaneControl:
814 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
815 ? {
816 accessibilityLabel: "Toggle inspector",
817 onPress: handleToggleInspector,
818 }
819 : undefined,
820 onOpenFilesInspector:
821 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
822 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
823 currentBranch: selectedThread?.branch ?? null,
824 gitStatus: gitStatus.data,
825 gitOperationLabel: gitState.gitOperationLabel,
826 canOpenTerminal: Boolean(selectedThreadProject?.workspaceRoot),
827 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
828 projectScripts: selectedThreadProject
829 ? resolveProjectScripts(
830 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
831 selectedThreadProject,
832 )
833 : [],
834 terminalSessions: terminalMenuSessions,
835 showDirectFileControl: layout.usesSplitView,
836 onOpenTerminal: handleOpenTerminal,
837 onOpenNewTerminal: handleOpenNewTerminal,
838 onRunProjectScript: handleRunProjectScript,
839 onPull: gitActions.onPullSelectedThreadBranch,
840 onRunAction: gitActions.onRunSelectedThreadGitAction,
841 };
842 const threadCenterHeaderItems = useThreadGitCenterHeaderItems(threadGitControlProps);
843 const compactRightHeaderItems = useThreadGitRightHeaderItems(threadGitControlProps);
844 const splitLeftHeaderItems = useMemo<NativeHeaderItems>(
845 () => [
846 {
847 // Match Mail's split-view detail toolbar: the first detail action sits
848 // inside the content pane, not flush against the sidebar divider.
849 spacing: 18,
850 type: "spacing" as const,
851 },
852 ...(props.onReturnToThread
853 ? [
854 withNativeGlassHeaderItem({
855 accessibilityLabel: "Return to chat",
856 icon: { name: "chevron.left", type: "sfSymbol" as const },
857 identifier: "thread-left-return",
858 onPress: props.onReturnToThread,
859 type: "button" as const,
860 }),
861 ]
862 : []),
863 withNativeGlassHeaderItem({
864 accessibilityLabel: panes.primarySidebarVisible
865 ? "Maximize content"
866 : "Show thread sidebar",
867 icon: {
868 name: panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left",
869 type: "sfSymbol" as const,
870 },
871 identifier: "thread-left-sidebar",
872 onPress: togglePrimarySidebar,
873 type: "button" as const,
874 }),
875 withNativeGlassHeaderItem({
876 accessibilityLabel: "New task",
877 icon: { name: "square.and.pencil", type: "sfSymbol" as const },
878 identifier: "thread-left-new-task",
879 onPress: () => navigation.navigate("NewTaskSheet", { screen: "NewTask" }),
880 type: "button" as const,
881 }),
882 ],
883 [panes.primarySidebarVisible, props.onReturnToThread, navigation, togglePrimarySidebar],
884 );
885 const androidHeaderActions = useMemo<ReadonlyArray<AndroidHeaderAction>>(() => {
886 if (Platform.OS !== "android") return [];
887​
888 const actions: AndroidHeaderAction[] = [];
889 if (props.onReturnToThread) {
890 actions.push({
891 accessibilityLabel: "Return to chat",
892 icon: "chevron.left",
893 onPress: props.onReturnToThread,
894 });
895 }
896 if (selectedThreadCwd !== null) {
897 actions.push({
898 accessibilityLabel: "Open files",
899 icon: "folder",
900 onPress: handleOpenFilesInspector,
901 });
902 }
903 if (selectedThreadProject?.workspaceRoot) {
904 actions.push({
905 accessibilityLabel: "Open terminal",
906 icon: "terminal",
907 onPress: () => handleOpenTerminal(null),
908 });
909 }
910 actions.push({
911 accessibilityLabel: "Open git controls",
912 icon: "point.topleft.down.curvedto.point.bottomright.up",
913 onPress: handleOpenGitInspector,
914 });
915 if (fileInspector.supported && selectedThreadCwd !== null) {
916 actions.push({
917 accessibilityLabel: "Toggle inspector",
918 icon: "sidebar.right",
919 onPress: handleToggleInspector,
920 });
921 }
922 return actions;
923 }, [
924 fileInspector.supported,
925 handleOpenFilesInspector,
926 handleOpenTerminal,
927 handleOpenGitInspector,
928 handleToggleInspector,
929 props.onReturnToThread,
930 selectedThreadCwd,
931 selectedThreadProject?.workspaceRoot,
932 ]);
933​
934 const handleEditFailedCreation = useCallback(async () => {
935 const creation = selectedThreadCreation?.message;
936 if (!creation?.creation || routeThreadIdentity === null) {
937 return;
938 }
939 // The drain restored the prompt and attachments into the recovery draft
940 // the rejected creation owns. Open that draft by id: without it the sheet
941 // mints a fresh empty one and the restored content is unreachable.
942 try {
943 await recoverFailedThreadDraft(creation);
944 } catch (error) {
945 Alert.alert(
946 "Could not restore draft",
947 error instanceof Error ? error.message : String(error),
948 );
949 return;
950 }
951 clearPendingThreadCreationOutcome(routeThreadIdentity);
952 navigation.dispatch(
953 StackActions.replace("NewTaskSheet", {
954 screen: "NewTaskDraft",
955 params: {
956 draftId: restoredNewTaskDraftKey(creation.messageId),
957 environmentId: String(creation.environmentId),
958 projectId: String(creation.creation.projectId),
959 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
960 },
961 }),
962 );
963 }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
964 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
965 if (selectedThreadCreation === null) {
966 return null;
967 }
968 if (selectedThreadCreation.outcome?.kind === "failed") {
969 return {
970 kind: "failed",
971 reason: selectedThreadCreation.outcome.reason,
972 onEditTask: handleEditFailedCreation,
973 };
974 }
975 return {
976 kind: "preparing",
977 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
978 };
979 })();
980 // Deep links / cold starts land with Thread as the ONLY route, where the
981 // native back button does not render. Provide an explicit Home escape for
982 // that case; when history exists the native back button is used instead.
983 const canGoBack = navigation.canGoBack();
984 const compactHomeHeaderItems = useMemo<NativeHeaderItems>(
985 () => [
986 withNativeGlassHeaderItem({
987 accessibilityLabel: "Go to threads list",
988 icon: { name: "list.bullet", type: "sfSymbol" as const },
989 identifier: "thread-left-home",
990 onPress: () => navigation.dispatch(StackActions.replace("Home")),
991 type: "button" as const,
992 }),
993 ],
994 [navigation],
995 );
996​
997 if (!environmentId || !threadId) {
998 return <OpeningThreadLoadingScreen />;
999 }
1000​
1001 if (!selectedThread) {
1002 return <OpeningThreadLoadingScreen />;
1004​
1005 // A queued creation renders as ready content: its prompt is the whole
1006 // conversation until the server creates the thread. The subscription's
1007 // not-found error for that window is expected, not a load failure.
1008 const contentPresentation =
1009 creationState !== null
1010 ? { kind: "ready" as const }
1011 : projectThreadContentPresentation({
1012 hasDetail: selectedThreadDetail !== null,
1013 detailError: Option.getOrNull(selectedThreadDetailState.error),
1014 detailDeleted: selectedThreadDetailState.status === "deleted",
1015 connectionState: routeConnectionState,
1016 });
1017 const contextLimitReached =
1018 serverConfig !== null &&
1019 selectedThreadDetail !== null &&
1020 threadContextReachedLimit(
1021 selectedThreadDetail.activities,
1022 serverConfig?.settings.threadContextTokenLimit,
1023 );
1024 const renderThreadRouteBody = (showActionControls: boolean) => (
1025 <>
1026 <ThreadGitControls {...threadGitControlProps} showActionControls={showActionControls} />
1027​
1028 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
1029​
1030 <View
1031 className={materialYouStyleLayoutActive ? "flex-1 bg-thread-canvas" : "flex-1 bg-screen"}
1032 style={
1033 materialYouStyleLayoutActive
1034 ? {
1035 borderTopLeftRadius: 28,
1036 borderTopRightRadius: 28,
1037 marginRight: layout.usesSplitView ? 8 : 0,
1038 overflow: "hidden",
1040 : undefined
1043 <ThreadDetailScreen
1044 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
1045 contentPresentation={contentPresentation}
1046 screenTone={connectionTone(routeConnectionState)}
1047 connectionError={routeConnectionError}
1048 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
1049 feedbackSubmissions={composer.feedbackSubmissions}
1050 onDismissFeedback={composer.dismissFeedback}
1051 selectedThreadFeed={composer.selectedThreadFeed}
1052 activeWorkStartedAt={composer.activeWorkStartedAt}
1053 isCompacting={composer.isCompacting}
1054 creationState={creationState}
1055 activePendingApproval={requests.activePendingApproval}
1056 respondingApprovalId={requests.respondingApprovalId}
1057 activePendingUserInput={requests.activePendingUserInput}
1058 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1059 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1060 respondingUserInputId={requests.respondingUserInputId}
1061 draftMessage={composer.draftMessage}
1062 draftAttachments={composer.draftAttachments}
1063 connectionStateLabel={routeConnectionState}
1064 threadSyncStatus={selectedThreadDetailState.status}
1065 loadEarlier={loadEarlierTurns}
1066 environmentId={selectedThread.environmentId}
1067 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1068 threadCwd={selectedThreadCwd}
1069 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1070 queuedMessages={composer.selectedThreadQueuedMessages}
1071 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1072 layoutVariant={layout.variant}
1073 usesAutomaticContentInsets={usesNativeHeaderGlass}
1074 onOpenConnectionEditor={handleOpenConnectionEditor}
1075 onChangeDraftMessage={composer.onChangeDraftMessage}
1076 onPickDraftMedia={composer.onPickDraftMedia}
1077 onPickDraftFiles={composer.onPickDraftFiles}
1078 onNativePasteImages={composer.onNativePasteImages}
1079 onRemoveDraftImage={composer.onRemoveDraftImage}
1080 serverConfig={serverConfig}
1081 contextLimitReached={contextLimitReached}
1082 isGeneratingHandover={isGeneratingHandover}
1083 onGenerateHandover={
1084 serverConfig?.environment.capabilities.threadHandoverGeneration === true
1085 ? handleGenerateHandover
1086 : undefined
1088 onStopThread={handleStopThread}
1089 onSendMessage={composer.onSendMessage}
1090 onReconnectEnvironment={handleReconnectEnvironment}
1091 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
1092 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
1093 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1094 onRespondToApproval={requests.onRespondToApproval}
1095 onSelectUserInputOption={requests.onSelectUserInputOption}
1096 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1097 onSubmitUserInput={requests.onSubmitUserInput}
1098 onDismissUserInput={requests.onDismissUserInput}
1099 />
1100 </View>
1101 </>
1102 );
1103​
1104 return (
1105 <>
1106 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1107 <NativeStackScreenOptions
1108 optionsVersion={threadGitControlProps.projectScripts}
1109 options={{
1110 // Android draws its own in-flow header (AndroidScreenHeader below);
1111 // the native stack header stays iOS-only.
1112 headerShown: Platform.OS !== "android",
1113 headerTitle: selectedThread.title,
1114 headerTitleStyle: usesNativeHeaderGlass
1115 ? {
1116 fontSize: 17,
1117 fontWeight: "800",
1119 : undefined,
1120 title: selectedThread.title,
1121 headerBackVisible: !layout.usesSplitView,
1122 // Compact uses the NATIVE back button when a previous route exists;
1123 // deep links / cold starts get an explicit Home button instead.
1124 // Split view always uses its custom left items.
1125 unstable_headerLeftItems:
1126 Platform.OS === "ios"
1127 ? layout.usesSplitView
1128 ? () => splitLeftHeaderItems
1129 : canGoBack
1130 ? undefined
1131 : () => compactHomeHeaderItems
1132 : undefined,
1133 // Search lives in the persistent sidebar, so the split header keeps
1134 // the git controls on the RIGHT (no center items — center space is
1135 // reserved for future breadcrumbs/status).
1136 unstable_headerRightItems:
1137 Platform.OS === "ios"
1138 ? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
1139 : undefined,
1140 unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
1141 contentStyle:
1142 Platform.OS === "android" && materialYouStyleLayoutActive
1143 ? { backgroundColor: headerColor }
1144 : undefined,
1145 }}
1146 />
1147​
1148 {Platform.OS === "android" ? (
1149 <AndroidScreenHeader
1150 title={selectedThread.title}
1151 subtitle={headerSubtitle}
1152 onBack={layout.usesSplitView ? undefined : () => navigation.goBack()}
1153 actions={androidHeaderActions}
1154 hideBottomBorder={materialYouStyleLayoutActive}
1155 />
1156 ) : null}
1157​
1158 {/* Android surfaces the git/files/inspector actions in its in-flow
1159 header above, so the fallback action toolbar stays iOS-only. */}
1160 {renderThreadRouteBody(
1161 Platform.OS !== "android" && !layout.usesSplitView && !usesNativeHeaderGlass,
1162 )}
1163 </>
1164 );