Open History to see the last commit
1import { QueryClient, QueryClientProvider, useQuery, useQueryClient } from "@tanstack/react-query";
2import type { OrchestrationEvent, OrchestrationReadModel, WsWelcomePayload } from "@t3tools/contracts";
3import { StatusBar } from "expo-status-bar";
4import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5import {
6 ActivityIndicator,
7 Pressable,
8 SafeAreaView,
9 ScrollView,
10 Text,
11 TextInput,
12 View,
13} from "react-native";
14
15import {
16 createBackendProfileId,
17 loadBackendState,
18 normalizeBackendInput,
19 saveBackendProfiles,
20 setActiveBackendProfileId,
21 type BackendProfile,
22} from "./backendProfiles";
23import { T3MobileClient } from "./t3MobileClient";
24import type { TransportStatus } from "./wsTransport";
25
26const queryClient = new QueryClient({
27 defaultOptions: {
28 queries: {
29 staleTime: 5_000,
30 retry: 1,
31 },
32 },
33});
34
35type ThemeButtonVariant = "primary" | "ghost" | "danger";
36
37function ThemeButton(props: {
38 readonly label: string;
39 readonly onPress: () => void;
40 readonly disabled?: boolean;
41 readonly variant?: ThemeButtonVariant;
42}) {
43 const { label, onPress, disabled = false, variant = "primary" } = props;
44 const backgroundClassName =
45 variant === "primary"
46 ? "bg-blue-600"
47 : variant === "danger"
48 ? "bg-red-600"
49 : "bg-slate-200";
50 const textClassName = variant === "ghost" ? "text-slate-700" : "text-white";
51
52 return (
53 <Pressable
54 className={`h-11 items-center justify-center rounded-xl px-4 ${backgroundClassName} ${disabled ? "opacity-50" : "opacity-100"}`}
55 disabled={disabled}
56 onPress={onPress}
57 >
58 <Text className={`text-sm font-semibold ${textClassName}`}>{label}</Text>
59 </Pressable>
60 );
61}
62
63function SectionCard(props: { readonly title: string; readonly children: React.ReactNode }) {
64 return (
65 <View className="gap-3 rounded-2xl border border-slate-200 bg-white p-4">
66 <Text className="text-xs font-semibold uppercase tracking-[1.5px] text-slate-500">{props.title}</Text>
67 {props.children}
68 </View>
69 );
70}
71
72function statusLabel(status: TransportStatus): string {
73 if (status.state === "connected") return "Connected";
74 if (status.state === "connecting") return "Connecting";
75 if (status.state === "error") return "Connection Error";
76 return "Disconnected";
77}
78
79function statusClassName(status: TransportStatus): string {
80 if (status.state === "connected") return "bg-emerald-100 text-emerald-700";
81 if (status.state === "connecting") return "bg-amber-100 text-amber-700";
82 if (status.state === "error") return "bg-red-100 text-red-700";
83 return "bg-slate-200 text-slate-700";
84}
85
86function formatDate(iso: string | null | undefined): string {
87 if (!iso) return "-";
88
89 const value = new Date(iso);
90 if (Number.isNaN(value.getTime())) return "-";
91 return value.toLocaleString();
92}
93
94function formatEventType(event: OrchestrationEvent): string {
95 const eventRecord = event as Record<string, unknown>;
96 if (typeof eventRecord.type === "string") return eventRecord.type;
97 return "event";
98}
99
100function formatEventTimestamp(event: OrchestrationEvent): string {
101 const eventRecord = event as Record<string, unknown>;
102 if (typeof eventRecord.createdAt === "string") return formatDate(eventRecord.createdAt);
103 return "";
104}
105
106function eventKey(event: OrchestrationEvent): string {
107 const eventRecord = event as Record<string, unknown>;
108 if (typeof eventRecord.eventId === "string") return eventRecord.eventId;
109 if (typeof eventRecord.id === "string") return eventRecord.id;
110 return `${formatEventType(event)}-${formatEventTimestamp(event)}`;
111}
112
113function AppContent() {
114 const queryClient = useQueryClient();
115 const cleanupRef = useRef<(() => void) | null>(null);
116
117 const [profiles, setProfiles] = useState<BackendProfile[]>([]);
118 const [activeProfileId, setActiveProfileId] = useState<string | null>(null);
119 const [initialActiveProfileId, setInitialActiveProfileId] = useState<string | null>(null);
120 const [loadingProfiles, setLoadingProfiles] = useState(true);
121
122 const [wsUrlInput, setWsUrlInput] = useState("");
123 const [authTokenInput, setAuthTokenInput] = useState("");
124
125 const [client, setClient] = useState<T3MobileClient | null>(null);
126 const [connectionStatus, setConnectionStatus] = useState<TransportStatus>({
127 state: "disconnected",
128 });
129 const [welcome, setWelcome] = useState<WsWelcomePayload | null>(null);
130 const [recentEvents, setRecentEvents] = useState<OrchestrationEvent[]>([]);
131 const [uiError, setUiError] = useState<string | null>(null);
132
133 const activeProfile = useMemo(
134 () => profiles.find((profile) => profile.id === activeProfileId) ?? null,
135 [activeProfileId, profiles],
136 );
137
138 const snapshotQuery = useQuery<OrchestrationReadModel>({
139 queryKey: ["orchestration.snapshot", activeProfileId],
140 queryFn: async () => {
141 if (!client) {
142 throw new Error("No active backend connection.");
143 }
144 return client.getSnapshot();
145 },
146 enabled: client !== null && activeProfileId !== null,
147 refetchInterval: connectionStatus.state === "connected" ? 10_000 : false,
148 });
149
150 const disconnectFromBackend = useCallback(async () => {
151 cleanupRef.current?.();
152 cleanupRef.current = null;
153
154 setClient(null);
155 setActiveProfileId(null);
156 setWelcome(null);
157 setRecentEvents([]);
158 setConnectionStatus({ state: "disconnected" });
159
160 await setActiveBackendProfileId(null);
161 queryClient.removeQueries({ queryKey: ["orchestration.snapshot"] });
162 }, [queryClient]);
163
164 const connectToProfile = useCallback(
165 async (profile: BackendProfile) => {
166 setUiError(null);
167 cleanupRef.current?.();
168 cleanupRef.current = null;
169
170 setWelcome(null);
171 setRecentEvents([]);
172 setConnectionStatus({ state: "connecting" });
173
174 const nextClient = new T3MobileClient({
175 profile,
176 onStatus: (status) => {
177 setConnectionStatus(status);
178 },
179 });
180
181 const unsubscribeWelcome = nextClient.onWelcome((payload) => {
182 setWelcome(payload);
183 });
184
185 const unsubscribeDomainEvents = nextClient.onDomainEvent((event) => {
186 setRecentEvents((current) => [event, ...current].slice(0, 60));
187 void queryClient.invalidateQueries({ queryKey: ["orchestration.snapshot", profile.id] });
188 });
189
190 cleanupRef.current = () => {
191 unsubscribeWelcome();
192 unsubscribeDomainEvents();
193 nextClient.dispose();
194 };
195
196 setClient(nextClient);
197 setActiveProfileId(profile.id);
198 await setActiveBackendProfileId(profile.id);
199
200 const now = new Date().toISOString();
201 setProfiles((current) => {
202 const nextProfiles = current.map((candidate) =>
203 candidate.id === profile.id ? { ...candidate, lastConnectedAt: now } : candidate,
204 );
205 void saveBackendProfiles(nextProfiles);
206 return nextProfiles;
207 });
208
209 void queryClient.invalidateQueries({ queryKey: ["orchestration.snapshot", profile.id] });
210 },
211 [queryClient],
212 );
213
214 const saveAndConnectProfile = useCallback(async () => {
215 try {
216 setUiError(null);
217 const normalized = normalizeBackendInput(wsUrlInput, authTokenInput);
218 const now = new Date().toISOString();
219
220 const existing = profiles.find(
221 (profile) => profile.url === normalized.url && (profile.authToken ?? "") === (normalized.authToken ?? ""),
222 );
223
224 const profile: BackendProfile = existing
225 ? {
226 ...existing,
227 name: normalized.name,
228 }
229 : {
230 id: createBackendProfileId(),
231 name: normalized.name,
232 url: normalized.url,
233 authToken: normalized.authToken,
234 createdAt: now,
235 lastConnectedAt: null,
236 };
237
238 const nextProfiles = existing
239 ? profiles.map((candidate) => (candidate.id === existing.id ? profile : candidate))
240 : [profile, ...profiles];
241
242 setProfiles(nextProfiles);
243 await saveBackendProfiles(nextProfiles);
244 await connectToProfile(profile);
245
246 setWsUrlInput("");
247 setAuthTokenInput("");
248 } catch (error) {
249 setUiError(error instanceof Error ? error.message : "Unable to save backend profile.");
250 }
251 }, [authTokenInput, connectToProfile, profiles, wsUrlInput]);
252
253 const removeProfile = useCallback(
254 async (profileId: string) => {
255 const nextProfiles = profiles.filter((profile) => profile.id !== profileId);
256 setProfiles(nextProfiles);
257 await saveBackendProfiles(nextProfiles);
258
259 if (activeProfileId === profileId) {
260 await disconnectFromBackend();
261 }
262
263 if (initialActiveProfileId === profileId) {
264 setInitialActiveProfileId(null);
265 }
266 },
267 [activeProfileId, disconnectFromBackend, initialActiveProfileId, profiles],
268 );
269
270 useEffect(() => {
271 let cancelled = false;
272
273 void (async () => {
274 const state = await loadBackendState();
275 if (cancelled) return;
276
277 setProfiles(state.profiles);
278 setInitialActiveProfileId(state.activeProfileId);
279 setLoadingProfiles(false);
280 })();
281
282 return () => {
283 cancelled = true;
284 cleanupRef.current?.();
285 cleanupRef.current = null;
286 };
287 }, []);
288
289 useEffect(() => {
290 if (loadingProfiles || !initialActiveProfileId) return;
291
292 const profile = profiles.find((candidate) => candidate.id === initialActiveProfileId);
293 setInitialActiveProfileId(null);
294
295 if (profile) {
296 void connectToProfile(profile);
297 }
298 }, [connectToProfile, initialActiveProfileId, loadingProfiles, profiles]);
299
300 const snapshotError = snapshotQuery.error instanceof Error ? snapshotQuery.error.message : null;
301 const snapshot = snapshotQuery.data;
302
303 if (loadingProfiles) {
304 return (
305 <SafeAreaView className="flex-1 items-center justify-center bg-slate-100">
306 <ActivityIndicator size="small" color="#334155" />
307 <Text className="mt-3 text-sm text-slate-600">Loading servers...</Text>
308 </SafeAreaView>
309 );
310 }
311
312 if (client && activeProfile) {
313 return (
314 <SafeAreaView className="flex-1 bg-slate-100">
315 <StatusBar />
316 <ScrollView contentContainerStyle={{ padding: 16, gap: 14, paddingBottom: 40 }}>
317 <View className="rounded-2xl border border-slate-200 bg-white p-4">
318 <View className="flex-row items-start justify-between">
319 <View className="max-w-[75%] gap-1">
320 <Text className="text-xl font-semibold text-slate-900">T3 Code Mobile</Text>
321 <Text className="text-xs text-slate-600">{activeProfile.name}</Text>
322 <Text className="text-[11px] text-slate-500">{activeProfile.url}</Text>
323 </View>
324 <View className={`rounded-full px-3 py-1 ${statusClassName(connectionStatus)}`}>
325 <Text className="text-xs font-semibold">{statusLabel(connectionStatus)}</Text>
326 </View>
327 </View>
328 {connectionStatus.detail ? (
329 <Text className="mt-3 text-[11px] text-slate-500">{connectionStatus.detail}</Text>
330 ) : null}
331 <View className="mt-4 flex-row gap-2">
332 <View className="flex-1">
333 <ThemeButton
334 label={snapshotQuery.isFetching ? "Refreshing..." : "Refresh Snapshot"}
335 onPress={() => {
336 void snapshotQuery.refetch();
337 }}
338 disabled={snapshotQuery.isFetching}
339 />
340 </View>
341 <View className="flex-1">
342 <ThemeButton label="Switch Server" variant="ghost" onPress={() => void disconnectFromBackend()} />
343 </View>
344 </View>
345 </View>
346
347 <SectionCard title="Session">
348 <Text className="text-sm text-slate-700">Project: {welcome?.projectName ?? "Waiting for welcome event..."}</Text>
349 <Text className="text-sm text-slate-700">Workspace: {welcome?.cwd ?? "-"}</Text>
350 <Text className="text-sm text-slate-700">
351 Bootstrap Thread: {welcome?.bootstrapThreadId ?? "not provided"}
352 </Text>
353 </SectionCard>
354
355 <SectionCard title="Orchestration Snapshot">
356 {snapshotQuery.isLoading ? (
357 <View className="items-start gap-2">
358 <ActivityIndicator size="small" color="#334155" />
359 <Text className="text-sm text-slate-600">Loading snapshot...</Text>
360 </View>
361 ) : snapshotError ? (
362 <Text className="text-sm text-red-700">{snapshotError}</Text>
363 ) : snapshot ? (
364 <View className="gap-2">
365 <Text className="text-sm text-slate-700">Projects: {snapshot.projects.length}</Text>
366 <Text className="text-sm text-slate-700">Threads: {snapshot.threads.length}</Text>
367 <Text className="text-sm text-slate-700">Updated: {formatDate(snapshot.updatedAt)}</Text>
368 <View className="mt-1 gap-2 rounded-xl border border-slate-200 bg-slate-50 p-3">
369 {snapshot.projects.slice(0, 4).map((project) => (
370 <View key={project.id} className="gap-0.5">
371 <Text className="text-sm font-medium text-slate-800">{project.title}</Text>
372 <Text className="text-[11px] text-slate-500">{project.workspaceRoot}</Text>
373 </View>
374 ))}
375 {snapshot.projects.length === 0 ? (
376 <Text className="text-sm text-slate-500">No projects available.</Text>
377 ) : null}
378 </View>
379 </View>
380 ) : (
381 <Text className="text-sm text-slate-600">No snapshot data available.</Text>
382 )}
383 </SectionCard>
384
385 <SectionCard title="Recent Domain Events">
386 {recentEvents.length === 0 ? (
387 <Text className="text-sm text-slate-500">No events received yet.</Text>
388 ) : (
389 <View className="gap-2">
390 {recentEvents.slice(0, 25).map((event) => (
391 <View
392 key={eventKey(event)}
393 className="rounded-lg border border-slate-200 bg-slate-50 px-3 py-2"
394 >
395 <Text className="text-xs font-semibold uppercase text-slate-700">{formatEventType(event)}</Text>
396 <Text className="mt-1 text-[11px] text-slate-500">{formatEventTimestamp(event)}</Text>
397 </View>
398 ))}
399 </View>
400 )}
401 </SectionCard>
402 </ScrollView>
403 </SafeAreaView>
404 );
405 }
406
407 return (
408 <SafeAreaView className="flex-1 bg-slate-100">
409 <StatusBar />
410 <ScrollView contentContainerStyle={{ padding: 16, gap: 14, paddingBottom: 40 }}>
411 <View className="rounded-2xl border border-slate-200 bg-white p-4">
412 <Text className="text-2xl font-semibold text-slate-900">Connect T3 Code</Text>
413 <Text className="mt-2 text-sm leading-5 text-slate-600">
414 Enter your websocket server URL and optional auth token. Saved servers appear below.
415 </Text>
416
417 <View className="mt-4 gap-3">
418 <View className="gap-1.5">
419 <Text className="text-xs font-semibold uppercase tracking-[1.4px] text-slate-500">Server URL</Text>
420 <TextInput
421 className="h-11 rounded-xl border border-slate-300 bg-white px-3 text-sm text-slate-900"
422 autoCapitalize="none"
423 autoCorrect={false}
424 keyboardType="url"
425 placeholder="ws://localhost:3773"
426 placeholderTextColor="#94a3b8"
427 value={wsUrlInput}
428 onChangeText={setWsUrlInput}
429 />
430 </View>
431 <View className="gap-1.5">
432 <Text className="text-xs font-semibold uppercase tracking-[1.4px] text-slate-500">Auth Token (Optional)</Text>
433 <TextInput
434 className="h-11 rounded-xl border border-slate-300 bg-white px-3 text-sm text-slate-900"
435 autoCapitalize="none"
436 autoCorrect={false}
437 placeholder="token"
438 placeholderTextColor="#94a3b8"
439 value={authTokenInput}
440 onChangeText={setAuthTokenInput}
441 />
442 </View>
443 <ThemeButton label="Save and Connect" onPress={() => void saveAndConnectProfile()} />
444 </View>
445 {uiError ? <Text className="mt-3 text-sm text-red-700">{uiError}</Text> : null}
446 </View>
447
448 <SectionCard title="Saved Backends">
449 {profiles.length === 0 ? (
450 <Text className="text-sm text-slate-500">No servers saved yet.</Text>
451 ) : (
452 <View className="gap-3">
453 {profiles.map((profile) => (
454 <View key={profile.id} className="gap-3 rounded-xl border border-slate-200 bg-slate-50 p-3">
455 <View className="gap-1">
456 <Text className="text-sm font-semibold text-slate-900">{profile.name}</Text>
457 <Text className="text-[11px] text-slate-600">{profile.url}</Text>
458 <Text className="text-[11px] text-slate-500">
459 Token: {profile.authToken ? "configured" : "none"}
460 </Text>
461 <Text className="text-[11px] text-slate-500">
462 Last connected: {formatDate(profile.lastConnectedAt)}
463 </Text>
464 </View>
465 <View className="flex-row gap-2">
466 <View className="flex-1">
467 <ThemeButton
468 label="Connect"
469 onPress={() => {
470 void connectToProfile(profile);
471 }}
472 />
473 </View>
474 <View className="flex-1">
475 <ThemeButton
476 label="Delete"
477 variant="danger"
478 onPress={() => {
479 void removeProfile(profile.id);
480 }}
481 />
482 </View>
483 </View>
484 </View>
485 ))}
486 </View>
487 )}
488 </SectionCard>
489 </ScrollView>
490 </SafeAreaView>
491 );
492}
493
494export default function App() {
495 return (
496 <QueryClientProvider client={queryClient}>
497 <AppContent />
498 </QueryClientProvider>
499 );
500}