The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { ClientCapabilities, PlatformConnectionSource } from "@t3tools/client-runtime/platform"; |
| 2 | import { |
| 3 | ConnectionBlockedError, |
| 4 | ConnectionTransientError, |
| 5 | Connectivity, |
| 6 | Wakeups, |
| 7 | } from "@t3tools/client-runtime/connection"; |
| 8 | import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay"; |
| 9 | import * as Clock from "effect/Clock"; |
| 10 | import { msg } from "gt-react-native"; |
| 11 | import { m } from "../i18n/messages"; |
| 12 | import * as Context from "effect/Context"; |
| 13 | import * as Effect from "effect/Effect"; |
| 14 | import * as Layer from "effect/Layer"; |
| 15 | import * as Option from "effect/Option"; |
| 16 | import * as Queue from "effect/Queue"; |
| 17 | import * as Stream from "effect/Stream"; |
| 18 | import Constants from "expo-constants"; |
| 19 | import * as Network from "expo-network"; |
| 20 | import { AppState } from "react-native"; |
| 21 | |
| 22 | import { authClientMetadata } from "../lib/authClientMetadata"; |
| 23 | import * as Runtime from "../lib/runtime"; |
| 24 | import * as MobileStorage from "../persistence/mobile-storage"; |
| 25 | import { appAtomRegistry } from "../state/atom-registry"; |
| 26 | import { mobileApplicationActiveWakeup } from "./app-state-wakeups"; |
| 27 | import * as EnvironmentOwnedDataCleanup from "./environment-owned-data-cleanup"; |
| 28 | import * as ConnectionStorage from "./storage"; |
| 29 | |
| 30 | function networkStatus(state: Network.NetworkState): "unknown" | "offline" | "online" { |
| 31 | if (state.isConnected === false) { |
| 32 | return "offline"; |
| 33 | } |
| 34 | if (state.isConnected === true) { |
| 35 | return "online"; |
| 36 | } |
| 37 | return "unknown"; |
| 38 | } |
| 39 | |
| 40 | const layerConnectivity = Connectivity.layer({ |
| 41 | status: Effect.tryPromise({ |
| 42 | try: () => Network.getNetworkStateAsync(), |
| 43 | catch: () => undefined, |
| 44 | }).pipe( |
| 45 | Effect.match({ |
| 46 | onFailure: () => "unknown" as const, |
| 47 | onSuccess: networkStatus, |
| 48 | }), |
| 49 | ), |
| 50 | changes: Stream.callback((queue) => |
| 51 | Effect.acquireRelease( |
| 52 | Effect.sync(() => { |
| 53 | let active = true; |
| 54 | const networkSubscription = Network.addNetworkStateListener((state) => { |
| 55 | Queue.offerUnsafe(queue, networkStatus(state)); |
| 56 | }); |
| 57 | const appStateSubscription = AppState.addEventListener("change", (state) => { |
| 58 | if (state !== "active") { |
| 59 | return; |
| 60 | } |
| 61 | void Network.getNetworkStateAsync() |
| 62 | .then((current) => { |
| 63 | if (active) { |
| 64 | Queue.offerUnsafe(queue, networkStatus(current)); |
| 65 | } |
| 66 | }) |
| 67 | .catch(() => undefined); |
| 68 | }); |
| 69 | return { |
| 70 | close: () => { |
| 71 | active = false; |
| 72 | networkSubscription.remove(); |
| 73 | appStateSubscription.remove(); |
| 74 | }, |
| 75 | }; |
| 76 | }), |
| 77 | ({ close }) => Effect.sync(close), |
| 78 | ).pipe(Effect.asVoid), |
| 79 | ), |
| 80 | }); |
| 81 | |
| 82 | /** Wake connections on network path changes; online/offline misses Wi-Fi-to-cellular moves. */ |
| 83 | const networkPathChanges = Stream.callback<"network-changed">((queue) => |
| 84 | Effect.acquireRelease( |
| 85 | Effect.sync(() => { |
| 86 | let active = true; |
| 87 | let previous: Network.NetworkStateType | undefined; |
| 88 | const record = (state: Network.NetworkState) => { |
| 89 | const type = state.isConnected === true ? state.type : undefined; |
| 90 | if (previous !== undefined && type !== undefined && type !== previous) { |
| 91 | Queue.offerUnsafe(queue, "network-changed"); |
| 92 | } |
| 93 | previous = type ?? previous; |
| 94 | }; |
| 95 | // Seed the current type: the listener reports only changes and would miss the first move. |
| 96 | void Network.getNetworkStateAsync() |
| 97 | .then((state) => { |
| 98 | if (active && previous === undefined && state.isConnected === true) { |
| 99 | previous = state.type; |
| 100 | } |
| 101 | }) |
| 102 | .catch(() => undefined); |
| 103 | const subscription = Network.addNetworkStateListener(record); |
| 104 | return { |
| 105 | remove: () => { |
| 106 | active = false; |
| 107 | subscription.remove(); |
| 108 | }, |
| 109 | }; |
| 110 | }), |
| 111 | (subscription) => Effect.sync(() => subscription.remove()), |
| 112 | ).pipe(Effect.asVoid), |
| 113 | ); |
| 114 | |
| 115 | const layerWakeups = Wakeups.layer({ |
| 116 | changes: Stream.mergeAll( |
| 117 | [ |
| 118 | Stream.callback<"application-active-probe" | "application-active-long">((queue) => |
| 119 | Effect.acquireRelease( |
| 120 | Effect.gen(function* () { |
| 121 | const nowMs = yield* Clock.currentTimeMillis; |
| 122 | let backgroundedAtMs = AppState.currentState === "background" ? nowMs : null; |
| 123 | return AppState.addEventListener("change", (state) => { |
| 124 | if (state === "background") { |
| 125 | backgroundedAtMs = Date.now(); |
| 126 | return; |
| 127 | } |
| 128 | if (state === "active") { |
| 129 | Queue.offerUnsafe( |
| 130 | queue, |
| 131 | mobileApplicationActiveWakeup(backgroundedAtMs, Date.now()), |
| 132 | ); |
| 133 | backgroundedAtMs = null; |
| 134 | } |
| 135 | }); |
| 136 | }), |
| 137 | (subscription) => Effect.sync(() => subscription.remove()), |
| 138 | ).pipe(Effect.asVoid), |
| 139 | ), |
| 140 | managedRelayAccountChanges(appAtomRegistry).pipe( |
| 141 | Stream.map(() => "credentials-changed" as const), |
| 142 | ), |
| 143 | networkPathChanges, |
| 144 | ], |
| 145 | { concurrency: "unbounded" }, |
| 146 | ), |
| 147 | }); |
| 148 | |
| 149 | const layerCapabilities = Layer.effectContext( |
| 150 | Effect.gen(function* () { |
| 151 | const storage = yield* MobileStorage.MobileStorage; |
| 152 | return Context.make( |
| 153 | ClientCapabilities.CloudSession, |
| 154 | ClientCapabilities.CloudSession.of({ |
| 155 | identity: Effect.sync(() => |
| 156 | Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)), |
| 157 | ), |
| 158 | clerkToken: Effect.gen(function* () { |
| 159 | const session = appAtomRegistry.get(managedRelaySessionAtom); |
| 160 | if (session === null) { |
| 161 | return yield* new ConnectionBlockedError({ |
| 162 | reason: "authentication", |
| 163 | detail: m( |
| 164 | msg("Sign in to {product} to connect this environment.", { product: "T3 Connect" }), |
| 165 | ), |
| 166 | }); |
| 167 | } |
| 168 | const token = yield* session.readClerkToken().pipe( |
| 169 | Effect.mapError( |
| 170 | (error) => |
| 171 | new ConnectionTransientError({ |
| 172 | reason: "network", |
| 173 | detail: error.message, |
| 174 | }), |
| 175 | ), |
| 176 | ); |
| 177 | if (token === null) { |
| 178 | return yield* new ConnectionBlockedError({ |
| 179 | reason: "authentication", |
| 180 | detail: m(msg("The {product} session is unavailable.", { product: "T3 Connect" })), |
| 181 | }); |
| 182 | } |
| 183 | return token; |
| 184 | }), |
| 185 | }), |
| 186 | ).pipe( |
| 187 | Context.add( |
| 188 | ClientCapabilities.PrimaryEnvironmentAuth, |
| 189 | ClientCapabilities.PrimaryEnvironmentAuth.of({ |
| 190 | bearerToken: Effect.succeedNone, |
| 191 | }), |
| 192 | ), |
| 193 | // The relay device id already persists in secure storage; analytics only sends its hash. |
| 194 | Context.add(ClientCapabilities.AnalyticsDevice, { |
| 195 | id: storage.loadOrCreateAgentAwarenessDeviceId.pipe(Effect.option), |
| 196 | }), |
| 197 | Context.add( |
| 198 | ClientCapabilities.RelayDeviceIdentity, |
| 199 | ClientCapabilities.RelayDeviceIdentity.of({ |
| 200 | deviceId: storage.loadOrCreateAgentAwarenessDeviceId.pipe( |
| 201 | Effect.mapError( |
| 202 | (cause) => |
| 203 | new ConnectionTransientError({ |
| 204 | reason: "remote-unavailable", |
| 205 | detail: m( |
| 206 | msg("Could not load the mobile device identity: {cause}", { |
| 207 | cause: String(cause), |
| 208 | }), |
| 209 | ), |
| 210 | }), |
| 211 | ), |
| 212 | Effect.asSome, |
| 213 | ), |
| 214 | }), |
| 215 | ), |
| 216 | Context.add( |
| 217 | ClientCapabilities.ClientPresentation, |
| 218 | ClientCapabilities.ClientPresentation.of({ |
| 219 | metadata: authClientMetadata(Constants.expoConfig?.version), |
| 220 | }), |
| 221 | ), |
| 222 | Context.add( |
| 223 | ClientCapabilities.SshEnvironmentGateway, |
| 224 | ClientCapabilities.SshEnvironmentGateway.of({ |
| 225 | provision: Effect.fn("ClientCapabilities.SshEnvironmentGateway.provision")(() => |
| 226 | Effect.fail( |
| 227 | new ConnectionBlockedError({ |
| 228 | reason: "unsupported", |
| 229 | detail: m( |
| 230 | msg("{feature} environments are only available in the desktop app.", { |
| 231 | feature: "SSH", |
| 232 | }), |
| 233 | ), |
| 234 | }), |
| 235 | ), |
| 236 | ), |
| 237 | prepare: Effect.fn("ClientCapabilities.SshEnvironmentGateway.prepare")(() => |
| 238 | Effect.fail( |
| 239 | new ConnectionBlockedError({ |
| 240 | reason: "unsupported", |
| 241 | detail: m( |
| 242 | msg("{feature} environments are only available in the desktop app.", { |
| 243 | feature: "SSH", |
| 244 | }), |
| 245 | ), |
| 246 | }), |
| 247 | ), |
| 248 | ), |
| 249 | disconnect: Effect.fn("ClientCapabilities.SshEnvironmentGateway.disconnect")( |
| 250 | () => Effect.void, |
| 251 | ), |
| 252 | }), |
| 253 | ), |
| 254 | ); |
| 255 | }), |
| 256 | ); |
| 257 | |
| 258 | const layerPlatformConnectionSource = Layer.succeed( |
| 259 | PlatformConnectionSource.PlatformConnectionSource, |
| 260 | PlatformConnectionSource.PlatformConnectionSource.of({ |
| 261 | registrations: Stream.empty, |
| 262 | }), |
| 263 | ); |
| 264 | |
| 265 | const layerProvidedConnectionStorage = ConnectionStorage.layer.pipe(Layer.provide(Runtime.layer)); |
| 266 | const layerProvidedCapabilities = layerCapabilities.pipe(Layer.provide(Runtime.layer)); |
| 267 | |
| 268 | type ConnectionPlatformLayerSource = |
| 269 | | typeof layerProvidedConnectionStorage |
| 270 | | typeof Runtime.layer |
| 271 | | typeof layerConnectivity |
| 272 | | typeof layerWakeups |
| 273 | | typeof layerProvidedCapabilities |
| 274 | | typeof layerPlatformConnectionSource |
| 275 | | typeof EnvironmentOwnedDataCleanup.layer; |
| 276 | |
| 277 | export const layer: Layer.Layer< |
| 278 | Layer.Success<ConnectionPlatformLayerSource>, |
| 279 | Layer.Error<ConnectionPlatformLayerSource>, |
| 280 | Layer.Services<ConnectionPlatformLayerSource> |
| 281 | > = Layer.mergeAll( |
| 282 | layerProvidedConnectionStorage, |
| 283 | Runtime.layer, |
| 284 | layerConnectivity, |
| 285 | layerWakeups, |
| 286 | layerProvidedCapabilities, |
| 287 | layerPlatformConnectionSource, |
| 288 | EnvironmentOwnedDataCleanup.layer, |
| 289 | ); |