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

ThreadRouteScreen.tsx

418 lines16.1 KB

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