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