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

ThreadRouteScreen.tsx

439 lines17.2 KB

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