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