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