Open History to see the last commit
1import { Stack, useLocalSearchParams, useRouter } from "expo-router";
2import { useCallback, useMemo, useState } from "react";
3import * as Arr from "effect/Array";
4import * as Option from "effect/Option";
5import { pipe } from "effect/Function";
6import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
7import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
8import { Pressable, ScrollView, Text as RNText, View, useColorScheme } from "react-native";
9import { useThemeColor } from "../../lib/useThemeColor";
10import { useVcsStatus } from "../../state/use-vcs-status";
11import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
12
13import { EmptyState } from "../../components/EmptyState";
14import { LoadingScreen } from "../../components/LoadingScreen";
15import { buildThreadRoutePath, buildThreadTerminalNavigation } from "../../lib/routes";
16import { scopedThreadKey } from "../../lib/scopedEntities";
17import { connectionTone } from "../connection/connectionTone";
18
19import { useRemoteCatalog } from "../../state/use-remote-catalog";
20import {
21 useRemoteConnectionStatus,
22 useRemoteEnvironmentState,
23} from "../../state/use-remote-environment-registry";
24import { useKnownTerminalSessions } from "../../state/use-terminal-session";
25import { useSelectedThreadDetail } from "../../state/use-thread-detail";
26import { useThreadSelection } from "../../state/use-thread-selection";
27import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
28import {
29 buildTerminalMenuSessions,
30 nextOpenTerminalId,
31 resolveProjectScriptTerminalId,
32} from "../terminal/terminalMenu";
33import {
34 resolvePreferredThreadWorktreePath,
35 stagePendingTerminalLaunch,
36} from "../terminal/terminalLaunchContext";
37import { terminalDebugLog } from "../terminal/terminalDebugLog";
38import { ThreadDetailScreen } from "./ThreadDetailScreen";
39import { ThreadGitControls } from "./ThreadGitControls";
40import { ThreadNavigationDrawer } from "./ThreadNavigationDrawer";
41import { useSelectedThreadCommands } from "../../state/use-selected-thread-commands";
42import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
43import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
44import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
45import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
46import { useThreadComposerState } from "../../state/use-thread-composer-state";
47
48function firstRouteParam(value: string | string[] | undefined): string | null {
49 if (Array.isArray(value)) {
50 return value[0] ?? null;
51 }
52
53 return value ?? null;
54}
55
56function OpeningThreadLoadingScreen() {
57 return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
58}
59
60export function ThreadRouteScreen() {
61 const { isLoadingSavedConnection, environmentStateById, pendingConnectionError } =
62 useRemoteEnvironmentState();
63 const { connectionState, connectionError: aggregateConnectionError } =
64 useRemoteConnectionStatus();
65 const { projects, threads } = useRemoteCatalog();
66 const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
67 useThreadSelection();
68 const selectedThreadDetail = useSelectedThreadDetail();
69 const { selectedThreadCwd } = useSelectedThreadWorktree();
70 const composer = useThreadComposerState();
71 const gitState = useSelectedThreadGitState();
72 const gitActions = useSelectedThreadGitActions();
73 const requests = useSelectedThreadRequests();
74 const commands = useSelectedThreadCommands({
75 refreshSelectedThreadGitStatus: gitActions.refreshSelectedThreadGitStatus,
76 });
77 const router = useRouter();
78 const params = useLocalSearchParams<{
79 environmentId?: string | string[];
80 threadId?: string | string[];
81 }>();
82 const [drawerVisible, setDrawerVisible] = useState(false);
83 const environmentIdRaw = firstRouteParam(params.environmentId);
84 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
85 const threadId = firstRouteParam(params.threadId);
86 const routeEnvironmentRuntime = environmentId
87 ? (environmentStateById[environmentId] ?? null)
88 : null;
89 const routeConnectionState = routeEnvironmentRuntime?.connectionState ?? connectionState;
90 const routeConnectionError =
91 pendingConnectionError ?? routeEnvironmentRuntime?.connectionError ?? aggregateConnectionError;
92
93 /* ─── Native header theming ──────────────────────────────────────── */
94 const isDark = useColorScheme() === "dark";
95 const iconColor = String(useThemeColor("--color-icon"));
96 const foregroundColor = String(useThemeColor("--color-foreground"));
97 const secondaryFg = isDark ? "#a3a3a3" : "#525252";
98
99 /* ─── Git status for native header trigger ───────────────────────── */
100 const gitStatus = useVcsStatus({
101 environmentId: selectedThread?.environmentId ?? null,
102 cwd: selectedThreadCwd,
103 });
104 const knownTerminalSessions = useKnownTerminalSessions({
105 environmentId: selectedThread?.environmentId ?? null,
106 threadId: selectedThread?.id ?? null,
107 });
108 const terminalMenuSessions = useMemo(
109 () =>
110 buildTerminalMenuSessions({
111 knownSessions: knownTerminalSessions,
112 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
113 }),
114 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
115 );
116 const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
117
118 /* ─── Git action progress (for overlay banner) ──────────────────── */
119 const gitActionProgressTarget = useMemo(
120 () => ({
121 environmentId: selectedThread?.environmentId ?? null,
122 cwd: selectedThreadCwd,
123 }),
124 [selectedThread?.environmentId, selectedThreadCwd],
125 );
126 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
127
128 const handleOpenDrawer = useCallback(() => {
129 setDrawerVisible(true);
130 }, []);
131
132 const handleOpenConnectionEditor = useCallback(() => {
133 void router.push("/connections");
134 }, [router]);
135
136 const handleOpenTerminal = useCallback(
137 (nextTerminalId?: string | null) => {
138 terminalDebugLog("terminal-menu:open-existing", {
139 terminalId: nextTerminalId ?? null,
140 hasThread: Boolean(selectedThread),
141 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
142 });
143
144 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
145 return;
146 }
147
148 void router.push(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
149 },
150 [router, selectedThread, selectedThreadProject?.workspaceRoot],
151 );
152
153 const handleOpenNewTerminal = useCallback(() => {
154 terminalDebugLog("terminal-menu:open-new", {
155 hasThread: Boolean(selectedThread),
156 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
157 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
158 });
159
160 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
161 return;
162 }
163
164 const nextId = nextOpenTerminalId({
165 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
166 });
167 void router.push(buildThreadTerminalNavigation(selectedThread, nextId));
168 }, [router, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
169
170 const handleRunProjectScript = useCallback(
171 async (script: ProjectScript) => {
172 terminalDebugLog("project-script:press", {
173 scriptId: script.id,
174 command: script.command,
175 hasThread: Boolean(selectedThread),
176 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
177 });
178
179 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
180 terminalDebugLog("project-script:abort", {
181 scriptId: script.id,
182 reason: "no-thread-or-workspace",
183 });
184 return;
185 }
186
187 const targetTerminalId = resolveProjectScriptTerminalId({
188 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
189 hasRunningTerminal: terminalMenuSessions.some(
190 (session) => session.status === "running" || session.status === "starting",
191 ),
192 });
193 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
194 threadShellWorktreePath: selectedThread.worktreePath ?? null,
195 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
196 });
197 const cwd = projectScriptCwd({
198 project: { cwd: selectedThreadProject.workspaceRoot },
199 worktreePath: preferredWorktreePath,
200 });
201 const env = projectScriptRuntimeEnv({
202 project: { cwd: selectedThreadProject.workspaceRoot },
203 worktreePath: preferredWorktreePath,
204 });
205 stagePendingTerminalLaunch({
206 target: {
207 environmentId: selectedThread.environmentId,
208 threadId: selectedThread.id,
209 terminalId: targetTerminalId,
210 },
211 launch: {
212 cwd,
213 worktreePath: preferredWorktreePath,
214 env,
215 initialInput: `${script.command}\r`,
216 },
217 });
218 terminalDebugLog("project-script:staged", {
219 scriptId: script.id,
220 terminalId: targetTerminalId,
221 cwd,
222 worktreePath: preferredWorktreePath,
223 });
224
225 void router.push(buildThreadTerminalNavigation(selectedThread, targetTerminalId));
226 },
227 [
228 router,
229 selectedThread,
230 selectedThreadDetailWorktreePath,
231 selectedThreadProject,
232 terminalMenuSessions,
233 ],
234 );
235
236 if (!environmentId || !threadId) {
237 return <OpeningThreadLoadingScreen />;
238 }
239
240 if (!selectedThread) {
241 const stillHydrating =
242 isLoadingSavedConnection ||
243 routeConnectionState === "connecting" ||
244 routeConnectionState === "reconnecting";
245
246 if (stillHydrating) {
247 return <OpeningThreadLoadingScreen />;
248 }
249
250 return (
251 <ScrollView
252 contentInsetAdjustmentBehavior="automatic"
253 contentContainerStyle={{
254 flexGrow: 1,
255 justifyContent: "center",
256 paddingHorizontal: 24,
257 paddingVertical: 32,
258 }}
259 className="bg-screen flex-1"
260 >
261 <EmptyState
262 title="Thread unavailable"
263 detail="This thread is not available in the current mobile snapshot."
264 />
265 </ScrollView>
266 );
267 }
268
269 if (!selectedThreadDetail) {
270 return <OpeningThreadLoadingScreen />;
271 }
272
273 const selectedThreadKey = scopedThreadKey(selectedThread.environmentId, selectedThread.id);
274 const serverConfig =
275 routeEnvironmentRuntime?.serverConfig ??
276 pipe(
277 Object.values(environmentStateById),
278 Arr.map((runtime) => runtime.serverConfig),
279 Arr.findFirst((value) => value !== null),
280 Option.getOrNull,
281 );
282
283 const headerSubtitle = [
284 selectedThreadProject?.title ?? null,
285 selectedEnvironmentConnection?.environmentLabel ?? null,
286 ]
287 .filter(Boolean)
288 .join(" · ");
289
290 return (
291 <>
292 <Stack.Screen
293 options={{
294 headerShown: true,
295 headerTransparent: true,
296 headerStyle: { backgroundColor: "transparent" },
297 headerShadowVisible: false,
298 headerTintColor: iconColor,
299 headerBackTitle: "",
300 headerTitle: () => (
301 <Pressable
302 style={{ alignItems: "center", maxWidth: 200 }}
303 onLongPress={() => {
304 // TODO: trigger rename modal
305 }}
306 >
307 <RNText
308 numberOfLines={1}
309 style={{
310 fontFamily: "DMSans_700Bold",
311 fontSize: 18,
312 fontWeight: "900",
313 color: foregroundColor,
314 letterSpacing: -0.4,
315 }}
316 >
317 {selectedThreadDetail.title}
318 </RNText>
319 <RNText
320 numberOfLines={1}
321 style={{
322 fontFamily: "DMSans_700Bold",
323 fontSize: 12,
324 fontWeight: "700",
325 color: secondaryFg,
326 letterSpacing: 0.3,
327 }}
328 >
329 {headerSubtitle}
330 </RNText>
331 </Pressable>
332 ),
333 }}
334 />
335
336 <ThreadGitControls
337 currentBranch={selectedThreadDetail.branch}
338 gitStatus={gitStatus.data}
339 gitOperationLabel={gitState.gitOperationLabel}
340 canOpenTerminal={Boolean(selectedThreadProject?.workspaceRoot)}
341 projectScripts={selectedThreadProject?.scripts ?? []}
342 terminalSessions={terminalMenuSessions}
343 onOpenTerminal={handleOpenTerminal}
344 onOpenNewTerminal={handleOpenNewTerminal}
345 onRunProjectScript={handleRunProjectScript}
346 onPull={gitActions.onPullSelectedThreadBranch}
347 onRunAction={gitActions.onRunSelectedThreadGitAction}
348 />
349
350 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
351
352 <View className="flex-1 bg-screen">
353 <ThreadDetailScreen
354 selectedThread={selectedThreadDetail}
355 screenTone={connectionTone(routeConnectionState)}
356 connectionError={routeConnectionError}
357 httpBaseUrl={selectedEnvironmentConnection?.httpBaseUrl ?? null}
358 bearerToken={selectedEnvironmentConnection?.bearerToken ?? null}
359 selectedThreadFeed={composer.selectedThreadFeed}
360 activeWorkStartedAt={composer.activeWorkStartedAt}
361 activePendingApproval={requests.activePendingApproval}
362 respondingApprovalId={requests.respondingApprovalId}
363 activePendingUserInput={requests.activePendingUserInput}
364 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
365 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
366 respondingUserInputId={requests.respondingUserInputId}
367 draftMessage={composer.draftMessage}
368 draftAttachments={composer.draftAttachments}
369 connectionStateLabel={routeConnectionState}
370 activeThreadBusy={composer.activeThreadBusy}
371 environmentId={selectedThread.environmentId}
372 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
373 selectedThreadQueueCount={composer.selectedThreadQueueCount}
374 onOpenDrawer={handleOpenDrawer}
375 onOpenConnectionEditor={handleOpenConnectionEditor}
376 onChangeDraftMessage={composer.onChangeDraftMessage}
377 onPickDraftImages={composer.onPickDraftImages}
378 onNativePasteImages={composer.onNativePasteImages}
379 onRemoveDraftImage={composer.onRemoveDraftImage}
380 serverConfig={serverConfig}
381 onStopThread={commands.onStopThread}
382 onSendMessage={composer.onSendMessage}
383 onUpdateThreadModelSelection={commands.onUpdateThreadModelSelection}
384 onUpdateThreadRuntimeMode={commands.onUpdateThreadRuntimeMode}
385 onUpdateThreadInteractionMode={commands.onUpdateThreadInteractionMode}
386 onRespondToApproval={requests.onRespondToApproval}
387 onSelectUserInputOption={requests.onSelectUserInputOption}
388 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
389 onSubmitUserInput={requests.onSubmitUserInput}
390 />
391
392 <ThreadNavigationDrawer
393 visible={drawerVisible}
394 projects={projects}
395 threads={threads}
396 selectedThreadKey={selectedThreadKey}
397 onClose={() => setDrawerVisible(false)}
398 onSelectThread={(thread) => {
399 router.replace(buildThreadRoutePath(thread));
400 }}
401 onStartNewTask={() => router.push("/new")}
402 />
403 </View>
404 </>
405 );
406}