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

use-remote-environment-registry.ts

222 lines8.0 KB

1import * as Dialog from "../components/ui/Dialog";
2import { useAtomValue } from "@effect/atom-react";
3import { useNavigation } from "@react-navigation/native";
4import type { EnvironmentId } from "@t3tools/contracts";
5import * as Cause from "effect/Cause";
6import { AsyncResult, Atom } from "effect/reactivity";
7import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
8​
9import { hasCloudPublicConfig } from "../features/cloud/publicConfig";
10import { useConnectionController } from "../features/connection/useConnectionController";
11import { environmentPresentations } from "./presentation";
12import { useWorkspaceConnectionState, useWorkspaceEnvironments } from "./workspace";
13import type { SavedRemoteConnection } from "../lib/connection";
14import { appAtomRegistry } from "./atom-registry";
15import type { ConnectedEnvironmentSummary, EnvironmentRuntimeState } from "./remote-runtime-types";
16import { environmentSession } from "./session";
17import { environmentCatalog } from "../connection/catalog";
18import { createRemoteEnvironmentProjectionAtoms } from "./remote-environment-projections";
19import { serverEnvironment } from "./server";
20import { connectPairingUrl as connectPairingUrlCommand } from "../connection/onboarding";
21​
22const connectionPairingUrlAtom = Atom.make("").pipe(
23 Atom.keepAlive,
24 Atom.withLabel("mobile:connection-pairing-url"),
25);
26​
27const pendingConnectionErrorAtom = Atom.make<string | null>(null).pipe(
28 Atom.keepAlive,
29 Atom.withLabel("mobile:pending-connection-error"),
30);
31​
32export function setPendingConnectionError(message: string | null): void {
33 appAtomRegistry.set(pendingConnectionErrorAtom, message);
35​
36export interface PairingOutcome {
37 readonly ok: boolean;
38 /** Shown beside the pairing form; null when the failure got its own dialog. */
39 readonly error: string | null;
41​
42/** Pairs with the environment behind a pairing link and saves it. */
43export async function pairEnvironment(
44 pairingUrl: string,
45 expectedEnvironmentId?: EnvironmentId,
46): Promise<PairingOutcome> {
47 const result = await runAtomCommand(
48 appAtomRegistry,
49 connectPairingUrlCommand,
50 { pairingUrl, ...(expectedEnvironmentId === undefined ? {} : { expectedEnvironmentId }) },
51 { reportFailure: false },
52 );
53 if (AsyncResult.isSuccess(result)) {
54 appAtomRegistry.set(connectionPairingUrlAtom, "");
55 return { ok: true, error: null };
56 }
57 const error = Cause.squash(result.cause);
58 const message = error instanceof Error ? error.message : "Failed to pair with the environment.";
59 if (
60 error !== null &&
61 typeof error === "object" &&
62 "reason" in error &&
63 error.reason === "unsupported"
64 ) {
65 Dialog.alert("Client not supported", message);
66 return { ok: false, error: null };
67 }
68 return { ok: false, error: message };
70​
71const remoteEnvironmentProjections = createRemoteEnvironmentProjectionAtoms({
72 presentationAtom: environmentPresentations.presentationAtom,
73 preparedConnectionAtom: environmentSession.preparedConnectionValueAtom,
74 serverConfigAtom: serverEnvironment.configValueAtom,
75});
76​
77export const environmentConnectedAtom = Atom.family((environmentId: EnvironmentId) =>
78 Atom.make(
79 (get) =>
80 get(remoteEnvironmentProjections.runtimeStateAtom(environmentId))?.connectionState ===
81 "connected",
82 ).pipe(Atom.withLabel(`mobile:environment-connected:${environmentId}`)),
83);
84​
85const EMPTY_SAVED_CONNECTION_ATOM = Atom.make<SavedRemoteConnection | null>(null).pipe(
86 Atom.withLabel("mobile:saved-connection:empty"),
87);
88​
89const EMPTY_RUNTIME_STATE_ATOM = Atom.make<EnvironmentRuntimeState | null>(null).pipe(
90 Atom.withLabel("mobile:environment-runtime-state:empty"),
91);
92​
93const savedConnectionsByIdAtom = Atom.make((get) => {
94 const catalog = get(environmentCatalog.catalogValueAtom);
95 return Object.fromEntries(
96 [...catalog.entries.keys()].flatMap((environmentId) => {
97 const connection = get(remoteEnvironmentProjections.savedConnectionAtom(environmentId));
98 return connection === null ? [] : [[environmentId, connection]];
99 }),
100 ) as Record<EnvironmentId, SavedRemoteConnection>;
101}).pipe(Atom.withLabel("mobile:saved-connections-by-id"));
102​
103export function useSavedRemoteConnections() {
104 const catalog = useAtomValue(environmentCatalog.catalogValueAtom);
105 const savedConnectionsById = useAtomValue(savedConnectionsByIdAtom);
106​
107 return {
108 isLoadingSavedConnection: !catalog.isReady,
109 savedConnectionsById,
110 };
112​
113export function useSavedRemoteConnection(
114 environmentId: EnvironmentId | null,
115): SavedRemoteConnection | null {
116 return useAtomValue(
117 environmentId === null
118 ? EMPTY_SAVED_CONNECTION_ATOM
119 : remoteEnvironmentProjections.savedConnectionAtom(environmentId),
120 );
122​
123export function useRemoteEnvironmentRuntime(
124 environmentId: EnvironmentId | null,
125): EnvironmentRuntimeState | null {
126 return useAtomValue(
127 environmentId === null
128 ? EMPTY_RUNTIME_STATE_ATOM
129 : remoteEnvironmentProjections.runtimeStateAtom(environmentId),
130 );
132​
133export function useRemoteConnectionStatus() {
134 const state = useWorkspaceConnectionState();
135 const connectedEnvironments: ReadonlyArray<ConnectedEnvironmentSummary> =
136 useWorkspaceEnvironments();
137 const pendingConnectionError = useAtomValue(pendingConnectionErrorAtom);
138​
139 return {
140 connectedEnvironments,
141 connectionState: state.connectionState,
142 connectionError: pendingConnectionError ?? state.connectionError,
143 };
145​
146export function useRemoteConnections() {
147 const controller = useConnectionController();
148 const navigation = useNavigation();
149 const connectionPairingUrl = useAtomValue(connectionPairingUrlAtom);
150 const { connectedEnvironments, connectionError, connectionState } = useRemoteConnectionStatus();
151​
152 const onChangeConnectionPairingUrl = (pairingUrl: string) => {
153 appAtomRegistry.set(connectionPairingUrlAtom, pairingUrl);
154 };
155​
156 const onConnectPress = (pairingUrl?: string, expectedEnvironmentId?: EnvironmentId) =>
157 pairEnvironment(pairingUrl ?? connectionPairingUrl, expectedEnvironmentId);
158​
159 const onReconnectEnvironment = (environmentId: EnvironmentId) =>
160 controller.retryEnvironment(environmentId);
161 const onSetEnvironmentEnabled = (environmentId: EnvironmentId, enabled: boolean) =>
162 controller.setEnvironmentEnabled(environmentId, enabled);
163 const onUpdateEnvironment = (
164 environmentId: EnvironmentId,
165 updates: { readonly label: string; readonly displayUrl: string },
166 ) => controller.updateEnvironment(environmentId, updates);
167​
168 const onRemoveEnvironmentPress = (environmentId: EnvironmentId) => {
169 const environment = connectedEnvironments.find(
170 (candidate) => candidate.environmentId === environmentId,
171 );
172 if (!environment) {
173 return;
174 }
175 const remove = {
176 text: "Remove",
177 style: "destructive",
178 onPress: () => {
179 void controller.removeEnvironment(environmentId);
180 },
181 } as const;
182 if (environment.isRelayManaged) {
183 Dialog.alert(
184 "Remove from this device?",
185 `Forget ${environment.environmentLabel} and its cached threads on this device.\n\nIt stays on your T3 Connect account and keeps its host space. Deregister it under T3 Account → T3 Connect to free it.`,
186 [
187 { text: "Cancel", style: "cancel" },
188 // SettingsAuth renders nothing in builds without cloud config.
189 ...(hasCloudPublicConfig()
190 ? [
191 {
192 text: "Open T3 Account",
193 onPress: () => navigation.navigate("SettingsAuth"),
194 },
195 ]
196 : []),
197 remove,
198 ],
199 );
200 return;
201 }
202 Dialog.alert(
203 "Remove from this device?",
204 `Forget ${environment.environmentLabel} and its cached threads on this device. Switch it off instead to keep it saved.`,
205 [{ text: "Cancel", style: "cancel" }, remove],
206 );
207 };
208​
209 return {
210 connectionPairingUrl,
211 connectionState,
212 connectionError,
213 connectedEnvironments,
214 connectedEnvironmentCount: connectedEnvironments.length,
215 onChangeConnectionPairingUrl,
216 onConnectPress,
217 onReconnectEnvironment,
218 onSetEnvironmentEnabled,
219 onUpdateEnvironment,
220 onRemoveEnvironmentPress,
221 };