Open History to see the last commit
1import { ConnectionTraceId } from "./ConnectionTraceId";
2import { useAuth } from "@clerk/expo";
3import { SymbolView } from "../../components/AppSymbol";
4import {
5 connectionStatusText,
6 type EnvironmentConnectionPhase,
7} from "@t3tools/client-runtime/connection";
8import {
9 type EnvironmentId,
10 type EnvironmentMachineKind,
11 type ExecutionEnvironmentDescriptor,
12 resolveEnvironmentMachineKind,
13} from "@t3tools/contracts";
14import { useAtomValue } from "@effect/atom-react";
15import { useCallback, useState } from "react";
16import {
17 ActivityIndicator,
18 Pressable,
19 type NativeSyntheticEvent,
20 type TextLayoutEventData,
21 View,
22} from "react-native";
23
24import { AppText as Text } from "../../components/AppText";
25import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
26import { ThemedSwitch } from "../../components/ThemedSwitch";
27import { cn } from "../../lib/cn";
28import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
29import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
30import { serverEnvironment } from "../../state/server";
31import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
32import { hasCloudPublicConfig } from "../cloud/publicConfig";
33import { ConnectionStatusDot } from "./ConnectionStatusDot";
34import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
35
36interface CloudEnvironmentRowsProps {
37 readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
38 readonly onSetEnvironmentEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
39 /** Long-press on a saved row. The callback owns the confirm. */
40 readonly onRemoveEnvironment: (environmentId: EnvironmentId) => void;
41 readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
42 readonly showcaseSignedIn?: boolean;
43 /**
44 * Hide the "T3 Connect" section title when the host provides its own header.
45 */
46 readonly showHeader?: boolean;
47}
48
49/**
50 * "T3 Connect" section: every environment published to the signed-in account,
51 * with connect switches, availability status, and loading/error
52 * states. Shared between the Settings environments screen and the T3 Connect
53 * onboarding sheet.
54 *
55 * Already-connected relay environments render even without cloud config or a
56 * signed-in account — they are registered on this device and must stay
57 * reachable and removable. Only discovery (the available list, refresh, and
58 * its errors) requires a signed-in session.
59 */
60export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
61 // Showcase captures run without a Clerk publishable key, so `ClerkProvider`
62 // is never mounted and any `useAuth` call throws — the fixture states whether
63 // the rows are signed in instead of asking Clerk.
64 if (props.showcaseSignedIn !== undefined) {
65 return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
66 }
67 // No cloud config means no `ClerkProvider` either, so `useAuth` would throw.
68 if (!hasCloudPublicConfig()) {
69 return <ConnectedOnlyCloudEnvironmentRows {...props} />;
70 }
71 return <SignedInCloudEnvironmentRows {...props} />;
72}
73
74function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
75 const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
76 if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
77 return <CloudEnvironmentRowsContent {...props} />;
78}
79
80function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
81 if (props.connectedCloudEnvironments.length === 0) return null;
82 return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
83}
84
85function CloudEnvironmentRowsContent(
86 props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },
87) {
88 const controller = useConnectionController();
89 const discoveryAvailable = props.discoveryAvailable ?? true;
90 const availableCloudEnvironments = discoveryAvailable
91 ? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)
92 : [];
93 const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
94 const hasCloudRows =
95 props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
96
97 const handleConnectCloudEnvironment = useCallback(
98 (entry: RelayEnvironmentView) => controller.connectRelayEnvironment(entry.environment),
99 [controller],
100 );
101
102 // The relay's health probe carries each server's descriptor, so a machine
103 // can wear its detected glyph before this device ever connects to it.
104 const discoveredDescriptors = new Map(
105 controller.relayEnvironments.flatMap((entry) =>
106 entry.status?.descriptor === undefined
107 ? []
108 : [[entry.environment.environmentId, entry.status.descriptor] as const],
109 ),
110 );
111
112 const handleToggleCloudError = useCallback((environmentId: string) => {
113 setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
114 }, []);
115
116 const showHeader = props.showHeader ?? true;
117
118 return (
119 <View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
120 {showHeader ? (
121 <View className="px-1">
122 <Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
123 </View>
124 ) : null}
125
126 {hasCloudRows ? (
127 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
128 {props.connectedCloudEnvironments.map((environment, index) => (
129 <ConnectedCloudEnvironmentRow
130 key={environment.environmentId}
131 environment={environment}
132 descriptor={discoveredDescriptors.get(environment.environmentId)}
133 borderTop={index !== 0}
134 onSetEnabled={(enabled) =>
135 props.onSetEnvironmentEnabled(environment.environmentId, enabled)
136 }
137 onRemove={() => props.onRemoveEnvironment(environment.environmentId)}
138 errorExpanded={expandedErrorId === environment.environmentId}
139 onToggleError={() => handleToggleCloudError(environment.environmentId)}
140 />
141 ))}
142 {availableCloudEnvironments.map((environment, index) => (
143 <CloudEnvironmentRow
144 key={environment.environment.environmentId}
145 environment={environment}
146 borderTop={props.connectedCloudEnvironments.length > 0 || index !== 0}
147 onConnect={() => handleConnectCloudEnvironment(environment)}
148 errorExpanded={expandedErrorId === environment.environment.environmentId}
149 onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
150 />
151 ))}
152 </View>
153 ) : controller.relayDiscovery.isRefreshing ? (
154 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card p-6">
155 <ActivityIndicator colorClassName={"accent-icon"} />
156 <Text className="text-center text-sm leading-normal text-foreground-muted">
157 Loading linked cloud environments.
158 </Text>
159 </View>
160 ) : controller.relayDiscovery.error ? null : (
161 <View collapsable={false} className="rounded-[24px] bg-card p-5">
162 <Text className="text-sm leading-normal text-foreground-muted">
163 No additional linked cloud environments.
164 </Text>
165 </View>
166 )}
167
168 {/* Rendered alongside any connected rows — a failed discovery must not
169 hide behind an otherwise-healthy list. */}
170 {discoveryAvailable &&
171 controller.relayDiscovery.error &&
172 !controller.relayDiscovery.isRefreshing ? (
173 <View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
174 <Text className="text-base font-t3-bold text-foreground">
175 Could not load T3 Connect environments
176 </Text>
177 <Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
178 {controller.relayDiscovery.errorTraceId ? (
179 <CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
180 ) : null}
181 <Pressable
182 accessibilityRole="button"
183 onPress={() => {
184 void controller.refreshRelayEnvironments();
185 }}
186 className="self-start rounded-full bg-subtle px-3.5 py-2 active:opacity-70"
187 >
188 <Text className="text-xs font-t3-bold text-foreground">Try again</Text>
189 </Pressable>
190 </View>
191 ) : null}
192 </View>
193 );
194}
195
196/**
197 * A saved T3 Connect environment. The switch turns it on or off; off keeps the
198 * registration and cache but drops the connection and hides its errors.
199 * Long-press removes it from this device.
200 */
201function ConnectedCloudEnvironmentRow(props: {
202 readonly environment: ConnectedEnvironmentSummary;
203 /** Discovery's view of the server, for the glyph before the first connection. */
204 readonly descriptor: ExecutionEnvironmentDescriptor | undefined;
205 readonly borderTop: boolean;
206 readonly errorExpanded: boolean;
207 readonly onSetEnabled: (enabled: boolean) => void;
208 readonly onRemove: () => void;
209 readonly onToggleError: () => void;
210}) {
211 const serverConfig = useAtomValue(
212 serverEnvironment.configValueAtom(props.environment.environmentId),
213 );
214 const unsupported = props.environment.connectionState === "unsupported";
215 const enabled = props.environment.isEnabled && !unsupported;
216 // Discovery empties its map on every refresh; hold the last descriptor seen
217 // so the glyph does not blink back to the generic one each time.
218 const [lastDescriptor, setLastDescriptor] = useState(props.descriptor);
219 if (props.descriptor !== undefined && props.descriptor !== lastDescriptor) {
220 setLastDescriptor(props.descriptor);
221 }
222 return (
223 <Pressable
224 accessibilityHint="Long press to remove from this device"
225 onLongPress={props.onRemove}
226 >
227 <CloudEnvironmentRowShell
228 borderTop={props.borderTop}
229 connectionError={enabled || unsupported ? props.environment.connectionError : null}
230 connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}
231 connectionState={enabled || unsupported ? props.environment.connectionState : "available"}
232 errorExpanded={props.errorExpanded}
233 label={props.environment.environmentLabel}
234 machine={resolveEnvironmentMachineKind(
235 serverConfig ?? (lastDescriptor === undefined ? null : { environment: lastDescriptor }),
236 )}
237 onValueChange={props.onSetEnabled}
238 onToggleError={props.onToggleError}
239 disabled={unsupported}
240 {...(enabled || unsupported ? {} : { statusText: "Off" })}
241 value={enabled}
242 />
243 </Pressable>
244 );
245}
246
247function CloudEnvironmentRow(props: {
248 readonly environment: RelayEnvironmentView;
249 readonly borderTop: boolean;
250 readonly errorExpanded: boolean;
251 readonly onConnect: () => void;
252 readonly onToggleError: () => void;
253}) {
254 const presentation = availableCloudEnvironmentPresentation({
255 isStatusPending: props.environment.availability === "checking",
256 status: props.environment.status,
257 statusError: props.environment.error,
258 statusErrorTraceId: props.environment.traceId,
259 });
260
261 return (
262 <CloudEnvironmentRowShell
263 borderTop={props.borderTop}
264 connectionError={presentation.connectionError}
265 connectionErrorTraceId={presentation.connectionErrorTraceId}
266 connectionState={presentation.connectionState}
267 errorExpanded={props.errorExpanded}
268 label={props.environment.environment.label}
269 machine={resolveEnvironmentMachineKind(
270 props.environment.status?.descriptor === undefined
271 ? null
272 : { environment: props.environment.status.descriptor },
273 )}
274 onValueChange={(enabled) => {
275 if (enabled) {
276 props.onConnect();
277 }
278 }}
279 onToggleError={props.onToggleError}
280 disabled={presentation.connectionState === "unsupported"}
281 statusText={presentation.statusText}
282 value={false}
283 />
284 );
285}
286
287function CloudEnvironmentRowShell(props: {
288 readonly borderTop: boolean;
289 readonly connectionError: string | null;
290 readonly connectionErrorTraceId: string | null;
291 readonly connectionState: EnvironmentConnectionPhase;
292 readonly disabled?: boolean;
293 readonly errorExpanded: boolean;
294 readonly label: string;
295 readonly machine: EnvironmentMachineKind;
296 readonly onToggleError: () => void;
297 readonly onValueChange: (enabled: boolean) => void;
298 readonly statusText?: string;
299 readonly value: boolean;
300}) {
301 const isRetrying =
302 props.connectionState === "connecting" || props.connectionState === "reconnecting";
303 const shouldPulse = isRetrying;
304 const statusText =
305 props.statusText ??
306 connectionStatusText({
307 phase: props.connectionState,
308 error: props.connectionError,
309 traceId: props.connectionErrorTraceId,
310 });
311 // Unsupported is a compatibility note, not a failure, so it stays muted.
312 const statusClassName =
313 props.connectionError && props.connectionState !== "unsupported"
314 ? "text-danger-foreground"
315 : "text-foreground-muted";
316 const [errorMeasurement, setErrorMeasurement] = useState<{
317 readonly text: string;
318 readonly lineCount: number;
319 } | null>(null);
320 const errorTraceId = props.connectionErrorTraceId;
321 const measuredErrorText = errorTraceId ? `${statusText} Trace ID: ${errorTraceId}` : statusText;
322 const errorLineCount =
323 errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
324 const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
325 const isErrorExpanded = errorCanExpand && props.errorExpanded;
326 const StatusContainer = errorCanExpand ? Pressable : View;
327 const onMeasuredErrorTextLayout = useCallback(
328 (event: NativeSyntheticEvent<TextLayoutEventData>) => {
329 if (!props.connectionError) {
330 return;
331 }
332 const nextLineCount = event.nativeEvent.lines.length;
333 setErrorMeasurement((currentMeasurement) =>
334 currentMeasurement?.text === measuredErrorText &&
335 currentMeasurement.lineCount === nextLineCount
336 ? currentMeasurement
337 : { text: measuredErrorText, lineCount: nextLineCount },
338 );
339 },
340 [measuredErrorText, props.connectionError],
341 );
342 return (
343 <View
344 collapsable={false}
345 className={cn(
346 "flex-row items-center gap-3 bg-card px-4 py-3.5",
347 props.borderTop && "border-t border-border",
348 )}
349 >
350 <View className="min-w-0 flex-1 gap-0.5">
351 <View className="min-w-0 flex-row items-center gap-2">
352 <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
353 <EnvironmentMachineSymbol
354 kind={props.machine}
355 size={14}
356 tintColorClassName="accent-foreground-muted"
357 />
358 <Text
359 className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
360 numberOfLines={1}
361 >
362 {props.label}
363 </Text>
364 </View>
365 {props.connectionError ? (
366 <Text
367 aria-hidden
368 onTextLayout={onMeasuredErrorTextLayout}
369 className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
370 >
371 {measuredErrorText}
372 </Text>
373 ) : null}
374 <StatusContainer
375 {...(errorCanExpand
376 ? { accessibilityRole: "button" as const, onPress: props.onToggleError }
377 : {})}
378 className="min-w-0 flex-row items-start gap-1"
379 >
380 <Text
381 className={cn("min-w-0 flex-1 text-xs", statusClassName)}
382 numberOfLines={isErrorExpanded ? undefined : 1}
383 >
384 {statusText}
385 {errorTraceId ? (
386 <ConnectionTraceId
387 traceId={errorTraceId}
388 tone={
389 props.connectionError && props.connectionState !== "unsupported"
390 ? "danger"
391 : "muted"
392 }
393 activation="longPress"
394 />
395 ) : null}
396 </Text>
397 {errorCanExpand ? (
398 <SymbolView
399 name="chevron.down"
400 size={10}
401 tintColorClassName={"accent-chevron"}
402 type="monochrome"
403 style={{
404 marginTop: 3,
405 transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
406 }}
407 />
408 ) : null}
409 </StatusContainer>
410 </View>
411 <ThemedSwitch
412 disabled={props.disabled}
413 onValueChange={props.onValueChange}
414 value={props.value}
415 />
416 </View>
417 );
418}
419
420function CopyTraceIdButton(props: { readonly traceId: string }) {
421 return (
422 <Pressable
423 accessibilityRole="button"
424 onPress={() => {
425 copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
426 }}
427 className="self-start flex-row items-center gap-1.5 rounded-full bg-subtle px-3 py-2 active:opacity-70"
428 >
429 <SymbolView
430 name="doc.on.doc"
431 size={12}
432 tintColorClassName={"accent-icon"}
433 type="monochrome"
434 />
435 <Text className="text-xs font-t3-bold text-foreground">Copy trace ID</Text>
436 </Pressable>
437 );
438}