The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 471 lines 18.6 KB
Raw
1 import { T, useGT, useMessages } from "gt-react-native";
2 import { Button } from "../../components/ui/Button";
3 import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
4 import { ConnectionTraceId } from "./ConnectionTraceId";
5 import { useAuth } from "@clerk/expo";
6 import { SymbolView } from "../../components/ui/AppSymbol";
7 import {
8 hasSavedBearerRoute,
9 type EnvironmentConnectionPhase,
10 } from "@t3tools/client-runtime/connection";
11 import {
12 type EnvironmentId,
13 type EnvironmentMachineKind,
14 type ExecutionEnvironmentDescriptor,
15 resolveEnvironmentMachineKind,
16 } from "@t3tools/contracts";
17 import { useAtomValue } from "@effect/atom-react";
18 import { useState } from "react";
19 import { Pressable, type TextLayoutEvent, View } from "react-native";
20
21 import { AppText as Text } from "../../components/ui/AppText";
22 import { EnvironmentMachineSymbol } from "../../components/EnvironmentMachineSymbol";
23 import { ThemedSwitch } from "../../components/ui/ThemedSwitch";
24 import { cn } from "../../lib/cn";
25 import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
26 import type { MarkedText } from "@t3tools/client-runtime/errors";
27 import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
28 import { serverEnvironment } from "../../state/server";
29 import { environmentPresentations } from "../../state/presentation";
30 import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
31 import { hasCloudPublicConfig } from "../cloud/publicConfig";
32 import { ConnectionStatusDot } from "./ConnectionStatusDot";
33 import { useConnectionDiagnosis } from "./ConnectionDiagnosisDetails";
34 import { environmentStatusText } from "./environmentStatusText";
35 import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
36
37 interface CloudEnvironmentRowsProps {
38 readonly connectedCloudEnvironments: ReadonlyArray<ConnectedEnvironmentSummary>;
39 readonly onOpenEnvironment?: (environmentId: EnvironmentId) => void;
40 readonly onSetEnvironmentEnabled: (environmentId: EnvironmentId, enabled: boolean) => void;
41 readonly onRemoveEnvironment: (environmentId: EnvironmentId) => void;
42 readonly showcaseAvailableEnvironments?: ReadonlyArray<RelayEnvironmentView>;
43 readonly showcaseSignedIn?: boolean;
44 readonly showHeader?: boolean;
45 }
46
47 export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
48 // Showcase lacks ClerkProvider; use fixture auth state to avoid a throwing useAuth call.
49 if (props.showcaseSignedIn !== undefined) {
50 return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
51 }
52 // No cloud config means no `ClerkProvider` either, so `useAuth` would throw.
53 if (!hasCloudPublicConfig()) {
54 return <ConnectedOnlyCloudEnvironmentRows {...props} />;
55 }
56 return <SignedInCloudEnvironmentRows {...props} />;
57 }
58
59 function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
60 const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
61 if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
62 return <CloudEnvironmentRowsContent {...props} />;
63 }
64
65 function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
66 if (props.connectedCloudEnvironments.length === 0) return null;
67 return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
68 }
69
70 function CloudEnvironmentRowsContent(
71 props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },
72 ) {
73 const gt = useGT();
74 const controller = useConnectionController();
75 const discoveryAvailable = props.discoveryAvailable ?? true;
76 const availableCloudEnvironments = discoveryAvailable
77 ? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)
78 : [];
79 const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
80 const hasCloudRows =
81 props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
82
83 const handleConnectCloudEnvironment = (entry: RelayEnvironmentView) =>
84 controller.connectRelayEnvironment(entry.environment);
85
86 const discoveredDescriptors = new Map(
87 controller.relayEnvironments.flatMap((entry) =>
88 entry.status?.descriptor === undefined
89 ? []
90 : [[entry.environment.environmentId, entry.status.descriptor] as const],
91 ),
92 );
93
94 const handleToggleCloudError = (environmentId: string) => {
95 setExpandedErrorId((current) => (current === environmentId ? null : environmentId));
96 };
97
98 const showHeader = props.showHeader ?? true;
99
100 return (
101 <View collapsable={false} className={cn("gap-3", showHeader && "mt-5")}>
102 {showHeader ? (
103 <View className="px-1">
104 <Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
105 </View>
106 ) : null}
107
108 {hasCloudRows ? (
109 <View collapsable={false} className="overflow-hidden rounded-[24px] bg-grouped-card">
110 {props.connectedCloudEnvironments.map((environment) => (
111 <ConnectedCloudEnvironmentRow
112 key={environment.environmentId}
113 environment={environment}
114 descriptor={discoveredDescriptors.get(environment.environmentId)}
115 onSetEnabled={(enabled) =>
116 props.onSetEnvironmentEnabled(environment.environmentId, enabled)
117 }
118 onRemove={() => props.onRemoveEnvironment(environment.environmentId)}
119 onOpen={
120 props.onOpenEnvironment
121 ? () => props.onOpenEnvironment?.(environment.environmentId)
122 : undefined
123 }
124 errorExpanded={expandedErrorId === environment.environmentId}
125 onToggleError={() => handleToggleCloudError(environment.environmentId)}
126 />
127 ))}
128 {availableCloudEnvironments.map((environment) => (
129 <CloudEnvironmentRow
130 key={environment.environment.environmentId}
131 environment={environment}
132 showChevron={props.onOpenEnvironment !== undefined}
133 onConnect={() => handleConnectCloudEnvironment(environment)}
134 errorExpanded={expandedErrorId === environment.environment.environmentId}
135 onToggleError={() => handleToggleCloudError(environment.environment.environmentId)}
136 />
137 ))}
138 </View>
139 ) : controller.relayDiscovery.isRefreshing ? (
140 <View collapsable={false} className="items-center gap-3 rounded-[24px] bg-grouped-card p-6">
141 <AppActivityIndicator colorClassName={"accent-icon"} />
142 <Text className="text-center text-sm leading-normal text-foreground-muted">
143 <T>Loading linked cloud environments.</T>
144 </Text>
145 </View>
146 ) : controller.relayDiscovery.error ? null : (
147 <View collapsable={false} className="rounded-[24px] bg-grouped-card p-5">
148 <Text className="text-sm leading-normal text-foreground-muted">
149 <T>No additional linked cloud environments.</T>
150 </Text>
151 </View>
152 )}
153
154 {discoveryAvailable &&
155 controller.relayDiscovery.error &&
156 !controller.relayDiscovery.isRefreshing ? (
157 <View collapsable={false} className="gap-3 rounded-[24px] bg-grouped-card p-5">
158 <Text className="text-base font-t3-bold text-foreground">
159 {gt("Could not load {product} environments", { product: "T3 Connect" })}
160 </Text>
161 <Text className="text-sm text-foreground-muted">{controller.relayDiscovery.error}</Text>
162 {controller.relayDiscovery.errorTraceId ? (
163 <CopyTraceIdButton traceId={controller.relayDiscovery.errorTraceId} />
164 ) : null}
165 <Button
166 label={gt("Try again")}
167 tone="secondary"
168 onPress={() => {
169 void controller.refreshRelayEnvironments();
170 }}
171 />
172 </View>
173 ) : null}
174 </View>
175 );
176 }
177
178 function ConnectedCloudEnvironmentRow(props: {
179 readonly environment: ConnectedEnvironmentSummary;
180 readonly descriptor: ExecutionEnvironmentDescriptor | undefined;
181 readonly errorExpanded: boolean;
182 readonly onSetEnabled: (enabled: boolean) => void;
183 readonly onRemove: () => void;
184 readonly onOpen?: (() => void) | undefined;
185 readonly onToggleError: () => void;
186 }) {
187 const gt = useGT();
188 const serverConfig = useAtomValue(
189 serverEnvironment.configValueAtom(props.environment.environmentId),
190 );
191 const unsupported = props.environment.connectionState === "unsupported";
192 const presentation = useAtomValue(
193 environmentPresentations.presentationAtom(props.environment.environmentId),
194 );
195 const canRetry = presentation !== null && hasSavedBearerRoute(presentation.entry);
196 const enabled = props.environment.isEnabled && !unsupported;
197 const { diagnosis } = useConnectionDiagnosis(props.environment.environmentId, presentation);
198 const [lastDescriptor, setLastDescriptor] = useState(props.descriptor);
199 if (props.descriptor !== undefined && props.descriptor !== lastDescriptor) {
200 setLastDescriptor(props.descriptor);
201 }
202 return (
203 <CloudEnvironmentRowShell
204 opensDetails={props.onOpen !== undefined}
205 onOpen={props.onOpen}
206 onRemove={props.onRemove}
207 connectionError={enabled || unsupported ? props.environment.connectionError : null}
208 {...((enabled || unsupported) && props.environment.i18nConnectionError !== undefined
209 ? { i18nConnectionError: props.environment.i18nConnectionError }
210 : {})}
211 connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}
212 connectionState={enabled || unsupported ? props.environment.connectionState : "available"}
213 awaitingApproval={enabled && presentation?.connection.awaitingApproval === true}
214 errorExpanded={props.errorExpanded}
215 label={props.environment.environmentLabel}
216 machine={resolveEnvironmentMachineKind(
217 serverConfig ?? (lastDescriptor === undefined ? null : { environment: lastDescriptor }),
218 )}
219 onValueChange={props.onSetEnabled}
220 onToggleError={props.onToggleError}
221 disabled={unsupported && !canRetry}
222 {...(enabled || unsupported
223 ? diagnosis
224 ? { statusText: diagnosis.headline }
225 : {}
226 : { statusText: gt("Off", { $context: "environment is switched off" }) })}
227 value={enabled}
228 />
229 );
230 }
231
232 function CloudEnvironmentRow(props: {
233 readonly environment: RelayEnvironmentView;
234 readonly showChevron: boolean;
235 readonly errorExpanded: boolean;
236 readonly onConnect: () => void;
237 readonly onToggleError: () => void;
238 }) {
239 const m = useMessages();
240 const presentation = availableCloudEnvironmentPresentation(
241 {
242 isStatusPending: props.environment.availability === "checking",
243 status: props.environment.status,
244 statusError: props.environment.error,
245 statusErrorTraceId: props.environment.traceId,
246 },
247 m,
248 );
249
250 return (
251 <CloudEnvironmentRowShell
252 showChevron={props.showChevron}
253 connectionError={presentation.connectionError}
254 connectionErrorTraceId={presentation.connectionErrorTraceId}
255 connectionState={presentation.connectionState}
256 errorExpanded={props.errorExpanded}
257 label={props.environment.environment.label}
258 machine={resolveEnvironmentMachineKind(
259 props.environment.status?.descriptor === undefined
260 ? null
261 : { environment: props.environment.status.descriptor },
262 )}
263 onValueChange={(enabled) => {
264 if (enabled) {
265 props.onConnect();
266 }
267 }}
268 onToggleError={props.onToggleError}
269 disabled={presentation.connectionState === "unsupported"}
270 statusText={presentation.statusText}
271 value={false}
272 />
273 );
274 }
275
276 function CloudEnvironmentRowShell(props: {
277 readonly showChevron?: boolean;
278 readonly opensDetails?: boolean;
279 readonly onOpen?: (() => void) | undefined;
280 readonly onRemove?: (() => void) | undefined;
281 readonly connectionError: string | null;
282 readonly i18nConnectionError?: MarkedText;
283 readonly connectionErrorTraceId: string | null;
284 readonly connectionState: EnvironmentConnectionPhase;
285 /** Waiting on the host to approve this device: say so plainly, not as a failure. */
286 readonly awaitingApproval?: boolean;
287 readonly disabled?: boolean;
288 readonly errorExpanded: boolean;
289 readonly label: string;
290 readonly machine: EnvironmentMachineKind;
291 readonly onToggleError: () => void;
292 readonly onValueChange: (enabled: boolean) => void;
293 readonly statusText?: string;
294 readonly value: boolean;
295 }) {
296 const gt = useGT();
297 const m = useMessages();
298 const isRetrying =
299 props.connectionState === "connecting" || props.connectionState === "reconnecting";
300 const shouldPulse = isRetrying;
301 const statusText =
302 props.statusText ??
303 environmentStatusText(
304 {
305 phase: props.connectionState,
306 error: props.connectionError,
307 ...(props.i18nConnectionError === undefined
308 ? {}
309 : { i18nError: props.i18nConnectionError }),
310 traceId: props.connectionErrorTraceId,
311 ...(props.awaitingApproval ? { awaitingApproval: true as const } : {}),
312 },
313 m,
314 );
315 const statusClassName =
316 props.connectionError && props.connectionState !== "unsupported" && !props.awaitingApproval
317 ? "text-danger-foreground"
318 : "text-foreground-muted";
319 const [errorMeasurement, setErrorMeasurement] = useState<{
320 readonly text: string;
321 readonly lineCount: number;
322 } | null>(null);
323 const errorTraceId = props.connectionErrorTraceId;
324 const measuredErrorText = errorTraceId
325 ? `${statusText} ${gt("Trace ID:")} ${errorTraceId}`
326 : statusText;
327 const errorLineCount =
328 errorMeasurement?.text === measuredErrorText ? errorMeasurement.lineCount : 0;
329 const errorCanExpand = props.connectionError !== null && errorLineCount > 1;
330 const isErrorExpanded = errorCanExpand && props.errorExpanded;
331 const StatusContainer = errorCanExpand ? Pressable : View;
332 const ContentContainer = props.onOpen || props.onRemove ? Pressable : View;
333 const ChevronContainer = props.onOpen || props.onRemove ? Pressable : View;
334 const onMeasuredErrorTextLayout = (event: TextLayoutEvent) => {
335 if (!props.connectionError) {
336 return;
337 }
338 const nextLineCount = event.nativeEvent.lines.length;
339 setErrorMeasurement((currentMeasurement) =>
340 currentMeasurement?.text === measuredErrorText &&
341 currentMeasurement.lineCount === nextLineCount
342 ? currentMeasurement
343 : { text: measuredErrorText, lineCount: nextLineCount },
344 );
345 };
346 return (
347 <View collapsable={false} className="flex-row items-center gap-3 bg-grouped-card px-4 py-3.5">
348 <ContentContainer
349 className="min-w-0 flex-1 gap-0.5"
350 accessibilityHint={props.onRemove ? gt("Long press to remove from this device") : undefined}
351 accessibilityRole={props.onOpen ? "button" : undefined}
352 accessibilityLabel={
353 props.onOpen
354 ? gt("Manage {environment}", { environment: props.label })
355 : props.onRemove
356 ? gt("Remove {environment} from this device", { environment: props.label })
357 : undefined
358 }
359 onPress={props.onOpen}
360 onLongPress={props.onRemove}
361 >
362 <View className="min-w-0 flex-row items-center gap-2">
363 <ConnectionStatusDot state={props.connectionState} pulse={shouldPulse} size={7} />
364 <EnvironmentMachineSymbol
365 kind={props.machine}
366 size={14}
367 tintColorClassName="accent-foreground-muted"
368 />
369 <Text
370 className="min-w-0 flex-shrink text-base font-t3-bold leading-snug text-foreground"
371 numberOfLines={1}
372 >
373 {props.label}
374 </Text>
375 </View>
376 {props.connectionError ? (
377 <Text
378 aria-hidden
379 onTextLayout={onMeasuredErrorTextLayout}
380 className={cn("absolute inset-x-0 -z-[1] text-xs opacity-0", statusClassName)}
381 >
382 {measuredErrorText}
383 </Text>
384 ) : null}
385 <StatusContainer
386 {...(errorCanExpand
387 ? { accessibilityRole: "button" as const, onPress: props.onToggleError }
388 : {})}
389 className="min-w-0 flex-row items-start gap-1"
390 >
391 <Text
392 className={cn("min-w-0 flex-1 text-xs", statusClassName)}
393 numberOfLines={isErrorExpanded ? undefined : 1}
394 >
395 {statusText}
396 {errorTraceId ? (
397 <ConnectionTraceId
398 traceId={errorTraceId}
399 tone={
400 props.connectionError && props.connectionState !== "unsupported"
401 ? "danger"
402 : "muted"
403 }
404 activation="longPress"
405 />
406 ) : null}
407 </Text>
408 {errorCanExpand ? (
409 <SymbolView
410 name="chevron.down"
411 size={10}
412 tintColorClassName={"accent-chevron"}
413 type="monochrome"
414 style={{
415 marginTop: 3,
416 transform: [{ rotate: isErrorExpanded ? "180deg" : "0deg" }],
417 }}
418 />
419 ) : null}
420 </StatusContainer>
421 </ContentContainer>
422 <ThemedSwitch
423 accessibilityLabel={gt("Enable {environment}", { environment: props.label })}
424 style={{ alignSelf: "center" }}
425 disabled={props.disabled}
426 onValueChange={props.onValueChange}
427 value={props.value}
428 />
429 {props.opensDetails || props.showChevron ? (
430 <ChevronContainer
431 accessibilityRole={props.onOpen ? "button" : undefined}
432 accessibilityLabel={
433 props.onOpen
434 ? gt("Manage {environment}", { environment: props.label })
435 : props.onRemove
436 ? gt("Remove {environment} from this device", { environment: props.label })
437 : undefined
438 }
439 accessibilityHint={
440 props.onRemove ? gt("Long press to remove from this device") : undefined
441 }
442 onPress={props.onOpen}
443 onLongPress={props.onRemove}
444 style={{
445 opacity: props.opensDetails ? 1 : 0.4,
446 minWidth: 44,
447 minHeight: 44,
448 alignItems: "center",
449 justifyContent: "center",
450 }}
451 >
452 <SymbolView name="chevron.right" size={12} tintColorClassName="accent-icon-subtle" />
453 </ChevronContainer>
454 ) : null}
455 </View>
456 );
457 }
458
459 function CopyTraceIdButton(props: { readonly traceId: string }) {
460 const gt = useGT();
461 return (
462 <Button
463 label={gt("Copy trace ID")}
464 tone="secondary"
465 onPress={() => {
466 copyTextWithHaptic(props.traceId, { target: "connection-trace-id" });
467 }}
468 icon="doc.on.doc"
469 />
470 );
471 }