The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg } from "gt-i18n"; |
| 2 | import { translatableDetail } from "../errors/translatable.ts"; |
| 3 | import type { |
| 4 | RelayClientEnvironmentRecord, |
| 5 | RelayEnvironmentStatusResponse, |
| 6 | } from "@t3tools/contracts/relay"; |
| 7 | import { decodeRelayJwt } from "@t3tools/shared/relayJwt"; |
| 8 | import { |
| 9 | RelayEnvironmentConnectScope, |
| 10 | RelayEnvironmentStatusScope, |
| 11 | } from "@t3tools/contracts/relay"; |
| 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 Ref from "effect/Ref"; |
| 17 | import * as Semaphore from "effect/Semaphore"; |
| 18 | import * as Stream from "effect/Stream"; |
| 19 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 20 | |
| 21 | import * as ManagedRelay from "./managedRelay.ts"; |
| 22 | import * as ClientCapabilities from "../platform/capabilities.ts"; |
| 23 | import * as Connectivity from "../connection/connectivity.ts"; |
| 24 | import { mapManagedRelayError } from "../connection/errors.ts"; |
| 25 | import { ConnectionBlockedError, type ConnectionAttemptError } from "../connection/model.ts"; |
| 26 | import * as ConnectionWakeups from "../connection/wakeups.ts"; |
| 27 | |
| 28 | export type RelayEnvironmentAvailability = "checking" | "online" | "offline" | "error"; |
| 29 | |
| 30 | export interface RelayDiscoveredEnvironment { |
| 31 | readonly environment: RelayClientEnvironmentRecord; |
| 32 | readonly availability: RelayEnvironmentAvailability; |
| 33 | readonly status: Option.Option<RelayEnvironmentStatusResponse>; |
| 34 | readonly error: Option.Option<ConnectionAttemptError>; |
| 35 | } |
| 36 | |
| 37 | export interface RelayEnvironmentDiscoveryState { |
| 38 | readonly environments: ReadonlyMap<string, RelayDiscoveredEnvironment>; |
| 39 | // Only a loaded account list distinguishes a missing registration from an unknown one. |
| 40 | readonly listed: boolean; |
| 41 | readonly refreshing: boolean; |
| 42 | readonly offline: boolean; |
| 43 | readonly error: Option.Option<ConnectionAttemptError>; |
| 44 | } |
| 45 | |
| 46 | export class RelayEnvironmentDiscovery extends Context.Service< |
| 47 | RelayEnvironmentDiscovery, |
| 48 | { |
| 49 | readonly state: SubscriptionRef.SubscriptionRef<RelayEnvironmentDiscoveryState>; |
| 50 | readonly refresh: Effect.Effect<void>; |
| 51 | } |
| 52 | >()("@t3tools/client-runtime/relay/discovery/RelayEnvironmentDiscovery") {} |
| 53 | |
| 54 | export const EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE: RelayEnvironmentDiscoveryState = { |
| 55 | environments: new Map(), |
| 56 | listed: false, |
| 57 | refreshing: false, |
| 58 | offline: false, |
| 59 | error: Option.none(), |
| 60 | }; |
| 61 | |
| 62 | export type RelayEnvironmentRegistration = "registered" | "unregistered" | "unknown"; |
| 63 | |
| 64 | export function relayEnvironmentRegistration( |
| 65 | state: RelayEnvironmentDiscoveryState, |
| 66 | environmentId: string, |
| 67 | ): RelayEnvironmentRegistration { |
| 68 | if (state.environments.has(environmentId)) return "registered"; |
| 69 | return state.listed ? "unregistered" : "unknown"; |
| 70 | } |
| 71 | |
| 72 | function validateStatus( |
| 73 | environment: RelayClientEnvironmentRecord, |
| 74 | status: RelayEnvironmentStatusResponse, |
| 75 | ): Effect.Effect<RelayEnvironmentStatusResponse, ConnectionAttemptError> { |
| 76 | if (status.environmentId !== environment.environmentId) { |
| 77 | return Effect.fail( |
| 78 | new ConnectionBlockedError({ |
| 79 | reason: "configuration", |
| 80 | ...translatableDetail(msg("Relay returned status for a different environment.")), |
| 81 | }), |
| 82 | ); |
| 83 | } |
| 84 | if ( |
| 85 | status.endpoint.httpBaseUrl !== environment.endpoint.httpBaseUrl || |
| 86 | status.endpoint.wsBaseUrl !== environment.endpoint.wsBaseUrl || |
| 87 | status.endpoint.providerKind !== environment.endpoint.providerKind |
| 88 | ) { |
| 89 | return Effect.fail( |
| 90 | new ConnectionBlockedError({ |
| 91 | reason: "configuration", |
| 92 | ...translatableDetail(msg("Relay returned status for a different environment endpoint.")), |
| 93 | }), |
| 94 | ); |
| 95 | } |
| 96 | if ( |
| 97 | status.descriptor !== undefined && |
| 98 | status.descriptor.environmentId !== environment.environmentId |
| 99 | ) { |
| 100 | return Effect.fail( |
| 101 | new ConnectionBlockedError({ |
| 102 | reason: "configuration", |
| 103 | ...translatableDetail(msg("Relay returned a descriptor for a different environment.")), |
| 104 | }), |
| 105 | ); |
| 106 | } |
| 107 | return Effect.succeed(status); |
| 108 | } |
| 109 | |
| 110 | const relayAccountId = Effect.fn("clientRuntime.discovery.relayAccountId")(function* ( |
| 111 | clerkToken: string, |
| 112 | ) { |
| 113 | const claims = yield* decodeRelayJwt(clerkToken).pipe(Effect.option); |
| 114 | const sub = Option.isSome(claims) ? claims.value.sub : undefined; |
| 115 | return typeof sub === "string" && sub.length > 0 ? Option.some(sub) : Option.none<string>(); |
| 116 | }); |
| 117 | |
| 118 | /** @public */ |
| 119 | export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () { |
| 120 | const relay = yield* ManagedRelay.ManagedRelayClient; |
| 121 | const session = yield* ClientCapabilities.CloudSession; |
| 122 | const connectivity = yield* Connectivity.Connectivity; |
| 123 | const wakeups = yield* ConnectionWakeups.ConnectionWakeups; |
| 124 | const state = yield* SubscriptionRef.make(EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE); |
| 125 | const refreshLock = yield* Semaphore.make(1); |
| 126 | const foregroundCheckLock = yield* Semaphore.make(1); |
| 127 | const registrationCheckRequested = yield* Ref.make(false); |
| 128 | const hasRefreshed = yield* Ref.make(false); |
| 129 | const accountGeneration = yield* Ref.make(0); |
| 130 | const activeAccountId = yield* Ref.make<Option.Option<string>>(Option.none()); |
| 131 | const refreshGeneration = yield* Ref.make(0); |
| 132 | const offlineReportFingerprints = yield* Ref.make<ReadonlyMap<string, string>>(new Map()); |
| 133 | |
| 134 | const clearOfflineReport = Effect.fn("RelayEnvironmentDiscovery.clearOfflineReport")(function* ( |
| 135 | environmentId: string, |
| 136 | ) { |
| 137 | yield* Ref.update(offlineReportFingerprints, (current) => { |
| 138 | if (!current.has(environmentId)) { |
| 139 | return current; |
| 140 | } |
| 141 | const next = new Map(current); |
| 142 | next.delete(environmentId); |
| 143 | return next; |
| 144 | }); |
| 145 | }); |
| 146 | |
| 147 | const updateEnvironment = Effect.fn("RelayEnvironmentDiscovery.updateEnvironment")(function* ( |
| 148 | generation: number, |
| 149 | environmentId: string, |
| 150 | update: (current: RelayDiscoveredEnvironment) => RelayDiscoveredEnvironment, |
| 151 | ) { |
| 152 | if ((yield* Ref.get(accountGeneration)) !== generation) { |
| 153 | return; |
| 154 | } |
| 155 | yield* SubscriptionRef.update(state, (current) => { |
| 156 | const entry = current.environments.get(environmentId); |
| 157 | if (entry === undefined) { |
| 158 | return current; |
| 159 | } |
| 160 | const environments = new Map(current.environments); |
| 161 | environments.set(environmentId, update(entry)); |
| 162 | return { ...current, environments }; |
| 163 | }); |
| 164 | }); |
| 165 | |
| 166 | const refreshStatus = Effect.fn("RelayEnvironmentDiscovery.refreshStatus")(function* ( |
| 167 | generation: number, |
| 168 | clerkToken: string, |
| 169 | environment: RelayClientEnvironmentRecord, |
| 170 | ) { |
| 171 | const result = yield* relay |
| 172 | .getEnvironmentStatus({ |
| 173 | clerkToken, |
| 174 | scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope], |
| 175 | environmentId: environment.environmentId, |
| 176 | }) |
| 177 | .pipe( |
| 178 | Effect.mapError(mapManagedRelayError), |
| 179 | Effect.flatMap((status) => validateStatus(environment, status)), |
| 180 | Effect.result, |
| 181 | ); |
| 182 | |
| 183 | if (result._tag === "Success") { |
| 184 | if (result.success.status === "offline") { |
| 185 | const fingerprint = `${result.success.endpoint.httpBaseUrl}\n${result.success.error ?? ""}`; |
| 186 | const shouldReport = yield* Ref.modify(offlineReportFingerprints, (current) => { |
| 187 | if (current.get(environment.environmentId) === fingerprint) { |
| 188 | return [false, current]; |
| 189 | } |
| 190 | return [true, new Map(current).set(environment.environmentId, fingerprint)]; |
| 191 | }); |
| 192 | if (shouldReport) { |
| 193 | yield* Effect.logWarning("Relay environment health check reported offline", { |
| 194 | environmentId: result.success.environmentId, |
| 195 | endpoint: result.success.endpoint.httpBaseUrl, |
| 196 | message: result.success.error, |
| 197 | traceId: result.success.traceId, |
| 198 | }); |
| 199 | } |
| 200 | } else { |
| 201 | yield* clearOfflineReport(environment.environmentId); |
| 202 | } |
| 203 | yield* updateEnvironment(generation, environment.environmentId, (current) => ({ |
| 204 | ...current, |
| 205 | availability: result.success.status, |
| 206 | status: Option.some(result.success), |
| 207 | error: Option.none(), |
| 208 | })); |
| 209 | return; |
| 210 | } |
| 211 | |
| 212 | yield* clearOfflineReport(environment.environmentId); |
| 213 | yield* updateEnvironment(generation, environment.environmentId, (current) => ({ |
| 214 | ...current, |
| 215 | availability: "error", |
| 216 | error: Option.some(result.failure), |
| 217 | })); |
| 218 | }); |
| 219 | |
| 220 | const refresh = refreshLock.withPermits(1)( |
| 221 | Effect.gen(function* () { |
| 222 | yield* Ref.set(hasRefreshed, true); |
| 223 | if ((yield* connectivity.status) === "offline") { |
| 224 | yield* SubscriptionRef.update(state, (current) => ({ |
| 225 | ...current, |
| 226 | refreshing: false, |
| 227 | offline: true, |
| 228 | })); |
| 229 | return; |
| 230 | } |
| 231 | |
| 232 | let generation = yield* Ref.get(accountGeneration); |
| 233 | yield* Ref.set(refreshGeneration, generation); |
| 234 | yield* SubscriptionRef.set(state, { |
| 235 | environments: new Map(), |
| 236 | listed: false, |
| 237 | refreshing: true, |
| 238 | offline: false, |
| 239 | error: Option.none(), |
| 240 | }); |
| 241 | |
| 242 | // Sign-out triggers credentials-changed refreshes and must settle to an empty list. |
| 243 | // Only session-level missing credentials are benign; relay-side auth failures must surface. |
| 244 | const tokenResult = yield* Effect.result(session.clerkToken); |
| 245 | if (tokenResult._tag === "Failure") { |
| 246 | const failure = tokenResult.failure; |
| 247 | if (failure._tag === "ConnectionBlockedError" && failure.reason === "authentication") { |
| 248 | if ((yield* Ref.get(accountGeneration)) !== generation) { |
| 249 | return; |
| 250 | } |
| 251 | yield* SubscriptionRef.update(state, (current) => ({ |
| 252 | ...current, |
| 253 | refreshing: false, |
| 254 | })); |
| 255 | return; |
| 256 | } |
| 257 | return yield* failure; |
| 258 | } |
| 259 | const clerkToken = tokenResult.success; |
| 260 | if ((yield* Ref.get(accountGeneration)) !== generation) { |
| 261 | return; |
| 262 | } |
| 263 | const accountId = yield* relayAccountId(clerkToken); |
| 264 | const previousAccountId = yield* Ref.get(activeAccountId); |
| 265 | if ( |
| 266 | Option.isSome(previousAccountId) && |
| 267 | (!Option.isSome(accountId) || previousAccountId.value !== accountId.value) |
| 268 | ) { |
| 269 | generation = yield* Ref.updateAndGet(accountGeneration, (current) => current + 1); |
| 270 | yield* Ref.set(refreshGeneration, generation); |
| 271 | } |
| 272 | yield* Ref.set(activeAccountId, accountId); |
| 273 | |
| 274 | const environments = yield* relay |
| 275 | .listEnvironments({ clerkToken }) |
| 276 | .pipe(Effect.mapError(mapManagedRelayError)); |
| 277 | if ((yield* Ref.get(accountGeneration)) !== generation) { |
| 278 | return; |
| 279 | } |
| 280 | const next = new Map<string, RelayDiscoveredEnvironment>(); |
| 281 | for (const environment of environments) { |
| 282 | next.set(environment.environmentId, { |
| 283 | environment, |
| 284 | availability: "checking", |
| 285 | status: Option.none(), |
| 286 | error: Option.none(), |
| 287 | }); |
| 288 | } |
| 289 | yield* SubscriptionRef.update(state, (current) => ({ |
| 290 | ...current, |
| 291 | environments: next, |
| 292 | listed: true, |
| 293 | })); |
| 294 | |
| 295 | yield* Effect.forEach( |
| 296 | environments, |
| 297 | (environment) => refreshStatus(generation, clerkToken, environment), |
| 298 | { |
| 299 | concurrency: "unbounded", |
| 300 | discard: true, |
| 301 | }, |
| 302 | ); |
| 303 | if ((yield* Ref.get(accountGeneration)) !== generation) { |
| 304 | return; |
| 305 | } |
| 306 | yield* SubscriptionRef.update(state, (current) => ({ |
| 307 | ...current, |
| 308 | refreshing: false, |
| 309 | })); |
| 310 | }).pipe( |
| 311 | Effect.catch((error) => |
| 312 | Effect.gen(function* () { |
| 313 | const generation = yield* Ref.get(refreshGeneration); |
| 314 | if ((yield* Ref.get(accountGeneration)) !== generation) { |
| 315 | return; |
| 316 | } |
| 317 | yield* SubscriptionRef.update(state, (current) => ({ |
| 318 | ...current, |
| 319 | refreshing: false, |
| 320 | error: Option.some(error), |
| 321 | })); |
| 322 | }), |
| 323 | ), |
| 324 | ), |
| 325 | ); |
| 326 | |
| 327 | // Refreshes only when the account's registrations changed, so foregrounding keeps unchanged rows. |
| 328 | const checkRegistrations = Effect.fn("RelayEnvironmentDiscovery.checkRegistrations")( |
| 329 | function* () { |
| 330 | if ( |
| 331 | !(yield* Ref.get(hasRefreshed)) || |
| 332 | (yield* connectivity.status) === "offline" || |
| 333 | Option.isNone(yield* session.identity) |
| 334 | ) { |
| 335 | return; |
| 336 | } |
| 337 | const current = yield* SubscriptionRef.get(state); |
| 338 | if (!current.listed || current.refreshing || Option.isSome(current.error)) { |
| 339 | return yield* refresh; |
| 340 | } |
| 341 | const generation = yield* Ref.get(accountGeneration); |
| 342 | const clerkToken = yield* session.clerkToken; |
| 343 | const listed = yield* relay.listEnvironments({ clerkToken }); |
| 344 | if ((yield* Ref.get(accountGeneration)) !== generation) { |
| 345 | return; |
| 346 | } |
| 347 | const known = (yield* SubscriptionRef.get(state)).environments; |
| 348 | if ( |
| 349 | listed.length === known.size && |
| 350 | listed.every((environment) => known.has(environment.environmentId)) |
| 351 | ) { |
| 352 | return; |
| 353 | } |
| 354 | yield* refresh; |
| 355 | }, |
| 356 | Effect.catch((error) => |
| 357 | Effect.logDebug("Relay foreground registration check failed", { error }), |
| 358 | ), |
| 359 | ); |
| 360 | // A wakeup during a running check is answered by one more check once that one finishes. |
| 361 | const requestRegistrationCheck = Ref.set(registrationCheckRequested, true).pipe( |
| 362 | Effect.andThen( |
| 363 | foregroundCheckLock.withPermitsIfAvailable(1)( |
| 364 | Effect.gen(function* () { |
| 365 | while (yield* Ref.getAndSet(registrationCheckRequested, false)) { |
| 366 | yield* checkRegistrations(); |
| 367 | } |
| 368 | }), |
| 369 | ), |
| 370 | ), |
| 371 | ); |
| 372 | |
| 373 | yield* connectivity.changes.pipe( |
| 374 | Stream.changes, |
| 375 | Stream.runForEach((networkStatus) => |
| 376 | networkStatus === "offline" |
| 377 | ? SubscriptionRef.update(state, (current) => ({ |
| 378 | ...current, |
| 379 | refreshing: false, |
| 380 | offline: true, |
| 381 | })) |
| 382 | : Ref.get(hasRefreshed).pipe( |
| 383 | Effect.flatMap((shouldRefresh) => (shouldRefresh ? refresh : Effect.void)), |
| 384 | ), |
| 385 | ), |
| 386 | Effect.forkScoped, |
| 387 | ); |
| 388 | yield* wakeups.changes.pipe( |
| 389 | Stream.runForEach((reason) => |
| 390 | reason === "credentials-changed" |
| 391 | ? Effect.gen(function* () { |
| 392 | yield* Ref.update(accountGeneration, (current) => current + 1); |
| 393 | yield* Ref.set(activeAccountId, Option.none()); |
| 394 | yield* Ref.set(offlineReportFingerprints, new Map()); |
| 395 | yield* SubscriptionRef.set(state, EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE); |
| 396 | yield* refresh.pipe(Effect.forkScoped); |
| 397 | }) |
| 398 | : ConnectionWakeups.shouldRelistAccountAfterWakeup(reason) |
| 399 | ? requestRegistrationCheck.pipe(Effect.forkScoped) |
| 400 | : Effect.void, |
| 401 | ), |
| 402 | Effect.forkScoped, |
| 403 | ); |
| 404 | |
| 405 | return RelayEnvironmentDiscovery.of({ state, refresh }); |
| 406 | }); |
| 407 | |
| 408 | export const layer = Layer.effect(RelayEnvironmentDiscovery, make()); |