The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { msg } from "gt-i18n"; |
| 2 | import { MarkedText, messageFromError, translatableMessage } from "../errors/translatable.ts"; |
| 3 | import type { EnvironmentId } from "@t3tools/contracts"; |
| 4 | import { decodeRelayJwt } from "@t3tools/shared/relayJwt"; |
| 5 | import * as Cause from "effect/Cause"; |
| 6 | import * as Clock from "effect/Clock"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Option from "effect/Option"; |
| 9 | import * as Schema from "effect/Schema"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; |
| 12 | |
| 13 | import { findErrorTraceId } from "../errors/errorTrace.ts"; |
| 14 | import * as ManagedRelay from "./managedRelay.ts"; |
| 15 | import { relayProtectedErrorText } from "./errorPresentation.ts"; |
| 16 | |
| 17 | const DEFAULT_STALE_TIME_MS = 15_000; |
| 18 | const DEFAULT_IDLE_TTL_MS = 5 * 60_000; |
| 19 | const CLERK_TOKEN_EXPIRY_SKEW_MS = 5_000; |
| 20 | // Clerk retries a failed token request itself, but waits 3 s before the first |
| 21 | // retry and longer before each next one. A fresh request usually answers at |
| 22 | // once, so a slow read is replaced instead of waited out. |
| 23 | const CLERK_TOKEN_READ_TIMEOUT_MS = 4_000; |
| 24 | const CLERK_TOKEN_READ_ATTEMPTS = 3; |
| 25 | const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError); |
| 26 | |
| 27 | export interface ManagedRelaySession { |
| 28 | readonly accountId: string; |
| 29 | readonly readClerkToken: () => Effect.Effect<string | null, ManagedRelaySessionError>; |
| 30 | } |
| 31 | |
| 32 | export interface ManagedRelaySessionInput { |
| 33 | readonly accountId: string; |
| 34 | readonly readClerkToken: () => Promise<string | null>; |
| 35 | } |
| 36 | |
| 37 | interface ManagedRelaySessionControl { |
| 38 | readonly updateReadClerkToken: ( |
| 39 | readClerkToken: ManagedRelaySessionInput["readClerkToken"], |
| 40 | ) => void; |
| 41 | } |
| 42 | |
| 43 | export interface ManagedRelaySnapshotState<A> { |
| 44 | readonly data: A | null; |
| 45 | readonly error: string | null; |
| 46 | /** `error` as marked text, when the failure carries it. */ |
| 47 | readonly i18nError?: MarkedText; |
| 48 | readonly errorTraceId: string | null; |
| 49 | readonly isPending: boolean; |
| 50 | } |
| 51 | |
| 52 | export interface ManagedRelayQueryEvent { |
| 53 | readonly operation: "environments" | "devices" | "t3chat-link"; |
| 54 | readonly stage: "clerk-token" | "relay-request"; |
| 55 | readonly phase: "start" | "success" | "failure"; |
| 56 | readonly accountId: string; |
| 57 | readonly environmentId?: string; |
| 58 | readonly message?: string; |
| 59 | readonly traceId?: string | null; |
| 60 | } |
| 61 | |
| 62 | export class ManagedRelaySessionError extends Schema.TaggedError<ManagedRelaySessionError>()( |
| 63 | "ManagedRelaySessionError", |
| 64 | { |
| 65 | message: Schema.String, |
| 66 | i18nMessage: Schema.optionalKey(MarkedText), |
| 67 | cause: Schema.optional(Schema.Defect()), |
| 68 | }, |
| 69 | ) {} |
| 70 | |
| 71 | export const managedRelaySessionAtom = Atom.make<ManagedRelaySession | null>(null).pipe( |
| 72 | Atom.keepAlive, |
| 73 | Atom.withLabel("managed-relay:session"), |
| 74 | ); |
| 75 | |
| 76 | const managedRelaySessionControls = new WeakMap<ManagedRelaySession, ManagedRelaySessionControl>(); |
| 77 | |
| 78 | export function createManagedRelaySession(input: ManagedRelaySessionInput): ManagedRelaySession { |
| 79 | let cachedToken: { readonly token: string; readonly expiresAtMillis: number } | null = null; |
| 80 | let pendingToken: { |
| 81 | readonly operation: Promise<string | null>; |
| 82 | readonly startedAtMillis: number; |
| 83 | } | null = null; |
| 84 | let readClerkToken = input.readClerkToken; |
| 85 | let tokenProviderGeneration = 0; |
| 86 | |
| 87 | const readCachedClerkToken = async (nowMillis: number): Promise<string | null> => { |
| 88 | if (cachedToken && cachedToken.expiresAtMillis > nowMillis + CLERK_TOKEN_EXPIRY_SKEW_MS) { |
| 89 | return cachedToken.token; |
| 90 | } |
| 91 | // A read that outlived its timeout is left running, since it still fills |
| 92 | // the cache, but later readers start a fresh one instead of joining it. |
| 93 | if (pendingToken && nowMillis - pendingToken.startedAtMillis < CLERK_TOKEN_READ_TIMEOUT_MS) { |
| 94 | return await pendingToken.operation; |
| 95 | } |
| 96 | |
| 97 | const operationGeneration = tokenProviderGeneration; |
| 98 | const operation = readClerkToken().then((token) => { |
| 99 | if (operationGeneration !== tokenProviderGeneration) { |
| 100 | return token; |
| 101 | } |
| 102 | if (!token) { |
| 103 | cachedToken = null; |
| 104 | return null; |
| 105 | } |
| 106 | const expiresAtSeconds = Effect.runSync( |
| 107 | decodeRelayJwt(token).pipe( |
| 108 | Effect.map((claims) => claims.exp), |
| 109 | Effect.orElseSucceed(() => undefined), |
| 110 | ), |
| 111 | ); |
| 112 | cachedToken = |
| 113 | typeof expiresAtSeconds === "number" |
| 114 | ? { token, expiresAtMillis: expiresAtSeconds * 1_000 } |
| 115 | : null; |
| 116 | return token; |
| 117 | }); |
| 118 | const pending = { operation, startedAtMillis: nowMillis }; |
| 119 | pendingToken = pending; |
| 120 | try { |
| 121 | return await operation; |
| 122 | } finally { |
| 123 | if (pendingToken === pending) { |
| 124 | pendingToken = null; |
| 125 | } |
| 126 | } |
| 127 | }; |
| 128 | |
| 129 | const session: ManagedRelaySession = { |
| 130 | accountId: input.accountId, |
| 131 | readClerkToken: Effect.fn("clientRuntime.managedRelaySession.readClerkToken")(function* () { |
| 132 | for (let attempt = 0; attempt < CLERK_TOKEN_READ_ATTEMPTS; attempt += 1) { |
| 133 | const nowMillis = yield* Clock.currentTimeMillis; |
| 134 | const token = yield* Effect.tryPromise({ |
| 135 | try: () => readCachedClerkToken(nowMillis), |
| 136 | catch: (cause) => |
| 137 | new ManagedRelaySessionError({ |
| 138 | ...translatableMessage(msg("Could not obtain the T3 Connect session token.")), |
| 139 | cause, |
| 140 | }), |
| 141 | }).pipe(Effect.timeoutOption(CLERK_TOKEN_READ_TIMEOUT_MS)); |
| 142 | if (Option.isSome(token)) return token.value; |
| 143 | } |
| 144 | return yield* new ManagedRelaySessionError( |
| 145 | translatableMessage(msg("Timed out obtaining the T3 Connect session token.")), |
| 146 | ); |
| 147 | }), |
| 148 | }; |
| 149 | managedRelaySessionControls.set(session, { |
| 150 | updateReadClerkToken: (nextReadClerkToken) => { |
| 151 | readClerkToken = nextReadClerkToken; |
| 152 | tokenProviderGeneration += 1; |
| 153 | pendingToken = null; |
| 154 | }, |
| 155 | }); |
| 156 | return session; |
| 157 | } |
| 158 | |
| 159 | export function setManagedRelaySession( |
| 160 | registry: AtomRegistry.AtomRegistry, |
| 161 | input: ManagedRelaySessionInput | null, |
| 162 | ): void { |
| 163 | const current = registry.get(managedRelaySessionAtom); |
| 164 | if (input === null) { |
| 165 | if (current !== null) { |
| 166 | registry.set(managedRelaySessionAtom, null); |
| 167 | } |
| 168 | return; |
| 169 | } |
| 170 | if (current?.accountId === input.accountId) { |
| 171 | const control = managedRelaySessionControls.get(current); |
| 172 | if (control) { |
| 173 | // Clerk can replace its token reader during routine same-account refreshes. |
| 174 | // Keep the session stable so those refreshes do not invalidate queries or reconnect leases. |
| 175 | control.updateReadClerkToken(input.readClerkToken); |
| 176 | return; |
| 177 | } |
| 178 | } |
| 179 | registry.set(managedRelaySessionAtom, createManagedRelaySession(input)); |
| 180 | } |
| 181 | |
| 182 | export function managedRelayAccountChanges( |
| 183 | registry: AtomRegistry.AtomRegistry, |
| 184 | ): Stream.Stream<string | null> { |
| 185 | return AtomRegistry.toStream(registry, managedRelaySessionAtom).pipe( |
| 186 | Stream.map((session) => session?.accountId ?? null), |
| 187 | Stream.changes, |
| 188 | Stream.drop(1), |
| 189 | ); |
| 190 | } |
| 191 | |
| 192 | function readSessionClerkToken( |
| 193 | session: ManagedRelaySession, |
| 194 | ): Effect.Effect<string, ManagedRelaySessionError> { |
| 195 | return session.readClerkToken().pipe( |
| 196 | Effect.filterOrFail( |
| 197 | (token): token is string => Boolean(token), |
| 198 | () => |
| 199 | new ManagedRelaySessionError( |
| 200 | translatableMessage(msg("The T3 Connect session token is unavailable.")), |
| 201 | ), |
| 202 | ), |
| 203 | ); |
| 204 | } |
| 205 | |
| 206 | const SIGN_IN_BEFORE = { |
| 207 | deregister: msg("Sign in to T3 Connect before deregistering an environment."), |
| 208 | "link-t3chat": msg("Sign in to T3 Connect before linking T3 Chat."), |
| 209 | "unlink-t3chat": msg("Sign in to T3 Connect before unlinking T3 Chat."), |
| 210 | }; |
| 211 | |
| 212 | function requireSessionClerkToken( |
| 213 | registry: AtomRegistry.AtomRegistry, |
| 214 | accountId: string, |
| 215 | action: "deregister" | "link-t3chat" | "unlink-t3chat", |
| 216 | ): Effect.Effect<string, ManagedRelaySessionError> { |
| 217 | const session = registry.get(managedRelaySessionAtom); |
| 218 | if (!session || session.accountId !== accountId) { |
| 219 | return Effect.fail(new ManagedRelaySessionError(translatableMessage(SIGN_IN_BEFORE[action]))); |
| 220 | } |
| 221 | return readSessionClerkToken(session); |
| 222 | } |
| 223 | |
| 224 | export const deregisterManagedRelayEnvironment = Effect.fn( |
| 225 | "clientRuntime.managedRelaySession.deregisterEnvironment", |
| 226 | )(function* ( |
| 227 | registry: AtomRegistry.AtomRegistry, |
| 228 | input: { readonly accountId: string; readonly environmentId: EnvironmentId }, |
| 229 | ) { |
| 230 | const clerkToken = yield* requireSessionClerkToken(registry, input.accountId, "deregister"); |
| 231 | const relay = yield* ManagedRelay.ManagedRelayClient; |
| 232 | yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId }); |
| 233 | }); |
| 234 | |
| 235 | /** Returns the T3 Chat page URL where the signed-in user confirms the link. */ |
| 236 | export const createManagedRelayT3ChatLinkRequest = Effect.fn( |
| 237 | "clientRuntime.managedRelaySession.createT3ChatLinkRequest", |
| 238 | )(function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) { |
| 239 | const clerkToken = yield* requireSessionClerkToken(registry, input.accountId, "link-t3chat"); |
| 240 | const relay = yield* ManagedRelay.ManagedRelayClient; |
| 241 | return (yield* relay.createT3ChatLinkRequest({ clerkToken })).url; |
| 242 | }); |
| 243 | |
| 244 | export const unlinkManagedRelayT3Chat = Effect.fn("clientRuntime.managedRelaySession.unlinkT3Chat")( |
| 245 | function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) { |
| 246 | const clerkToken = yield* requireSessionClerkToken(registry, input.accountId, "unlink-t3chat"); |
| 247 | const relay = yield* ManagedRelay.ManagedRelayClient; |
| 248 | yield* relay.unlinkT3Chat({ clerkToken }); |
| 249 | }, |
| 250 | ); |
| 251 | |
| 252 | function requireClerkToken( |
| 253 | get: Atom.AtomContext, |
| 254 | accountId: string, |
| 255 | ): Effect.Effect<string, ManagedRelaySessionError> { |
| 256 | const session = get(managedRelaySessionAtom); |
| 257 | if (!session || session.accountId !== accountId) { |
| 258 | return Effect.fail( |
| 259 | new ManagedRelaySessionError( |
| 260 | translatableMessage(msg("Sign in to T3 Connect before loading relay data.")), |
| 261 | ), |
| 262 | ); |
| 263 | } |
| 264 | return readSessionClerkToken(session); |
| 265 | } |
| 266 | |
| 267 | function describeManagedRelayFailure(cause: Cause.Cause<unknown>): { |
| 268 | readonly message: string; |
| 269 | readonly i18nMessage?: MarkedText; |
| 270 | readonly traceId: string | null; |
| 271 | } { |
| 272 | const error = Cause.squash(cause); |
| 273 | const traceId = findErrorTraceId(error); |
| 274 | if (isManagedRelayRequestFailedError(error) && error.relayError) { |
| 275 | return { ...translatableMessage(...relayProtectedErrorText(error.relayError)), traceId }; |
| 276 | } |
| 277 | return error instanceof Error |
| 278 | ? { ...messageFromError(error), traceId } |
| 279 | : { ...translatableMessage(msg("Could not load T3 Connect data.")), traceId }; |
| 280 | } |
| 281 | |
| 282 | export function readManagedRelaySnapshotState<A>( |
| 283 | result: AsyncResult.AsyncResult<A, unknown>, |
| 284 | ): ManagedRelaySnapshotState<A> { |
| 285 | const failure = result._tag === "Failure" ? describeManagedRelayFailure(result.cause) : null; |
| 286 | return { |
| 287 | data: AsyncResult.getOrElse(result, () => null), |
| 288 | error: failure?.message ?? null, |
| 289 | ...(failure?.i18nMessage !== undefined ? { i18nError: failure.i18nMessage } : {}), |
| 290 | errorTraceId: failure?.traceId ?? null, |
| 291 | isPending: result.waiting, |
| 292 | }; |
| 293 | } |
| 294 | |
| 295 | // Logged where the listing runs so each failed fetch reports once, however many |
| 296 | // components read the atom. |
| 297 | const logListingFailure = |
| 298 | (label: string) => |
| 299 | <A, E, R>(self: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => |
| 300 | self.pipe( |
| 301 | Effect.tapCause((cause) => { |
| 302 | if (Cause.hasInterruptsOnly(cause)) return Effect.void; |
| 303 | const { message, traceId } = describeManagedRelayFailure(cause); |
| 304 | return Effect.logError(`[t3-cloud] Relay ${label} listing failed`).pipe( |
| 305 | Effect.annotateLogs({ message, traceId }), |
| 306 | ); |
| 307 | }), |
| 308 | ); |
| 309 | |
| 310 | export function createManagedRelayQueryManager( |
| 311 | runtime: Atom.AtomRuntime<ManagedRelay.ManagedRelayClient>, |
| 312 | options?: { |
| 313 | readonly staleTimeMs?: number; |
| 314 | readonly idleTtlMs?: number; |
| 315 | readonly onQueryEvent?: (event: ManagedRelayQueryEvent) => void; |
| 316 | }, |
| 317 | ) { |
| 318 | const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS; |
| 319 | const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS; |
| 320 | const observe = Effect.fn("managedRelayState.observe")(function* <A, E, R>( |
| 321 | input: Omit<ManagedRelayQueryEvent, "phase" | "message" | "traceId">, |
| 322 | effect: Effect.Effect<A, E, R>, |
| 323 | ): Effect.fn.Return<A, E, R> { |
| 324 | options?.onQueryEvent?.({ ...input, phase: "start" }); |
| 325 | return yield* effect.pipe( |
| 326 | Effect.onExit((exit) => |
| 327 | Effect.sync(() => { |
| 328 | if (exit._tag === "Success") { |
| 329 | options?.onQueryEvent?.({ ...input, phase: "success" }); |
| 330 | return; |
| 331 | } |
| 332 | const error = Cause.squash(exit.cause); |
| 333 | options?.onQueryEvent?.({ |
| 334 | ...input, |
| 335 | phase: "failure", |
| 336 | message: error instanceof Error ? error.message : String(error), |
| 337 | traceId: findErrorTraceId(error), |
| 338 | }); |
| 339 | }), |
| 340 | ), |
| 341 | ); |
| 342 | }); |
| 343 | |
| 344 | const environmentsAtom = Atom.family((accountId: string) => |
| 345 | runtime |
| 346 | .atom((get) => |
| 347 | Effect.gen(function* () { |
| 348 | const base = { operation: "environments" as const, accountId }; |
| 349 | const clerkToken = yield* observe( |
| 350 | { ...base, stage: "clerk-token" }, |
| 351 | requireClerkToken(get, accountId), |
| 352 | ); |
| 353 | const relay = yield* ManagedRelay.ManagedRelayClient; |
| 354 | return yield* observe( |
| 355 | { ...base, stage: "relay-request" }, |
| 356 | relay.listEnvironments({ clerkToken }), |
| 357 | ); |
| 358 | }).pipe(logListingFailure("environment")), |
| 359 | ) |
| 360 | .pipe( |
| 361 | Atom.swr({ staleTime, revalidateOnMount: true }), |
| 362 | Atom.setIdleTTL(idleTtl), |
| 363 | Atom.withLabel(`managed-relay:environments:${accountId}`), |
| 364 | ), |
| 365 | ); |
| 366 | |
| 367 | const devicesAtom = Atom.family((accountId: string) => |
| 368 | runtime |
| 369 | .atom((get) => |
| 370 | Effect.gen(function* () { |
| 371 | const base = { operation: "devices" as const, accountId }; |
| 372 | const clerkToken = yield* observe( |
| 373 | { ...base, stage: "clerk-token" }, |
| 374 | requireClerkToken(get, accountId), |
| 375 | ); |
| 376 | const relay = yield* ManagedRelay.ManagedRelayClient; |
| 377 | return yield* observe( |
| 378 | { ...base, stage: "relay-request" }, |
| 379 | relay.listDevices({ clerkToken }), |
| 380 | ); |
| 381 | }).pipe(logListingFailure("device")), |
| 382 | ) |
| 383 | .pipe( |
| 384 | Atom.swr({ staleTime, revalidateOnMount: true }), |
| 385 | Atom.setIdleTTL(idleTtl), |
| 386 | Atom.withLabel(`managed-relay:devices:${accountId}`), |
| 387 | ), |
| 388 | ); |
| 389 | |
| 390 | const t3ChatLinkAtom = Atom.family((accountId: string) => |
| 391 | runtime |
| 392 | .atom((get) => |
| 393 | Effect.gen(function* () { |
| 394 | const base = { operation: "t3chat-link" as const, accountId }; |
| 395 | const clerkToken = yield* observe( |
| 396 | { ...base, stage: "clerk-token" }, |
| 397 | requireClerkToken(get, accountId), |
| 398 | ); |
| 399 | const relay = yield* ManagedRelay.ManagedRelayClient; |
| 400 | return yield* observe( |
| 401 | { ...base, stage: "relay-request" }, |
| 402 | relay.getT3ChatLink({ clerkToken }), |
| 403 | ); |
| 404 | }), |
| 405 | ) |
| 406 | .pipe( |
| 407 | Atom.swr({ staleTime, revalidateOnMount: true }), |
| 408 | Atom.setIdleTTL(idleTtl), |
| 409 | Atom.withLabel(`managed-relay:t3chat-link:${accountId}`), |
| 410 | ), |
| 411 | ); |
| 412 | |
| 413 | return { |
| 414 | environmentsAtom, |
| 415 | devicesAtom, |
| 416 | t3ChatLinkAtom, |
| 417 | refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void { |
| 418 | registry.refresh(environmentsAtom(accountId)); |
| 419 | }, |
| 420 | refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void { |
| 421 | registry.refresh(devicesAtom(accountId)); |
| 422 | }, |
| 423 | refreshT3ChatLink(registry: AtomRegistry.AtomRegistry, accountId: string): void { |
| 424 | registry.refresh(t3ChatLinkAtom(accountId)); |
| 425 | }, |
| 426 | }; |
| 427 | } |