Open History to see the last commit
1import {
2 ClientPresentation,
3 CloudSession,
4 EnvironmentOwnedDataCleanup,
5 PlatformConnectionSource,
6 PrimaryEnvironmentAuth,
7 RelayDeviceIdentity,
8 SshEnvironmentGateway,
9} from "@t3tools/client-runtime/platform";
10import {
11 BearerConnectionCredential,
12 BearerConnectionProfile,
13 BearerConnectionRegistration,
14 BearerConnectionTarget,
15 ConnectionBlockedError,
16 ConnectionTransientError,
17 Connectivity,
18 mapRemoteEnvironmentError,
19 type PlatformConnectionRegistration,
20 PrimaryConnectionRegistration,
21 PrimaryConnectionTarget,
22 ResyncRequests,
23 Wakeups,
24} from "@t3tools/client-runtime/connection";
25import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
26import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
27import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
28import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
29import {
30 AuthStandardClientScopes,
31 type DesktopBridge,
32 type DesktopEnvironmentBootstrap,
33 type DesktopSshEnvironmentTarget,
34 PRIMARY_LOCAL_ENVIRONMENT_ID,
35} from "@t3tools/contracts";
36import * as Clock from "effect/Clock";
37import * as Context from "effect/Context";
38import * as Effect from "effect/Effect";
39import * as Layer from "effect/Layer";
40import * as Option from "effect/Option";
41import * as Queue from "effect/Queue";
42import * as Ref from "effect/Ref";
43import * as Stream from "effect/Stream";
44import { FetchHttpClient } from "effect/unstable/http";
45
46import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
47import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
48import {
49 readPrimaryEnvironmentTarget,
50 type PrimaryEnvironmentTarget,
51} from "../environments/primary/target";
52import { clearComposerDraftsEnvironment } from "../composerDraftStore";
53import { isHostedStaticApp } from "../hostedPairing";
54import { appAtomRegistry } from "../rpc/atomRegistry";
55import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";
56import {
57 desktopLocalConnectionId,
58 readDesktopSecondaryBootstrapsResult,
59 type DesktopSecondaryBootstrapsRead,
60} from "./desktopLocal";
61import { connectionStorageLayer } from "./storage";
62
63let nextObservedRpcRequestId = 0;
64
65function currentNetworkStatus(): "unknown" | "offline" | "online" {
66 if (typeof navigator === "undefined") {
67 return "unknown";
68 }
69 return navigator.onLine ? "online" : "offline";
70}
71
72const connectivityLayer = Connectivity.layer({
73 status: Effect.sync(currentNetworkStatus),
74 changes: Stream.callback((queue) =>
75 Effect.acquireRelease(
76 Effect.sync(() => {
77 const online = () => Queue.offerUnsafe(queue, "online");
78 const offline = () => Queue.offerUnsafe(queue, "offline");
79 window.addEventListener("online", online);
80 window.addEventListener("offline", offline);
81 return { online, offline };
82 }),
83 ({ online, offline }) =>
84 Effect.sync(() => {
85 window.removeEventListener("online", online);
86 window.removeEventListener("offline", offline);
87 }),
88 ).pipe(Effect.asVoid),
89 ),
90});
91
92const wakeupsLayer = Wakeups.layer({
93 changes: Stream.merge(
94 Stream.callback<"application-active">((queue) =>
95 Effect.acquireRelease(
96 Effect.sync(() => {
97 const listener = () => {
98 if (document.visibilityState === "visible") {
99 Queue.offerUnsafe(queue, "application-active");
100 }
101 };
102 document.addEventListener("visibilitychange", listener);
103 return listener;
104 }),
105 (listener) =>
106 Effect.sync(() => {
107 document.removeEventListener("visibilitychange", listener);
108 }),
109 ).pipe(Effect.asVoid),
110 ),
111 managedRelayAccountChanges(appAtomRegistry).pipe(
112 Stream.map(() => "credentials-changed" as const),
113 ),
114 ).pipe(Stream.merge(ResyncRequests.resyncRequestStream)),
115});
116
117function clientMetadata() {
118 const desktop = window.desktopBridge !== undefined;
119 const platform = navigator.platform.trim();
120 return {
121 label: desktop ? "T3 Code Desktop" : "T3 Code Web",
122 deviceType: "desktop" as const,
123 ...(platform === "" ? {} : { os: platform }),
124 };
125}
126
127function sshPreparationError(cause: unknown) {
128 const message = cause instanceof Error ? cause.message : String(cause);
129 if (message.toLowerCase().includes("cancel")) {
130 return new ConnectionBlockedError({
131 reason: "authentication",
132 detail: message,
133 });
134 }
135 return new ConnectionTransientError({
136 reason: "remote-unavailable",
137 detail: `Could not prepare the SSH environment: ${message}`,
138 });
139}
140
141export const provisionDesktopSshEnvironment = Effect.fn(
142 "web.connectionPlatform.ssh.provisionDesktop",
143)(function* (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) {
144 const bootstrap = yield* Effect.tryPromise({
145 try: () =>
146 bridge.ensureSshEnvironment(target, {
147 issuePairingToken: true,
148 }),
149 catch: sshPreparationError,
150 });
151 const pairingToken = bootstrap.pairingToken;
152 if (pairingToken === null) {
153 return yield* new ConnectionBlockedError({
154 reason: "authentication",
155 detail: "The SSH environment did not issue a pairing credential.",
156 });
157 }
158 const descriptor = yield* Effect.tryPromise({
159 try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
160 catch: sshPreparationError,
161 });
162 const access = yield* Effect.tryPromise({
163 try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
164 catch: sshPreparationError,
165 });
166 return {
167 environmentId: descriptor.environmentId,
168 label: descriptor.label,
169 bootstrap,
170 bearerToken: access.access_token,
171 };
172});
173
174const capabilitiesLayer = Layer.effectContext(
175 Effect.sync(() => {
176 const presentation = ClientPresentation.of({
177 metadata: clientMetadata(),
178 scopes: AuthStandardClientScopes,
179 });
180 const cloudSession = CloudSession.of({
181 clerkToken: Effect.gen(function* () {
182 const session = appAtomRegistry.get(managedRelaySessionAtom);
183 if (session === null) {
184 return yield* new ConnectionBlockedError({
185 reason: "authentication",
186 detail: "Sign in to T3 Connect to connect this environment.",
187 });
188 }
189 const token = yield* session.readClerkToken().pipe(
190 Effect.mapError(
191 (error) =>
192 new ConnectionTransientError({
193 reason: "network",
194 detail: error.message,
195 }),
196 ),
197 );
198 if (token === null) {
199 return yield* new ConnectionBlockedError({
200 reason: "authentication",
201 detail: "The T3 Connect session is unavailable.",
202 });
203 }
204 return token;
205 }),
206 });
207 const identity = RelayDeviceIdentity.of({
208 deviceId: Effect.succeed(Option.none()),
209 });
210 const primaryAuth = PrimaryEnvironmentAuth.of({
211 bearerToken: Effect.tryPromise({
212 try: readDesktopPrimaryBearerToken,
213 catch: (cause) =>
214 new ConnectionTransientError({
215 reason: "remote-unavailable",
216 detail: `Could not load the desktop primary credential: ${String(cause)}`,
217 }),
218 }).pipe(Effect.map(Option.fromNullishOr)),
219 });
220 const ssh = SshEnvironmentGateway.of({
221 provision: Effect.fn("web.connectionPlatform.ssh.provision")(function* (target) {
222 const bridge = window.desktopBridge;
223 if (bridge === undefined) {
224 return yield* new ConnectionBlockedError({
225 reason: "unsupported",
226 detail: "SSH environments are only available in the desktop app.",
227 });
228 }
229 return yield* provisionDesktopSshEnvironment(bridge, target);
230 }),
231 prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) {
232 const bridge = window.desktopBridge;
233 if (bridge === undefined) {
234 return yield* new ConnectionBlockedError({
235 reason: "unsupported",
236 detail: "SSH environments are only available in the desktop app.",
237 });
238 }
239 const bootstrap = yield* Effect.tryPromise({
240 try: () =>
241 bridge.ensureSshEnvironment(input.target, {
242 issuePairingToken: true,
243 }),
244 catch: sshPreparationError,
245 });
246 if (bootstrap.pairingToken === null) {
247 return yield* new ConnectionBlockedError({
248 reason: "authentication",
249 detail: "The SSH environment did not issue a pairing credential.",
250 });
251 }
252 const access = yield* Effect.tryPromise({
253 try: () =>
254 bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
255 catch: sshPreparationError,
256 });
257 return {
258 bootstrap,
259 bearerToken: access.access_token,
260 };
261 }),
262 disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
263 const bridge = window.desktopBridge;
264 if (bridge === undefined) {
265 return;
266 }
267 yield* Effect.tryPromise({
268 try: () => bridge.disconnectSshEnvironment(target),
269 catch: (cause) =>
270 new ConnectionTransientError({
271 reason: "remote-unavailable",
272 detail: `Could not disconnect the SSH environment: ${String(cause)}`,
273 }),
274 });
275 }),
276 });
277
278 return Context.make(CloudSession, cloudSession).pipe(
279 Context.add(PrimaryEnvironmentAuth, primaryAuth),
280 Context.add(RelayDeviceIdentity, identity),
281 Context.add(ClientPresentation, presentation),
282 Context.add(SshEnvironmentGateway, ssh),
283 );
284 }),
285);
286
287const loadPrimaryConnectionRegistration = Effect.fn(
288 "web.connectionPlatform.loadPrimaryConnectionRegistration",
289)(function* (resolved: PrimaryEnvironmentTarget) {
290 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
291 httpBaseUrl: resolved.target.httpBaseUrl,
292 }).pipe(Effect.provide(primaryEnvironmentHttpLayer), Effect.mapError(mapRemoteEnvironmentError));
293 return new PrimaryConnectionRegistration({
294 target: new PrimaryConnectionTarget({
295 environmentId: descriptor.environmentId,
296 label: descriptor.label,
297 httpBaseUrl: resolved.target.httpBaseUrl,
298 wsBaseUrl: resolved.target.wsBaseUrl,
299 }),
300 });
301});
302
303// A desktop-local secondary backend (e.g. a parallel WSL backend) lives on its
304// own loopback origin, so — unlike the same-origin primary — it authenticates
305// with a bearer token minted from the bootstrap credential the desktop issues.
306const loadSecondaryConnectionRegistration = Effect.fn(
307 "web.connectionPlatform.loadSecondaryConnectionRegistration",
308)(function* (entry: DesktopEnvironmentBootstrap) {
309 if (
310 entry.httpBaseUrl === null ||
311 entry.wsBaseUrl === null ||
312 entry.bootstrapToken === undefined
313 ) {
314 return yield* new ConnectionTransientError({
315 reason: "endpoint-unavailable",
316 detail: `Desktop-local backend ${entry.id} is not ready yet.`,
317 });
318 }
319 const httpBaseUrl = entry.httpBaseUrl;
320 const wsBaseUrl = entry.wsBaseUrl;
321 const descriptor = yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
322 Effect.mapError(mapRemoteEnvironmentError),
323 );
324 const issuedAtEpochMs = yield* Clock.currentTimeMillis;
325 const access = yield* bootstrapRemoteBearerSession({
326 httpBaseUrl,
327 credential: entry.bootstrapToken,
328 scopes: AuthStandardClientScopes,
329 clientMetadata: clientMetadata(),
330 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
331 // Keep the desktop pool's stable backend id in the connection id. The
332 // descriptor environment id still scopes projects and RPC state, while the
333 // backend id lets desktop-only operations (notably the WSL folder picker)
334 // route back to the instance that owns the environment.
335 const connectionId = desktopLocalConnectionId(entry.id);
336 // Prefer the desktop's bootstrap label (it identifies the backend and distro,
337 // e.g. "WSL: Ubuntu") over the generic descriptor label, so consumers can show
338 // a meaningful name without recovering it from the bootstrap list later.
339 const label = entry.label || descriptor.label;
340 return {
341 registration: new BearerConnectionRegistration({
342 target: new BearerConnectionTarget({
343 environmentId: descriptor.environmentId,
344 label,
345 connectionId,
346 }),
347 profile: new BearerConnectionProfile({
348 connectionId,
349 environmentId: descriptor.environmentId,
350 label,
351 httpBaseUrl,
352 wsBaseUrl,
353 }),
354 credential: new BearerConnectionCredential({ token: access.access_token }),
355 }),
356 expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, access.expires_in),
357 refreshAtEpochMs: secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, access.expires_in),
358 };
359});
360
361// Poll cadence for the desktop bootstrap topology. There is no change event on
362// the bridge, so the renderer polls; successful registrations are cached by a
363// signature of their endpoint + token until bearer credentials approach expiry.
364const PLATFORM_POLL_INTERVAL = "3 seconds";
365const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
366
367export function secondaryBearerExpiresAtEpochMs(
368 issuedAtEpochMs: number,
369 expiresInSeconds: number,
370): number {
371 return issuedAtEpochMs + Math.max(0, expiresInSeconds * 1_000);
372}
373
374export function secondaryBearerRefreshAtEpochMs(
375 issuedAtEpochMs: number,
376 expiresInSeconds: number,
377): number {
378 return Math.max(
379 issuedAtEpochMs,
380 secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, expiresInSeconds) -
381 SECONDARY_BEARER_REFRESH_SKEW_MS,
382 );
383}
384
385interface CachedPlatformRegistration {
386 readonly signature: string;
387 readonly registration: PlatformConnectionRegistration;
388 readonly expiresAtEpochMs?: number;
389 readonly refreshAtEpochMs?: number;
390}
391
392export type PrimaryEnvironmentTargetRead =
393 | {
394 readonly _tag: "Success";
395 readonly target: PrimaryEnvironmentTarget | null;
396 }
397 | {
398 readonly _tag: "Failure";
399 readonly cause: unknown;
400 };
401
402export function readPrimaryEnvironmentTargetResult(
403 readTarget: () => PrimaryEnvironmentTarget | null = readPrimaryEnvironmentTarget,
404): PrimaryEnvironmentTargetRead {
405 try {
406 return { _tag: "Success", target: readTarget() };
407 } catch (cause) {
408 return { _tag: "Failure", cause };
409 }
410}
411
412export function primaryRegistrationToRetainAfterTopologyRead(
413 previous: ReadonlyMap<string, CachedPlatformRegistration>,
414 topologyRead: PrimaryEnvironmentTargetRead,
415): CachedPlatformRegistration | undefined {
416 return topologyRead._tag === "Failure" ? previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID) : undefined;
417}
418
419export function canReuseCachedPlatformRegistration(
420 cached: CachedPlatformRegistration,
421 signature: string,
422 nowEpochMs: number,
423): boolean {
424 return (
425 cached.signature === signature &&
426 (cached.refreshAtEpochMs === undefined || nowEpochMs < cached.refreshAtEpochMs)
427 );
428}
429
430export function canRetainCachedPlatformRegistrationAfterRefreshFailure(
431 cached: CachedPlatformRegistration,
432 signature: string,
433 nowEpochMs: number,
434): boolean {
435 return (
436 cached.signature === signature &&
437 cached.expiresAtEpochMs !== undefined &&
438 nowEpochMs < cached.expiresAtEpochMs
439 );
440}
441
442export function secondaryRegistrationsToRetainAfterTopologyRead(
443 previous: ReadonlyMap<string, CachedPlatformRegistration>,
444 topologyRead: DesktopSecondaryBootstrapsRead,
445 nowEpochMs: number,
446): ReadonlyMap<string, CachedPlatformRegistration> {
447 if (topologyRead._tag === "Success") {
448 return new Map();
449 }
450 return new Map(
451 [...previous].filter(
452 ([, cached]) => cached.expiresAtEpochMs !== undefined && nowEpochMs < cached.expiresAtEpochMs,
453 ),
454 );
455}
456
457const platformConnectionSourceLayer = Layer.effect(
458 PlatformConnectionSource,
459 Effect.gen(function* () {
460 if (isHostedStaticApp()) {
461 return PlatformConnectionSource.of({
462 registrations: Stream.empty,
463 });
464 }
465 const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>());
466
467 // Resolve the full set of platform-managed environments the host currently
468 // reports: the primary (same-origin cookie auth) plus any desktop-local
469 // backends running alongside it (bearer auth). Reused registrations come
470 // from the cache; a failed entry is skipped and retried on the next poll.
471 const buildPlatformRegistrations = Effect.gen(function* () {
472 const previous = yield* Ref.get(cacheRef);
473 const nowEpochMs = yield* Clock.currentTimeMillis;
474 const next = new Map<string, CachedPlatformRegistration>();
475 const registrations: Array<PlatformConnectionRegistration> = [];
476
477 const primaryTopologyRead = readPrimaryEnvironmentTargetResult();
478 const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead(
479 previous,
480 primaryTopologyRead,
481 );
482 if (retainedPrimary !== undefined) {
483 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, retainedPrimary);
484 registrations.push(retainedPrimary.registration);
485 }
486
487 if (primaryTopologyRead._tag === "Failure") {
488 yield* Effect.logWarning("Could not read the primary environment topology.", {
489 cause: primaryTopologyRead.cause,
490 });
491 } else if (primaryTopologyRead.target !== null) {
492 const primaryTarget = primaryTopologyRead.target;
493 const signature = `primary|${primaryTarget.target.httpBaseUrl}|${primaryTarget.target.wsBaseUrl}`;
494 const cached = previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID);
495 if (
496 cached !== undefined &&
497 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
498 ) {
499 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
500 registrations.push(cached.registration);
501 } else {
502 const built = yield* loadPrimaryConnectionRegistration(primaryTarget).pipe(
503 Effect.tapError((error) =>
504 Effect.logWarning("Could not discover the primary environment.", { error }),
505 ),
506 Effect.option,
507 );
508 if (Option.isSome(built)) {
509 const cacheEntry = { signature, registration: built.value };
510 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
511 registrations.push(built.value);
512 }
513 }
514 }
515
516 const topologyRead = readDesktopSecondaryBootstrapsResult();
517 for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
518 previous,
519 topologyRead,
520 nowEpochMs,
521 )) {
522 next.set(id, cached);
523 registrations.push(cached.registration);
524 }
525
526 if (topologyRead._tag === "Failure") {
527 yield* Effect.logWarning("Could not read the desktop-local backend topology.", {
528 cause: topologyRead.cause,
529 });
530 } else {
531 for (const bootstrap of topologyRead.bootstraps) {
532 const signature = `${bootstrap.httpBaseUrl}|${bootstrap.wsBaseUrl}|${bootstrap.bootstrapToken ?? ""}`;
533 const cached = previous.get(bootstrap.id);
534 if (
535 cached !== undefined &&
536 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
537 ) {
538 next.set(bootstrap.id, cached);
539 registrations.push(cached.registration);
540 continue;
541 }
542 const built = yield* loadSecondaryConnectionRegistration(bootstrap).pipe(
543 Effect.tapError((error) =>
544 Effect.logWarning("Could not connect a desktop-local backend.", {
545 id: bootstrap.id,
546 error,
547 }),
548 ),
549 Effect.option,
550 );
551 if (Option.isSome(built)) {
552 const cacheEntry = { signature, ...built.value };
553 next.set(bootstrap.id, cacheEntry);
554 registrations.push(built.value.registration);
555 } else if (
556 cached !== undefined &&
557 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, signature, nowEpochMs)
558 ) {
559 next.set(bootstrap.id, cached);
560 registrations.push(cached.registration);
561 }
562 }
563 }
564
565 yield* Ref.set(cacheRef, next);
566 return registrations as ReadonlyArray<PlatformConnectionRegistration>;
567 }).pipe(Effect.provide(FetchHttpClient.layer));
568
569 return PlatformConnectionSource.of({
570 registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
571 Stream.mapEffect(() => buildPlatformRegistrations),
572 ),
573 });
574 }),
575);
576
577const environmentOwnedDataCleanupLayer = Layer.succeed(
578 EnvironmentOwnedDataCleanup,
579 EnvironmentOwnedDataCleanup.of({
580 clear: (environmentId) =>
581 Effect.sync(() => {
582 clearComposerDraftsEnvironment(environmentId);
583 }),
584 }),
585);
586
587const rpcRequestObserverLayer = Layer.succeed(
588 EnvironmentRpcRequestObserver,
589 EnvironmentRpcRequestObserver.of({
590 observe: ({ environmentId, method }) =>
591 Effect.sync(() => {
592 nextObservedRpcRequestId += 1;
593 const requestId = `${environmentId}:${nextObservedRpcRequestId}`;
594 trackRpcRequestSent(requestId, `${method} · ${environmentId}`);
595 return Effect.sync(() => {
596 acknowledgeRpcRequest(requestId);
597 });
598 }),
599 }),
600);
601
602type ConnectionPlatformLayerSource =
603 | typeof connectionStorageLayer
604 | typeof connectivityLayer
605 | typeof wakeupsLayer
606 | typeof capabilitiesLayer
607 | typeof platformConnectionSourceLayer
608 | typeof environmentOwnedDataCleanupLayer
609 | typeof rpcRequestObserverLayer;
610
611export const connectionPlatformLayer: Layer.Layer<
612 Layer.Success<ConnectionPlatformLayerSource>,
613 Layer.Error<ConnectionPlatformLayerSource>,
614 Layer.Services<ConnectionPlatformLayerSource>
615> = Layer.mergeAll(
616 connectionStorageLayer,
617 connectivityLayer,
618 wakeupsLayer,
619 capabilitiesLayer,
620 platformConnectionSourceLayer,
621 environmentOwnedDataCleanupLayer,
622 rpcRequestObserverLayer,
623);