The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Effect from "effect/Effect"; |
| 2 | import * as Option from "effect/Option"; |
| 3 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 4 | import * as Schema from "effect/Schema"; |
| 5 | import type { HttpClientResponse } from "effect/http"; |
| 6 | import { |
| 7 | EnvironmentCloudEndpointUnavailableError, |
| 8 | EnvironmentHttpBadRequestError, |
| 9 | EnvironmentHttpConflictError, |
| 10 | EnvironmentHttpForbiddenError, |
| 11 | EnvironmentHttpInternalServerError, |
| 12 | EnvironmentHttpUnauthorizedError, |
| 13 | } from "@t3tools/contracts"; |
| 14 | import { |
| 15 | RelayOkResponse, |
| 16 | type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType, |
| 17 | type RelayManagedEndpointProviderKind, |
| 18 | } from "@t3tools/contracts/relay"; |
| 19 | import { EnvironmentSupervisor } from "@t3tools/client-runtime/connection"; |
| 20 | import { findErrorTraceId } from "@t3tools/client-runtime/errors"; |
| 21 | import { ManagedRelay, relayRequestFailureDetail } from "@t3tools/client-runtime/relay"; |
| 22 | |
| 23 | import { executeConnectedEnvironmentHttpRequest } from "@t3tools/client-runtime/state/environmentHttpAuth"; |
| 24 | import { msg } from "gt-react-native"; |
| 25 | |
| 26 | import { m } from "../../i18n/messages"; |
| 27 | import * as MobileStorage from "../../persistence/mobile-storage"; |
| 28 | import { resolveCloudPublicConfig } from "./publicConfig"; |
| 29 | |
| 30 | function readRelayUrl(): string | null { |
| 31 | return resolveCloudPublicConfig().relay.url; |
| 32 | } |
| 33 | |
| 34 | export class CloudEnvironmentLinkError extends Schema.TaggedError<CloudEnvironmentLinkError>()( |
| 35 | "CloudEnvironmentLinkError", |
| 36 | { |
| 37 | message: Schema.String, |
| 38 | cause: Schema.optional(Schema.Defect()), |
| 39 | traceId: Schema.optional(Schema.String), |
| 40 | relayLinkCommitted: Schema.optionalKey(Schema.Literal(true)), |
| 41 | }, |
| 42 | ) {} |
| 43 | |
| 44 | const isEnvironmentCloudApiError = Schema.is( |
| 45 | Schema.Union([ |
| 46 | EnvironmentHttpBadRequestError, |
| 47 | EnvironmentHttpUnauthorizedError, |
| 48 | EnvironmentHttpForbiddenError, |
| 49 | EnvironmentHttpConflictError, |
| 50 | EnvironmentHttpInternalServerError, |
| 51 | EnvironmentCloudEndpointUnavailableError, |
| 52 | ]), |
| 53 | ); |
| 54 | |
| 55 | // Live Activities need only agent activity, so a phone never starts a tunnel on the host. |
| 56 | const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind; |
| 57 | |
| 58 | function cloudEnvironmentLinkError( |
| 59 | message: string, |
| 60 | withDetail: (detail: string) => string, |
| 61 | options?: { readonly relayLinkCommitted: true }, |
| 62 | ) { |
| 63 | return (cause: unknown) => { |
| 64 | const environmentError = findEnvironmentCloudApiError(cause); |
| 65 | const traceId = findErrorTraceId(cause); |
| 66 | const detail = environmentError |
| 67 | ? withDetail(environmentError.message) |
| 68 | : withDevCause(message, cause); |
| 69 | return new CloudEnvironmentLinkError({ |
| 70 | message: detail, |
| 71 | cause, |
| 72 | ...options, |
| 73 | ...(traceId === null ? {} : { traceId }), |
| 74 | }); |
| 75 | }; |
| 76 | } |
| 77 | |
| 78 | function isDevRuntime(): boolean { |
| 79 | return typeof __DEV__ !== "undefined" && __DEV__; |
| 80 | } |
| 81 | |
| 82 | function causeMessage(cause: unknown): string | null { |
| 83 | if (cause instanceof Error && cause.message) { |
| 84 | return cause.message; |
| 85 | } |
| 86 | if (typeof cause === "object" && cause !== null) { |
| 87 | const record = cause as { readonly message?: unknown; readonly cause?: unknown }; |
| 88 | if (typeof record.message === "string" && record.message.length > 0) { |
| 89 | const nested = causeMessage(record.cause); |
| 90 | return nested ? `${record.message}: ${nested}` : record.message; |
| 91 | } |
| 92 | } |
| 93 | return null; |
| 94 | } |
| 95 | |
| 96 | function withDevCause(message: string, cause: unknown): string { |
| 97 | if (!isDevRuntime()) { |
| 98 | return message; |
| 99 | } |
| 100 | const detail = causeMessage(cause); |
| 101 | return detail ? `${message} (${detail})` : message; |
| 102 | } |
| 103 | |
| 104 | function decodedRelayClientError(url: string) { |
| 105 | return (cause: ManagedRelay.ManagedRelayClientError) => { |
| 106 | const failed = cause._tag === "ManagedRelayRequestFailedError" ? cause : undefined; |
| 107 | const traceId = failed?.traceId; |
| 108 | const detail = failed ? relayRequestFailureDetail(failed, m) : null; |
| 109 | return new CloudEnvironmentLinkError({ |
| 110 | message: detail |
| 111 | ? m(msg("{url} failed: {detail}", { url, detail })) |
| 112 | : m(msg("{url} failed", { url })), |
| 113 | cause, |
| 114 | ...(traceId ? { traceId } : {}), |
| 115 | }); |
| 116 | }; |
| 117 | } |
| 118 | |
| 119 | function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null { |
| 120 | if (isEnvironmentCloudApiError(cause)) { |
| 121 | return cause; |
| 122 | } |
| 123 | if (typeof cause !== "object" || cause === null) { |
| 124 | return null; |
| 125 | } |
| 126 | return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null; |
| 127 | } |
| 128 | |
| 129 | function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> { |
| 130 | const relayUrl = readRelayUrl(); |
| 131 | return relayUrl |
| 132 | ? Effect.succeed(relayUrl) |
| 133 | : Effect.fail( |
| 134 | new CloudEnvironmentLinkError({ message: m(msg("Relay URL is not configured.")) }), |
| 135 | ); |
| 136 | } |
| 137 | |
| 138 | function endpointOrigin(httpBaseUrl: string) { |
| 139 | const url = new URL(httpBaseUrl); |
| 140 | return { |
| 141 | localHttpHost: "127.0.0.1", |
| 142 | localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)), |
| 143 | }; |
| 144 | } |
| 145 | |
| 146 | function ensureLinkedEnvironmentMatches(input: { |
| 147 | readonly expectedEnvironmentId: string; |
| 148 | readonly expectedProviderKind: RelayManagedEndpointProviderKind; |
| 149 | readonly link: RelayEnvironmentLinkResponseType; |
| 150 | }): Effect.Effect<void, CloudEnvironmentLinkError> { |
| 151 | if (input.link.environmentId !== input.expectedEnvironmentId) { |
| 152 | return new CloudEnvironmentLinkError({ |
| 153 | message: m(msg("Relay returned credentials for a different environment.")), |
| 154 | }); |
| 155 | } |
| 156 | if (input.link.endpoint.providerKind !== input.expectedProviderKind) { |
| 157 | return new CloudEnvironmentLinkError({ |
| 158 | message: m(msg("Relay returned credentials for a different endpoint provider.")), |
| 159 | }); |
| 160 | } |
| 161 | return Effect.void; |
| 162 | } |
| 163 | |
| 164 | const decodeRelayOkResponse = Schema.decodeUnknownEffect(RelayOkResponse); |
| 165 | |
| 166 | export const updateLinkedEnvironmentLiveActivityPreference = Effect.fn( |
| 167 | "linkEnvironment.updateLinkedEnvironmentLiveActivityPreference", |
| 168 | )(function* (liveActivitiesEnabled: boolean) { |
| 169 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 170 | if (Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))) { |
| 171 | return "disconnected" as const; |
| 172 | } |
| 173 | |
| 174 | return yield* executeConnectedEnvironmentHttpRequest< |
| 175 | "connect", |
| 176 | HttpClientResponse.HttpClientResponse, |
| 177 | unknown, |
| 178 | never |
| 179 | >({ |
| 180 | group: "connect", |
| 181 | method: "POST", |
| 182 | url: (urls) => urls.liveActivityPreference(), |
| 183 | timeoutMs: 8_000, |
| 184 | requestInit: { redirect: "error" }, |
| 185 | isUnauthorizedResponse: (response) => response.status === 401, |
| 186 | request: ({ client, headers }) => |
| 187 | client.liveActivityPreference({ |
| 188 | headers, |
| 189 | payload: { liveActivitiesEnabled }, |
| 190 | responseMode: "response-only", |
| 191 | }), |
| 192 | }).pipe( |
| 193 | Effect.flatMap((response) => |
| 194 | Effect.gen(function* () { |
| 195 | if (response.status === 404) return "unsupported" as const; |
| 196 | if (response.status === 200) { |
| 197 | const json = yield* response.json; |
| 198 | const result = yield* decodeRelayOkResponse(json); |
| 199 | return result.ok ? ("updated" as const) : ("unlinked" as const); |
| 200 | } |
| 201 | return yield* new CloudEnvironmentLinkError({ |
| 202 | message: m(msg("Environment returned HTTP {status}."), { status: response.status }), |
| 203 | }); |
| 204 | }), |
| 205 | ), |
| 206 | Effect.mapError( |
| 207 | cloudEnvironmentLinkError( |
| 208 | m(msg("Could not update the environment's Live Activity preference.")), |
| 209 | (detail) => |
| 210 | m(msg("Could not update the environment's Live Activity preference: {detail}"), { |
| 211 | detail, |
| 212 | }), |
| 213 | ), |
| 214 | ), |
| 215 | ); |
| 216 | }); |
| 217 | |
| 218 | // Linking can install the relay client and start a managed tunnel before it answers. |
| 219 | const CLOUD_LINK_REQUEST_TIMEOUT_MS = 60_000; |
| 220 | |
| 221 | /** Links the supervised environment, signing its requests with this device's own credential. */ |
| 222 | export const linkEnvironmentToCloudWithPreference = Effect.fn( |
| 223 | "linkEnvironment.linkEnvironmentToCloudWithPreference", |
| 224 | )(function* (input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }) { |
| 225 | const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; |
| 226 | const prepared = yield* SubscriptionRef.get(supervisor.prepared); |
| 227 | if (Option.isNone(prepared)) { |
| 228 | return yield* new CloudEnvironmentLinkError({ |
| 229 | message: m(msg("The environment is not connected.")), |
| 230 | }); |
| 231 | } |
| 232 | const { environmentId, httpBaseUrl, target } = prepared.value; |
| 233 | const wsBaseUrl = |
| 234 | target._tag === "PrimaryConnectionTarget" |
| 235 | ? target.wsBaseUrl |
| 236 | : httpBaseUrl.replace(/^http/, "ws"); |
| 237 | const relayUrl = yield* requireRelayUrl(); |
| 238 | // Publishing is a host-local setting, so enable it before committing a link a retry would skip. |
| 239 | yield* executeConnectedEnvironmentHttpRequest({ |
| 240 | group: "connect", |
| 241 | method: "POST", |
| 242 | url: (urls) => urls.preferences(), |
| 243 | timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS, |
| 244 | request: ({ client, headers }) => |
| 245 | client.preferences({ headers, payload: { publishAgentActivity: true } }), |
| 246 | }).pipe( |
| 247 | Effect.mapError( |
| 248 | cloudEnvironmentLinkError(m(msg("Could not turn on agent activity publishing.")), (detail) => |
| 249 | m(msg("Could not turn on agent activity publishing: {detail}", { detail })), |
| 250 | ), |
| 251 | ), |
| 252 | ); |
| 253 | const relayClient = yield* ManagedRelay.ManagedRelayClient; |
| 254 | const storage = yield* MobileStorage.MobileStorage; |
| 255 | const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe( |
| 256 | Effect.mapError( |
| 257 | cloudEnvironmentLinkError(m(msg("Could not load the mobile device id.")), (detail) => |
| 258 | m(msg("Could not load the mobile device id: {detail}", { detail })), |
| 259 | ), |
| 260 | ), |
| 261 | ); |
| 262 | const liveActivitiesEnabled = input.liveActivitiesEnabled; |
| 263 | const challenge = yield* relayClient |
| 264 | .createEnvironmentLinkChallenge({ |
| 265 | clerkToken: input.clerkToken, |
| 266 | payload: { |
| 267 | notificationsEnabled: true, |
| 268 | liveActivitiesEnabled, |
| 269 | managedTunnelsEnabled: false, |
| 270 | }, |
| 271 | }) |
| 272 | .pipe( |
| 273 | Effect.mapError( |
| 274 | decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`), |
| 275 | ), |
| 276 | ); |
| 277 | const proof = yield* executeConnectedEnvironmentHttpRequest({ |
| 278 | group: "connect", |
| 279 | method: "POST", |
| 280 | url: (urls) => urls.linkProof(), |
| 281 | timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS, |
| 282 | request: ({ client, headers }) => |
| 283 | client.linkProof({ |
| 284 | headers, |
| 285 | payload: { |
| 286 | challenge: challenge.challenge, |
| 287 | relayIssuer: relayUrl, |
| 288 | endpoint: { httpBaseUrl, wsBaseUrl, providerKind: PUBLISH_ONLY_PROVIDER_KIND }, |
| 289 | origin: endpointOrigin(httpBaseUrl), |
| 290 | }, |
| 291 | }), |
| 292 | }).pipe( |
| 293 | Effect.mapError( |
| 294 | cloudEnvironmentLinkError(m(msg("Could not obtain environment link proof.")), (detail) => |
| 295 | m(msg("Could not obtain environment link proof: {detail}", { detail })), |
| 296 | ), |
| 297 | ), |
| 298 | ); |
| 299 | const link = yield* relayClient |
| 300 | .linkEnvironment({ |
| 301 | clerkToken: input.clerkToken, |
| 302 | payload: { |
| 303 | deviceId, |
| 304 | proof, |
| 305 | notificationsEnabled: true, |
| 306 | liveActivitiesEnabled, |
| 307 | managedTunnelsEnabled: false, |
| 308 | }, |
| 309 | }) |
| 310 | .pipe( |
| 311 | Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)), |
| 312 | ); |
| 313 | yield* ensureLinkedEnvironmentMatches({ |
| 314 | expectedEnvironmentId: environmentId, |
| 315 | expectedProviderKind: PUBLISH_ONLY_PROVIDER_KIND, |
| 316 | link, |
| 317 | }); |
| 318 | |
| 319 | yield* executeConnectedEnvironmentHttpRequest({ |
| 320 | group: "connect", |
| 321 | method: "POST", |
| 322 | url: (urls) => urls.relayConfig(), |
| 323 | timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS, |
| 324 | request: ({ client, headers }) => |
| 325 | client.relayConfig({ |
| 326 | headers, |
| 327 | payload: { |
| 328 | relayUrl, |
| 329 | relayIssuer: link.relayIssuer, |
| 330 | cloudUserId: link.cloudUserId, |
| 331 | environmentCredential: link.environmentCredential, |
| 332 | cloudMintPublicKey: link.cloudMintPublicKey, |
| 333 | endpointRuntime: link.endpointRuntime, |
| 334 | }, |
| 335 | }), |
| 336 | }).pipe( |
| 337 | Effect.mapError( |
| 338 | cloudEnvironmentLinkError( |
| 339 | m(msg("Could not configure environment relay access.")), |
| 340 | (detail) => m(msg("Could not configure environment relay access: {detail}", { detail })), |
| 341 | { relayLinkCommitted: true }, |
| 342 | ), |
| 343 | ), |
| 344 | ); |
| 345 | }); |