The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg } from "gt-react"; |
| 2 | import { |
| 3 | ClientCapabilities, |
| 4 | PlatformConnectionSource, |
| 5 | Persistence, |
| 6 | } from "@t3tools/client-runtime/platform"; |
| 7 | import { |
| 8 | BearerConnectionCredential, |
| 9 | BearerConnectionProfile, |
| 10 | BearerConnectionRegistration, |
| 11 | BearerConnectionTarget, |
| 12 | ConnectionBlockedError, |
| 13 | type ConnectionAttemptError, |
| 14 | ConnectionTransientError, |
| 15 | Connectivity, |
| 16 | mapRemoteEnvironmentError, |
| 17 | type PlatformConnectionRegistration, |
| 18 | PrimaryConnectionRegistration, |
| 19 | PrimaryConnectionTarget, |
| 20 | sshTargetKey, |
| 21 | Wakeups, |
| 22 | } from "@t3tools/client-runtime/connection"; |
| 23 | import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization"; |
| 24 | import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment"; |
| 25 | import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay"; |
| 26 | import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc"; |
| 27 | import { |
| 28 | AuthStandardClientScopes, |
| 29 | type DesktopBridge, |
| 30 | type DesktopEnvironmentBootstrap, |
| 31 | type DesktopSshEnvironmentBootstrap, |
| 32 | type DesktopSshEnvironmentTarget, |
| 33 | type EnvironmentId, |
| 34 | PRIMARY_LOCAL_ENVIRONMENT_ID, |
| 35 | } from "@t3tools/contracts"; |
| 36 | import * as Clock from "effect/Clock"; |
| 37 | import * as Context from "effect/Context"; |
| 38 | import * as Effect from "effect/Effect"; |
| 39 | import * as Layer from "effect/Layer"; |
| 40 | import * as Option from "effect/Option"; |
| 41 | import * as Queue from "effect/Queue"; |
| 42 | import * as Ref from "effect/Ref"; |
| 43 | import * as Stream from "effect/Stream"; |
| 44 | import { FetchHttpClient } from "effect/http"; |
| 45 | |
| 46 | import { APP_VERSION } from "../branding"; |
| 47 | import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth"; |
| 48 | import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer"; |
| 49 | import { |
| 50 | readPrimaryEnvironmentTarget, |
| 51 | type PrimaryEnvironmentTarget, |
| 52 | } from "../environments/primary/target"; |
| 53 | import { clearComposerDraftsEnvironment } from "../composerDraftStore"; |
| 54 | import { isHostedStaticApp } from "../hostedPairing"; |
| 55 | import { isLocalEnvironmentDisabled } from "../localEnvironment"; |
| 56 | import { randomUUID } from "../lib/utils"; |
| 57 | import { appAtomRegistry } from "../rpc/atomRegistry"; |
| 58 | import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState"; |
| 59 | import { |
| 60 | desktopLocalConnectionId, |
| 61 | readDesktopSecondaryBootstrapsResult, |
| 62 | type DesktopSecondaryBootstrapsRead, |
| 63 | } from "./desktopLocal"; |
| 64 | import * as ConnectionStorage from "./storage"; |
| 65 | import { clientPresentationMetadata } from "./clientMetadata"; |
| 66 | import { m } from "../i18n/messages"; |
| 67 | |
| 68 | let nextObservedRpcRequestId = 0; |
| 69 | |
| 70 | function currentNetworkStatus(): "unknown" | "offline" | "online" { |
| 71 | if (typeof navigator === "undefined") { |
| 72 | return "unknown"; |
| 73 | } |
| 74 | return navigator.onLine ? "online" : "offline"; |
| 75 | } |
| 76 | |
| 77 | const layerConnectivity = Connectivity.layer({ |
| 78 | status: Effect.sync(currentNetworkStatus), |
| 79 | changes: Stream.callback((queue) => |
| 80 | Effect.acquireRelease( |
| 81 | Effect.sync(() => { |
| 82 | const online = () => Queue.offerUnsafe(queue, "online"); |
| 83 | const offline = () => Queue.offerUnsafe(queue, "offline"); |
| 84 | window.addEventListener("online", online); |
| 85 | window.addEventListener("offline", offline); |
| 86 | return { online, offline }; |
| 87 | }), |
| 88 | ({ online, offline }) => |
| 89 | Effect.sync(() => { |
| 90 | window.removeEventListener("online", online); |
| 91 | window.removeEventListener("offline", offline); |
| 92 | }), |
| 93 | ).pipe(Effect.asVoid), |
| 94 | ), |
| 95 | }); |
| 96 | |
| 97 | interface NetworkInformationLike extends EventTarget { |
| 98 | readonly type?: string; |
| 99 | } |
| 100 | |
| 101 | // change also fires for same-network bandwidth and latency estimates; count only type changes. |
| 102 | const networkPathChanges = Stream.callback<"network-changed">((queue) => |
| 103 | Effect.acquireRelease( |
| 104 | Effect.sync(() => { |
| 105 | const connection = |
| 106 | typeof navigator === "undefined" |
| 107 | ? undefined |
| 108 | : (navigator as Navigator & { readonly connection?: NetworkInformationLike }).connection; |
| 109 | if (connection?.type === undefined) return undefined; |
| 110 | let previous = connection.type; |
| 111 | const listener = () => { |
| 112 | const type = connection.type; |
| 113 | if (type === undefined || type === previous) return; |
| 114 | previous = type; |
| 115 | Queue.offerUnsafe(queue, "network-changed"); |
| 116 | }; |
| 117 | connection.addEventListener("change", listener); |
| 118 | return { connection, listener }; |
| 119 | }), |
| 120 | (subscription) => |
| 121 | Effect.sync(() => |
| 122 | subscription?.connection.removeEventListener("change", subscription.listener), |
| 123 | ), |
| 124 | ).pipe(Effect.asVoid), |
| 125 | ); |
| 126 | |
| 127 | const layerWakeups = Wakeups.layer({ |
| 128 | changes: Stream.mergeAll( |
| 129 | [ |
| 130 | Stream.callback<"application-active">((queue) => |
| 131 | Effect.acquireRelease( |
| 132 | Effect.sync(() => { |
| 133 | const listener = () => { |
| 134 | if (document.visibilityState === "visible") { |
| 135 | Queue.offerUnsafe(queue, "application-active"); |
| 136 | } |
| 137 | }; |
| 138 | document.addEventListener("visibilitychange", listener); |
| 139 | return listener; |
| 140 | }), |
| 141 | (listener) => |
| 142 | Effect.sync(() => { |
| 143 | document.removeEventListener("visibilitychange", listener); |
| 144 | }), |
| 145 | ).pipe(Effect.asVoid), |
| 146 | ), |
| 147 | // A window left visible beside another app never fires visibilitychange when refocused. |
| 148 | Stream.callback<"application-focused">((queue) => |
| 149 | Effect.acquireRelease( |
| 150 | Effect.sync(() => { |
| 151 | const listener = () => { |
| 152 | if (document.visibilityState === "visible") { |
| 153 | Queue.offerUnsafe(queue, "application-focused"); |
| 154 | } |
| 155 | }; |
| 156 | window.addEventListener("focus", listener); |
| 157 | return listener; |
| 158 | }), |
| 159 | (listener) => |
| 160 | Effect.sync(() => { |
| 161 | window.removeEventListener("focus", listener); |
| 162 | }), |
| 163 | ).pipe(Effect.asVoid), |
| 164 | ), |
| 165 | managedRelayAccountChanges(appAtomRegistry).pipe( |
| 166 | Stream.map(() => "credentials-changed" as const), |
| 167 | ), |
| 168 | networkPathChanges, |
| 169 | ], |
| 170 | { concurrency: "unbounded" }, |
| 171 | ), |
| 172 | }); |
| 173 | |
| 174 | export function currentClientMetadata() { |
| 175 | return clientPresentationMetadata({ |
| 176 | appVersion: APP_VERSION, |
| 177 | hosted: isHostedStaticApp(), |
| 178 | identity: { |
| 179 | userAgent: navigator.userAgent, |
| 180 | platform: navigator.platform, |
| 181 | maxTouchPoints: navigator.maxTouchPoints, |
| 182 | }, |
| 183 | desktopBridge: window.desktopBridge, |
| 184 | }); |
| 185 | } |
| 186 | |
| 187 | function sshPreparationError(cause: unknown) { |
| 188 | const message = cause instanceof Error ? cause.message : String(cause); |
| 189 | if (message.toLowerCase().includes("cancel")) { |
| 190 | return new ConnectionBlockedError({ |
| 191 | reason: "authentication", |
| 192 | detail: message, |
| 193 | }); |
| 194 | } |
| 195 | return new ConnectionTransientError({ |
| 196 | reason: "remote-unavailable", |
| 197 | detail: m(msg("Could not prepare the SSH environment: {message}", { message })), |
| 198 | }); |
| 199 | } |
| 200 | |
| 201 | // IPC keeps running after its waiter is interrupted. A retry can adopt only |
| 202 | // that interrupted waiter's unfinished setup. |
| 203 | const pendingSshSetups = new Map< |
| 204 | string, |
| 205 | { readonly promise: Promise<DesktopSshEnvironmentBootstrap>; signal: AbortSignal } |
| 206 | >(); |
| 207 | |
| 208 | const ensureDesktopSshEnvironment = (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) => |
| 209 | Effect.tryPromise({ |
| 210 | try: (signal) => { |
| 211 | const key = sshTargetKey(target); |
| 212 | const pending = pendingSshSetups.get(key); |
| 213 | if (pending?.signal.aborted) { |
| 214 | pending.signal = signal; |
| 215 | return pending.promise; |
| 216 | } |
| 217 | const setup = { |
| 218 | promise: bridge.ensureSshEnvironment(target, { issuePairingToken: true }), |
| 219 | signal, |
| 220 | }; |
| 221 | pendingSshSetups.set(key, setup); |
| 222 | const forget = () => { |
| 223 | if (pendingSshSetups.get(key) === setup) pendingSshSetups.delete(key); |
| 224 | }; |
| 225 | setup.promise.then(forget, forget); |
| 226 | return setup.promise; |
| 227 | }, |
| 228 | catch: sshPreparationError, |
| 229 | }); |
| 230 | |
| 231 | export const provisionDesktopSshEnvironment = Effect.fn( |
| 232 | "web.connectionPlatform.ssh.provisionDesktop", |
| 233 | )(function* ( |
| 234 | bridge: DesktopBridge, |
| 235 | target: DesktopSshEnvironmentTarget, |
| 236 | expectedEnvironmentId?: EnvironmentId, |
| 237 | ) { |
| 238 | const bootstrap = yield* ensureDesktopSshEnvironment(bridge, target); |
| 239 | const pairingToken = bootstrap.pairingToken; |
| 240 | if (pairingToken === null) { |
| 241 | return yield* new ConnectionBlockedError({ |
| 242 | reason: "authentication", |
| 243 | detail: m(msg("The SSH environment did not issue a pairing credential.")), |
| 244 | }); |
| 245 | } |
| 246 | const descriptor = yield* Effect.tryPromise({ |
| 247 | try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl), |
| 248 | catch: sshPreparationError, |
| 249 | }); |
| 250 | if (expectedEnvironmentId !== undefined && descriptor.environmentId !== expectedEnvironmentId) { |
| 251 | return yield* new ConnectionBlockedError({ |
| 252 | reason: "configuration", |
| 253 | detail: m( |
| 254 | msg( |
| 255 | "That host reaches {label}, a different machine. Add it as its own environment instead.", |
| 256 | { label: descriptor.label }, |
| 257 | ), |
| 258 | ), |
| 259 | }); |
| 260 | } |
| 261 | const access = yield* Effect.tryPromise({ |
| 262 | try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken), |
| 263 | catch: (cause) => { |
| 264 | const error = sshPreparationError(cause); |
| 265 | // A reused remote server on another build can fail to decode the grant |
| 266 | // the desktop's runner just minted, and answers 500 on every retry. |
| 267 | if ( |
| 268 | error._tag === "ConnectionBlockedError" || |
| 269 | descriptor.serverVersion === APP_VERSION || |
| 270 | !error.detail.includes("[ssh_http:500]") |
| 271 | ) { |
| 272 | return error; |
| 273 | } |
| 274 | return new ConnectionBlockedError({ |
| 275 | reason: "configuration", |
| 276 | detail: m( |
| 277 | msg( |
| 278 | "{label} runs T3 Code {serverVersion}, but this desktop is {appVersion}, and that server could not accept its pairing. Restart the T3 server on {label} so it runs {appVersion}, then retry.", |
| 279 | { |
| 280 | label: descriptor.label, |
| 281 | serverVersion: descriptor.serverVersion, |
| 282 | appVersion: APP_VERSION, |
| 283 | }, |
| 284 | ), |
| 285 | ), |
| 286 | }); |
| 287 | }, |
| 288 | }); |
| 289 | return { |
| 290 | environmentId: descriptor.environmentId, |
| 291 | label: descriptor.label, |
| 292 | bootstrap, |
| 293 | bearerToken: access.access_token, |
| 294 | }; |
| 295 | }); |
| 296 | |
| 297 | /** Reuses SSH pairing tokens with all standard scopes to avoid adding a session on each connection. */ |
| 298 | export const prepareDesktopSshEnvironment = Effect.fn("web.connectionPlatform.ssh.prepareDesktop")( |
| 299 | function* ( |
| 300 | bridge: DesktopBridge, |
| 301 | input: { |
| 302 | readonly target: DesktopSshEnvironmentTarget; |
| 303 | readonly expectedEnvironmentId: EnvironmentId; |
| 304 | readonly bearerToken?: string; |
| 305 | }, |
| 306 | ) { |
| 307 | const bearerToken = input.bearerToken; |
| 308 | if (bearerToken !== undefined) { |
| 309 | const bootstrap = yield* Effect.tryPromise({ |
| 310 | try: () => bridge.ensureSshEnvironment(input.target, { issuePairingToken: false }), |
| 311 | catch: sshPreparationError, |
| 312 | }); |
| 313 | // Check identity before sending saved credentials or pairing. |
| 314 | const descriptor = yield* Effect.tryPromise({ |
| 315 | try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl), |
| 316 | catch: sshPreparationError, |
| 317 | }); |
| 318 | if (descriptor.environmentId !== input.expectedEnvironmentId) { |
| 319 | return yield* new ConnectionBlockedError({ |
| 320 | reason: "configuration", |
| 321 | detail: m( |
| 322 | msg( |
| 323 | "That host reaches {label}, a different machine. Add it as its own environment instead.", |
| 324 | { label: descriptor.label }, |
| 325 | ), |
| 326 | ), |
| 327 | }); |
| 328 | } |
| 329 | const session = yield* Effect.tryPromise({ |
| 330 | try: () => bridge.fetchSshSessionState(bootstrap.httpBaseUrl, bearerToken), |
| 331 | catch: sshPreparationError, |
| 332 | }); |
| 333 | // Stored grants never widen; re-pair tokens missing newer standard scopes. |
| 334 | const granted = session.permissions ?? session.scopes ?? []; |
| 335 | if ( |
| 336 | session.authenticated && |
| 337 | AuthStandardClientScopes.every((scope) => granted.includes(scope)) |
| 338 | ) { |
| 339 | return { bootstrap, bearerToken }; |
| 340 | } |
| 341 | } |
| 342 | const provisioned = yield* provisionDesktopSshEnvironment( |
| 343 | bridge, |
| 344 | input.target, |
| 345 | input.expectedEnvironmentId, |
| 346 | ); |
| 347 | return { bootstrap: provisioned.bootstrap, bearerToken: provisioned.bearerToken }; |
| 348 | }, |
| 349 | ); |
| 350 | |
| 351 | const ANALYTICS_DEVICE_ID_KEY = "t3code:analytics-device-id"; |
| 352 | |
| 353 | // Lives as long as this browser profile's site data. Storage can be blocked, which only drops the id. |
| 354 | const analyticsDevice = { |
| 355 | id: Effect.sync( |
| 356 | Option.liftThrowable(() => { |
| 357 | const existing = window.localStorage.getItem(ANALYTICS_DEVICE_ID_KEY); |
| 358 | if (existing) return existing; |
| 359 | const created = randomUUID(); |
| 360 | window.localStorage.setItem(ANALYTICS_DEVICE_ID_KEY, created); |
| 361 | return created; |
| 362 | }), |
| 363 | ), |
| 364 | }; |
| 365 | |
| 366 | const layerCapabilities = Layer.effectContext( |
| 367 | Effect.sync(() => { |
| 368 | const presentation = ClientCapabilities.ClientPresentation.of({ |
| 369 | metadata: currentClientMetadata(), |
| 370 | }); |
| 371 | const cloudSession = ClientCapabilities.CloudSession.of({ |
| 372 | identity: Effect.sync(() => |
| 373 | Option.fromNullishOr(appAtomRegistry.get(managedRelaySessionAtom)), |
| 374 | ), |
| 375 | clerkToken: Effect.gen(function* () { |
| 376 | const session = appAtomRegistry.get(managedRelaySessionAtom); |
| 377 | if (session === null) { |
| 378 | return yield* new ConnectionBlockedError({ |
| 379 | reason: "authentication", |
| 380 | detail: m(msg("Sign in to T3 Connect to connect this environment.")), |
| 381 | }); |
| 382 | } |
| 383 | const token = yield* session.readClerkToken().pipe( |
| 384 | Effect.mapError( |
| 385 | (error) => |
| 386 | new ConnectionTransientError({ |
| 387 | reason: "network", |
| 388 | detail: error.message, |
| 389 | }), |
| 390 | ), |
| 391 | ); |
| 392 | if (token === null) { |
| 393 | return yield* new ConnectionBlockedError({ |
| 394 | reason: "authentication", |
| 395 | detail: m(msg("The T3 Connect session is unavailable.")), |
| 396 | }); |
| 397 | } |
| 398 | return token; |
| 399 | }), |
| 400 | }); |
| 401 | const identity = ClientCapabilities.RelayDeviceIdentity.of({ |
| 402 | deviceId: Effect.succeedNone, |
| 403 | }); |
| 404 | const primaryAuth = ClientCapabilities.PrimaryEnvironmentAuth.of({ |
| 405 | bearerToken: Effect.tryPromise({ |
| 406 | try: readDesktopPrimaryBearerToken, |
| 407 | catch: (cause) => |
| 408 | new ConnectionTransientError({ |
| 409 | reason: "remote-unavailable", |
| 410 | detail: m( |
| 411 | msg("Could not load the desktop primary credential: {cause}", { |
| 412 | cause: String(cause), |
| 413 | }), |
| 414 | ), |
| 415 | }), |
| 416 | }).pipe(Effect.map(Option.fromNullishOr)), |
| 417 | }); |
| 418 | const ssh = ClientCapabilities.SshEnvironmentGateway.of({ |
| 419 | provision: Effect.fn("web.connectionPlatform.ssh.provision")( |
| 420 | function* (target, expectedEnvironmentId) { |
| 421 | const bridge = window.desktopBridge; |
| 422 | if (bridge === undefined) { |
| 423 | return yield* new ConnectionBlockedError({ |
| 424 | reason: "unsupported", |
| 425 | detail: m(msg("SSH environments are only available in the desktop app.")), |
| 426 | }); |
| 427 | } |
| 428 | return yield* provisionDesktopSshEnvironment(bridge, target, expectedEnvironmentId); |
| 429 | }, |
| 430 | ), |
| 431 | prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) { |
| 432 | const bridge = window.desktopBridge; |
| 433 | if (bridge === undefined) { |
| 434 | return yield* new ConnectionBlockedError({ |
| 435 | reason: "unsupported", |
| 436 | detail: m(msg("SSH environments are only available in the desktop app.")), |
| 437 | }); |
| 438 | } |
| 439 | return yield* prepareDesktopSshEnvironment(bridge, input); |
| 440 | }), |
| 441 | disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) { |
| 442 | const bridge = window.desktopBridge; |
| 443 | if (bridge === undefined) { |
| 444 | return; |
| 445 | } |
| 446 | pendingSshSetups.delete(sshTargetKey(target)); |
| 447 | yield* Effect.tryPromise({ |
| 448 | try: () => bridge.disconnectSshEnvironment(target), |
| 449 | catch: (cause) => |
| 450 | new ConnectionTransientError({ |
| 451 | reason: "remote-unavailable", |
| 452 | detail: m( |
| 453 | msg("Could not disconnect the SSH environment: {cause}", { cause: String(cause) }), |
| 454 | ), |
| 455 | }), |
| 456 | }); |
| 457 | }), |
| 458 | }); |
| 459 | |
| 460 | return Context.make(ClientCapabilities.CloudSession, cloudSession).pipe( |
| 461 | Context.add(ClientCapabilities.AnalyticsDevice, analyticsDevice), |
| 462 | Context.add(ClientCapabilities.PrimaryEnvironmentAuth, primaryAuth), |
| 463 | Context.add(ClientCapabilities.RelayDeviceIdentity, identity), |
| 464 | Context.add(ClientCapabilities.ClientPresentation, presentation), |
| 465 | Context.add(ClientCapabilities.SshEnvironmentGateway, ssh), |
| 466 | ); |
| 467 | }), |
| 468 | ); |
| 469 | |
| 470 | const loadPrimaryConnectionRegistration = Effect.fn( |
| 471 | "web.connectionPlatform.loadPrimaryConnectionRegistration", |
| 472 | )(function* (resolved: PrimaryEnvironmentTarget) { |
| 473 | const descriptor = yield* fetchRemoteEnvironmentDescriptor({ |
| 474 | httpBaseUrl: resolved.target.httpBaseUrl, |
| 475 | }).pipe( |
| 476 | Effect.provide(PrimaryEnvironmentHttpLayer.layer), |
| 477 | Effect.mapError(mapRemoteEnvironmentError), |
| 478 | ); |
| 479 | return new PrimaryConnectionRegistration({ |
| 480 | target: new PrimaryConnectionTarget({ |
| 481 | environmentId: descriptor.environmentId, |
| 482 | label: descriptor.label, |
| 483 | httpBaseUrl: resolved.target.httpBaseUrl, |
| 484 | wsBaseUrl: resolved.target.wsBaseUrl, |
| 485 | }), |
| 486 | }); |
| 487 | }); |
| 488 | |
| 489 | const loadSecondaryConnectionRegistration = Effect.fn( |
| 490 | "web.connectionPlatform.loadSecondaryConnectionRegistration", |
| 491 | )(function* (entry: DesktopEnvironmentBootstrap) { |
| 492 | if ( |
| 493 | entry.httpBaseUrl === null || |
| 494 | entry.wsBaseUrl === null || |
| 495 | entry.bootstrapToken === undefined |
| 496 | ) { |
| 497 | return yield* new ConnectionTransientError({ |
| 498 | reason: "endpoint-unavailable", |
| 499 | detail: m(msg("Desktop-local backend {id} is not ready yet.", { id: entry.id })), |
| 500 | }); |
| 501 | } |
| 502 | const httpBaseUrl = entry.httpBaseUrl; |
| 503 | const wsBaseUrl = entry.wsBaseUrl; |
| 504 | const descriptor = yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe( |
| 505 | Effect.mapError(mapRemoteEnvironmentError), |
| 506 | ); |
| 507 | const issuedAtEpochMs = yield* Clock.currentTimeMillis; |
| 508 | const access = yield* bootstrapRemoteBearerSession({ |
| 509 | httpBaseUrl, |
| 510 | credential: entry.bootstrapToken, |
| 511 | scopes: AuthStandardClientScopes, |
| 512 | clientMetadata: currentClientMetadata(), |
| 513 | }).pipe(Effect.mapError(mapRemoteEnvironmentError)); |
| 514 | // Desktop operations need the pool backend id to reach the owning instance; RPC uses the environment id. |
| 515 | const connectionId = desktopLocalConnectionId(entry.id); |
| 516 | const label = entry.label || descriptor.label; |
| 517 | return { |
| 518 | registration: new BearerConnectionRegistration({ |
| 519 | target: new BearerConnectionTarget({ |
| 520 | environmentId: descriptor.environmentId, |
| 521 | label, |
| 522 | connectionId, |
| 523 | }), |
| 524 | profile: new BearerConnectionProfile({ |
| 525 | connectionId, |
| 526 | environmentId: descriptor.environmentId, |
| 527 | label, |
| 528 | httpBaseUrl, |
| 529 | wsBaseUrl, |
| 530 | }), |
| 531 | credential: new BearerConnectionCredential({ token: access.access_token }), |
| 532 | }), |
| 533 | expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, access.expires_in), |
| 534 | refreshAtEpochMs: secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, access.expires_in), |
| 535 | }; |
| 536 | }); |
| 537 | |
| 538 | // The bridge has no topology event. Cache registrations until bearer credentials near expiry. |
| 539 | const PLATFORM_POLL_INTERVAL = "3 seconds"; |
| 540 | const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000; |
| 541 | |
| 542 | function secondaryBearerExpiresAtEpochMs( |
| 543 | issuedAtEpochMs: number, |
| 544 | expiresInSeconds: number, |
| 545 | ): number { |
| 546 | return issuedAtEpochMs + Math.max(0, expiresInSeconds * 1_000); |
| 547 | } |
| 548 | |
| 549 | function secondaryBearerRefreshAtEpochMs( |
| 550 | issuedAtEpochMs: number, |
| 551 | expiresInSeconds: number, |
| 552 | ): number { |
| 553 | return Math.max( |
| 554 | issuedAtEpochMs, |
| 555 | secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, expiresInSeconds) - |
| 556 | SECONDARY_BEARER_REFRESH_SKEW_MS, |
| 557 | ); |
| 558 | } |
| 559 | |
| 560 | interface CachedPlatformRegistration { |
| 561 | readonly signature: string; |
| 562 | readonly registration: PlatformConnectionRegistration; |
| 563 | readonly expiresAtEpochMs?: number; |
| 564 | readonly refreshAtEpochMs?: number; |
| 565 | readonly bootstrapToken?: string; |
| 566 | } |
| 567 | |
| 568 | export type PrimaryEnvironmentTargetRead = |
| 569 | | { |
| 570 | readonly _tag: "Success"; |
| 571 | readonly target: PrimaryEnvironmentTarget | null; |
| 572 | } |
| 573 | | { |
| 574 | readonly _tag: "Failure"; |
| 575 | readonly cause: unknown; |
| 576 | }; |
| 577 | |
| 578 | function readPrimaryEnvironmentTargetResult( |
| 579 | readTarget: () => PrimaryEnvironmentTarget | null = readPrimaryEnvironmentTarget, |
| 580 | ): PrimaryEnvironmentTargetRead { |
| 581 | try { |
| 582 | return { _tag: "Success", target: readTarget() }; |
| 583 | } catch (cause) { |
| 584 | return { _tag: "Failure", cause }; |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | export function primaryRegistrationToRetainAfterTopologyRead( |
| 589 | previous: ReadonlyMap<string, CachedPlatformRegistration>, |
| 590 | topologyRead: PrimaryEnvironmentTargetRead, |
| 591 | ): CachedPlatformRegistration | undefined { |
| 592 | return topologyRead._tag === "Failure" ? previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID) : undefined; |
| 593 | } |
| 594 | |
| 595 | export function canReuseCachedPlatformRegistration( |
| 596 | cached: CachedPlatformRegistration, |
| 597 | signature: string, |
| 598 | nowEpochMs: number, |
| 599 | ): boolean { |
| 600 | return ( |
| 601 | cached.signature === signature && |
| 602 | (cached.refreshAtEpochMs === undefined || nowEpochMs < cached.refreshAtEpochMs) |
| 603 | ); |
| 604 | } |
| 605 | |
| 606 | export function canRetainCachedPlatformRegistrationAfterRefreshFailure( |
| 607 | cached: CachedPlatformRegistration, |
| 608 | signature: string, |
| 609 | nowEpochMs: number, |
| 610 | ): boolean { |
| 611 | return ( |
| 612 | cached.signature === signature && |
| 613 | cached.expiresAtEpochMs !== undefined && |
| 614 | nowEpochMs < cached.expiresAtEpochMs |
| 615 | ); |
| 616 | } |
| 617 | |
| 618 | const REJECTED_BOOTSTRAP_RETRY_INITIAL_MS = 60_000; |
| 619 | const REJECTED_BOOTSTRAP_RETRY_MAX_MS = 30 * 60_000; |
| 620 | |
| 621 | export interface RejectedSecondaryBootstrap { |
| 622 | readonly signature: string; |
| 623 | readonly retryAtEpochMs: number; |
| 624 | readonly delayMs: number; |
| 625 | } |
| 626 | |
| 627 | /** Retry with backoff: a backend can restart on the same port with a fresh grant and no topology change. */ |
| 628 | export function isRejectedSecondaryBootstrap( |
| 629 | rejected: RejectedSecondaryBootstrap | undefined, |
| 630 | signature: string, |
| 631 | nowEpochMs: number, |
| 632 | ): rejected is RejectedSecondaryBootstrap { |
| 633 | return ( |
| 634 | rejected !== undefined && |
| 635 | rejected.signature === signature && |
| 636 | nowEpochMs < rejected.retryAtEpochMs |
| 637 | ); |
| 638 | } |
| 639 | |
| 640 | export function nextRejectedSecondaryBootstrap( |
| 641 | previous: RejectedSecondaryBootstrap | undefined, |
| 642 | signature: string, |
| 643 | nowEpochMs: number, |
| 644 | ): RejectedSecondaryBootstrap { |
| 645 | const delayMs = |
| 646 | previous?.signature === signature |
| 647 | ? Math.min(previous.delayMs * 2, REJECTED_BOOTSTRAP_RETRY_MAX_MS) |
| 648 | : REJECTED_BOOTSTRAP_RETRY_INITIAL_MS; |
| 649 | return { signature, retryAtEpochMs: nowEpochMs + delayMs, delayMs }; |
| 650 | } |
| 651 | |
| 652 | export function isRejectedBootstrapCredentialError(error: ConnectionAttemptError): boolean { |
| 653 | return error._tag === "ConnectionBlockedError" && error.reason === "authentication"; |
| 654 | } |
| 655 | |
| 656 | export function secondaryRegistrationsToRetainAfterTopologyRead( |
| 657 | previous: ReadonlyMap<string, CachedPlatformRegistration>, |
| 658 | topologyRead: DesktopSecondaryBootstrapsRead, |
| 659 | nowEpochMs: number, |
| 660 | ): ReadonlyMap<string, CachedPlatformRegistration> { |
| 661 | if (topologyRead._tag === "Success") { |
| 662 | return new Map(); |
| 663 | } |
| 664 | return new Map( |
| 665 | [...previous].filter( |
| 666 | ([, cached]) => cached.expiresAtEpochMs !== undefined && nowEpochMs < cached.expiresAtEpochMs, |
| 667 | ), |
| 668 | ); |
| 669 | } |
| 670 | |
| 671 | const layerPlatformConnectionSource = Layer.effect( |
| 672 | PlatformConnectionSource.PlatformConnectionSource, |
| 673 | Effect.gen(function* () { |
| 674 | if (isHostedStaticApp() || isLocalEnvironmentDisabled()) { |
| 675 | return PlatformConnectionSource.PlatformConnectionSource.of({ |
| 676 | registrations: Stream.empty, |
| 677 | }); |
| 678 | } |
| 679 | const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>()); |
| 680 | const rejectedRef = yield* Ref.make(new Map<string, RejectedSecondaryBootstrap>()); |
| 681 | |
| 682 | const buildPlatformRegistrations = Effect.gen(function* () { |
| 683 | const previous = yield* Ref.get(cacheRef); |
| 684 | const nowEpochMs = yield* Clock.currentTimeMillis; |
| 685 | const next = new Map<string, CachedPlatformRegistration>(); |
| 686 | const registrations: Array<PlatformConnectionRegistration> = []; |
| 687 | |
| 688 | const primaryTopologyRead = readPrimaryEnvironmentTargetResult(); |
| 689 | const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead( |
| 690 | previous, |
| 691 | primaryTopologyRead, |
| 692 | ); |
| 693 | if (retainedPrimary !== undefined) { |
| 694 | next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, retainedPrimary); |
| 695 | registrations.push(retainedPrimary.registration); |
| 696 | } |
| 697 | |
| 698 | if (primaryTopologyRead._tag === "Failure") { |
| 699 | yield* Effect.logWarning("Could not read the primary environment topology.", { |
| 700 | cause: primaryTopologyRead.cause, |
| 701 | }); |
| 702 | } else if (primaryTopologyRead.target !== null) { |
| 703 | const primaryTarget = primaryTopologyRead.target; |
| 704 | const signature = `primary|${primaryTarget.target.httpBaseUrl}|${primaryTarget.target.wsBaseUrl}`; |
| 705 | const cached = previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID); |
| 706 | if ( |
| 707 | cached !== undefined && |
| 708 | canReuseCachedPlatformRegistration(cached, signature, nowEpochMs) |
| 709 | ) { |
| 710 | next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached); |
| 711 | registrations.push(cached.registration); |
| 712 | } else { |
| 713 | const built = yield* loadPrimaryConnectionRegistration(primaryTarget).pipe( |
| 714 | Effect.tapError((error) => |
| 715 | Effect.logWarning("Could not discover the primary environment.", { error }), |
| 716 | ), |
| 717 | Effect.option, |
| 718 | ); |
| 719 | if (Option.isSome(built)) { |
| 720 | const cacheEntry = { signature, registration: built.value }; |
| 721 | next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry); |
| 722 | registrations.push(built.value); |
| 723 | } |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | const topologyRead = readDesktopSecondaryBootstrapsResult(); |
| 728 | for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead( |
| 729 | previous, |
| 730 | topologyRead, |
| 731 | nowEpochMs, |
| 732 | )) { |
| 733 | next.set(id, cached); |
| 734 | registrations.push(cached.registration); |
| 735 | } |
| 736 | |
| 737 | if (topologyRead._tag === "Failure") { |
| 738 | yield* Effect.logWarning("Could not read the desktop-local backend topology.", { |
| 739 | cause: topologyRead.cause, |
| 740 | }); |
| 741 | } else { |
| 742 | const rejected = yield* Ref.get(rejectedRef); |
| 743 | const nextRejected = new Map<string, RejectedSecondaryBootstrap>(); |
| 744 | for (const bootstrap of topologyRead.bootstraps) { |
| 745 | // Token rotation only controls exchange retries; dropping endpoint bearers also clears drafts. |
| 746 | const endpointSignature = `${bootstrap.httpBaseUrl}|${bootstrap.wsBaseUrl}`; |
| 747 | const signature = `${endpointSignature}|${bootstrap.bootstrapToken ?? ""}`; |
| 748 | const cached = previous.get(bootstrap.id); |
| 749 | // Rotation may mean a restart; retain the old bearer if the new exchange fails. |
| 750 | if ( |
| 751 | cached !== undefined && |
| 752 | cached.bootstrapToken === bootstrap.bootstrapToken && |
| 753 | canReuseCachedPlatformRegistration(cached, endpointSignature, nowEpochMs) |
| 754 | ) { |
| 755 | next.set(bootstrap.id, cached); |
| 756 | registrations.push(cached.registration); |
| 757 | continue; |
| 758 | } |
| 759 | const previouslyRejected = rejected.get(bootstrap.id); |
| 760 | if (isRejectedSecondaryBootstrap(previouslyRejected, signature, nowEpochMs)) { |
| 761 | nextRejected.set(bootstrap.id, previouslyRejected); |
| 762 | if ( |
| 763 | cached !== undefined && |
| 764 | canRetainCachedPlatformRegistrationAfterRefreshFailure( |
| 765 | cached, |
| 766 | endpointSignature, |
| 767 | nowEpochMs, |
| 768 | ) |
| 769 | ) { |
| 770 | next.set(bootstrap.id, cached); |
| 771 | registrations.push(cached.registration); |
| 772 | } |
| 773 | continue; |
| 774 | } |
| 775 | const built = yield* loadSecondaryConnectionRegistration(bootstrap).pipe( |
| 776 | Effect.tapError((error) => |
| 777 | Effect.logWarning("Could not connect a desktop-local backend.", { |
| 778 | id: bootstrap.id, |
| 779 | error, |
| 780 | }), |
| 781 | ), |
| 782 | Effect.tapError((error) => |
| 783 | isRejectedBootstrapCredentialError(error) |
| 784 | ? // Start backoff at rejection; this poll can outlast the first delay. |
| 785 | Clock.currentTimeMillis.pipe( |
| 786 | Effect.map((rejectedAtEpochMs) => |
| 787 | nextRejected.set( |
| 788 | bootstrap.id, |
| 789 | nextRejectedSecondaryBootstrap( |
| 790 | previouslyRejected, |
| 791 | signature, |
| 792 | rejectedAtEpochMs, |
| 793 | ), |
| 794 | ), |
| 795 | ), |
| 796 | ) |
| 797 | : Effect.void, |
| 798 | ), |
| 799 | Effect.option, |
| 800 | ); |
| 801 | if (Option.isSome(built)) { |
| 802 | const cacheEntry = { |
| 803 | signature: endpointSignature, |
| 804 | ...(bootstrap.bootstrapToken === undefined |
| 805 | ? {} |
| 806 | : { bootstrapToken: bootstrap.bootstrapToken }), |
| 807 | ...built.value, |
| 808 | }; |
| 809 | next.set(bootstrap.id, cacheEntry); |
| 810 | registrations.push(built.value.registration); |
| 811 | } else if ( |
| 812 | cached !== undefined && |
| 813 | canRetainCachedPlatformRegistrationAfterRefreshFailure( |
| 814 | cached, |
| 815 | endpointSignature, |
| 816 | nowEpochMs, |
| 817 | ) |
| 818 | ) { |
| 819 | next.set(bootstrap.id, cached); |
| 820 | registrations.push(cached.registration); |
| 821 | } |
| 822 | } |
| 823 | yield* Ref.set(rejectedRef, nextRejected); |
| 824 | } |
| 825 | |
| 826 | yield* Ref.set(cacheRef, next); |
| 827 | return registrations as ReadonlyArray<PlatformConnectionRegistration>; |
| 828 | }).pipe(Effect.provide(FetchHttpClient.layer)); |
| 829 | |
| 830 | return PlatformConnectionSource.PlatformConnectionSource.of({ |
| 831 | registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe( |
| 832 | Stream.mapEffect(() => buildPlatformRegistrations), |
| 833 | ), |
| 834 | }); |
| 835 | }), |
| 836 | ); |
| 837 | |
| 838 | const layerEnvironmentOwnedDataCleanup = Layer.succeed( |
| 839 | Persistence.EnvironmentOwnedDataCleanup, |
| 840 | Persistence.EnvironmentOwnedDataCleanup.of({ |
| 841 | clear: Effect.fn("Persistence.EnvironmentOwnedDataCleanup.clear")(function (environmentId) { |
| 842 | return Effect.sync(() => { |
| 843 | clearComposerDraftsEnvironment(environmentId); |
| 844 | }); |
| 845 | }), |
| 846 | }), |
| 847 | ); |
| 848 | |
| 849 | const layerRpcRequestObserver = Layer.succeed( |
| 850 | EnvironmentRpcRequestObserver, |
| 851 | EnvironmentRpcRequestObserver.of({ |
| 852 | // Every RPC passes through this observer; the request owns its span. |
| 853 | observe: Effect.fnUntraced(function* ({ environmentId, environmentLabel, method }) { |
| 854 | return yield* Effect.sync(() => { |
| 855 | nextObservedRpcRequestId += 1; |
| 856 | const requestId = `${environmentId}:${nextObservedRpcRequestId}`; |
| 857 | trackRpcRequestSent(requestId, method, `${method} · ${environmentLabel}`); |
| 858 | return Effect.sync(() => { |
| 859 | acknowledgeRpcRequest(requestId); |
| 860 | }); |
| 861 | }); |
| 862 | }), |
| 863 | }), |
| 864 | ); |
| 865 | |
| 866 | type ConnectionPlatformLayerSource = |
| 867 | | typeof ConnectionStorage.layer |
| 868 | | typeof layerConnectivity |
| 869 | | typeof layerWakeups |
| 870 | | typeof layerCapabilities |
| 871 | | typeof layerPlatformConnectionSource |
| 872 | | typeof layerEnvironmentOwnedDataCleanup |
| 873 | | typeof layerRpcRequestObserver; |
| 874 | |
| 875 | export const layer: Layer.Layer< |
| 876 | Layer.Success<ConnectionPlatformLayerSource>, |
| 877 | Layer.Error<ConnectionPlatformLayerSource>, |
| 878 | Layer.Services<ConnectionPlatformLayerSource> |
| 879 | > = Layer.mergeAll( |
| 880 | ConnectionStorage.layer, |
| 881 | layerConnectivity, |
| 882 | layerWakeups, |
| 883 | layerCapabilities, |
| 884 | layerPlatformConnectionSource, |
| 885 | layerEnvironmentOwnedDataCleanup, |
| 886 | layerRpcRequestObserver, |
| 887 | ); |