Skip to content
2 changes: 1 addition & 1 deletion apps/mobile/src/connection/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ const layerCapabilities = Layer.effectContext(
const layerPlatformConnectionSource = Layer.succeed(
PlatformConnectionSource.PlatformConnectionSource,
PlatformConnectionSource.PlatformConnectionSource.of({
registrations: Stream.empty,
snapshots: Stream.succeed({ registrations: [], discoveryComplete: true }),
}),
);

Expand Down
11 changes: 11 additions & 0 deletions apps/web/src/connection/catalog.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
import { createEnvironmentCatalogAtoms } from "@t3tools/client-runtime/state/connections";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";

import { connectionAtomRuntime } from "./runtime";

export const environmentCatalog = createEnvironmentCatalogAtoms(connectionAtomRuntime);

export const entriesAfterPlatformDiscoveryAtom = connectionAtomRuntime.atom(
Stream.unwrap(
EnvironmentRegistry.EnvironmentRegistry.pipe(
Effect.map((registry) => registry.entriesAfterPlatformDiscovery),
),
),
);
39 changes: 24 additions & 15 deletions apps/web/src/connection/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -673,17 +673,18 @@ const layerPlatformConnectionSource = Layer.effect(
Effect.gen(function* () {
if (isHostedStaticApp() || isLocalEnvironmentDisabled()) {
return PlatformConnectionSource.PlatformConnectionSource.of({
registrations: Stream.empty,
snapshots: Stream.succeed({ registrations: [], discoveryComplete: true }),
});
}
const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>());
const rejectedRef = yield* Ref.make(new Map<string, RejectedSecondaryBootstrap>());

const buildPlatformRegistrations = Effect.gen(function* () {
const discoverPlatformConnections = Effect.gen(function* () {
const previous = yield* Ref.get(cacheRef);
const nowEpochMs = yield* Clock.currentTimeMillis;
const next = new Map<string, CachedPlatformRegistration>();
const registrations: Array<PlatformConnectionRegistration> = [];
let discoveryComplete = true;

const primaryTopologyRead = readPrimaryEnvironmentTargetResult();
const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead(
Expand All @@ -696,6 +697,7 @@ const layerPlatformConnectionSource = Layer.effect(
}

if (primaryTopologyRead._tag === "Failure") {
discoveryComplete = false;
yield* Effect.logWarning("Could not read the primary environment topology.", {
cause: primaryTopologyRead.cause,
});
Expand All @@ -720,6 +722,8 @@ const layerPlatformConnectionSource = Layer.effect(
const cacheEntry = { signature, registration: built.value };
next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
registrations.push(built.value);
} else {
discoveryComplete = false;
}
}
}
Expand All @@ -735,6 +739,7 @@ const layerPlatformConnectionSource = Layer.effect(
}

if (topologyRead._tag === "Failure") {
discoveryComplete = false;
yield* Effect.logWarning("Could not read the desktop-local backend topology.", {
cause: topologyRead.cause,
});
Expand All @@ -758,6 +763,7 @@ const layerPlatformConnectionSource = Layer.effect(
}
const previouslyRejected = rejected.get(bootstrap.id);
if (isRejectedSecondaryBootstrap(previouslyRejected, signature, nowEpochMs)) {
discoveryComplete = false;
nextRejected.set(bootstrap.id, previouslyRejected);
if (
cached !== undefined &&
Expand Down Expand Up @@ -808,28 +814,31 @@ const layerPlatformConnectionSource = Layer.effect(
};
next.set(bootstrap.id, cacheEntry);
registrations.push(built.value.registration);
} else if (
cached !== undefined &&
canRetainCachedPlatformRegistrationAfterRefreshFailure(
cached,
endpointSignature,
nowEpochMs,
)
) {
next.set(bootstrap.id, cached);
registrations.push(cached.registration);
} else {
discoveryComplete = false;
if (
cached !== undefined &&
canRetainCachedPlatformRegistrationAfterRefreshFailure(
cached,
endpointSignature,
nowEpochMs,
)
) {
next.set(bootstrap.id, cached);
registrations.push(cached.registration);
}
}
}
yield* Ref.set(rejectedRef, nextRejected);
}

yield* Ref.set(cacheRef, next);
return registrations as ReadonlyArray<PlatformConnectionRegistration>;
return { registrations, discoveryComplete };
}).pipe(Effect.provide(FetchHttpClient.layer));

return PlatformConnectionSource.PlatformConnectionSource.of({
registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
Stream.mapEffect(() => buildPlatformRegistrations),
snapshots: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
Stream.mapEffect(() => discoverPlatformConnections),
),
});
}),
Expand Down
50 changes: 35 additions & 15 deletions apps/web/src/providerAuthDelivery.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
import { readCodexAuthDelivery } from "@t3tools/shared/codexAuthHandoff";
import * as Effect from "effect/Effect";
import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
import { msg } from "gt-react";

import { toastManager } from "./components/ui/toast";
import { entriesAfterPlatformDiscoveryAtom } from "./connection/catalog";
import { m } from "./i18n/messages";
import { appAtomRegistry } from "./rpc/atomRegistry";
import { environmentPresentations } from "./state/presentation";
Expand All @@ -25,20 +28,33 @@ export function startProviderAuthDelivery(): void {
);
if (!delivery) return;

const presentationAtom = environmentPresentations.presentationAtom(delivery.environmentId);
if (appAtomRegistry.get(presentationAtom)?.connection.phase === "connected") {
void completeProviderAuth(delivery);
return;
}
const unsubscribe = appAtomRegistry.subscribe(presentationAtom, (presentation) => {
if (presentation?.connection.phase !== "connected") return;
unsubscribe();
void completeProviderAuth(delivery);
});
void completeProviderAuth(delivery);
}

async function completeProviderAuth(delivery: ProviderAuthDelivery): Promise<void> {
const presentationAtom = environmentPresentations.presentationAtom(delivery.environmentId);
const destinationAtom = Atom.make((get) => {
const presentation = get(presentationAtom);
if (presentation === null) {
return AsyncResult.flatMap(get(entriesAfterPlatformDiscoveryAtom), (entries) =>
entries === null || entries.has(delivery.environmentId)
? AsyncResult.initial()
: AsyncResult.success("missing"),
);
}
return presentation.connection.phase === "connected"
? AsyncResult.success("connected")
: AsyncResult.initial();
});

try {
const destination = await Effect.runPromise(
AtomRegistry.getResult(appAtomRegistry, destinationAtom),
);
if (destination === "missing") {
reportUnavailableEnvironment();
return;
}
const result = await runAtomCommand(
appAtomRegistry,
serverEnvironment.completeProviderAuth,
Expand All @@ -60,10 +76,14 @@ async function completeProviderAuth(delivery: ProviderAuthDelivery): Promise<voi
});
}
} catch {
toastManager.add({
type: "error",
title: m(msg("ChatGPT sign-in couldn't finish")),
description: m(msg("Reconnect to the environment and try again.")),
});
reportUnavailableEnvironment();
}
}

function reportUnavailableEnvironment(): void {
toastManager.add({
type: "error",
title: m(msg("ChatGPT sign-in couldn't finish")),
description: m(msg("Reconnect to the environment and try again.")),
});
}
6 changes: 4 additions & 2 deletions packages/client-runtime/src/connection/layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,10 @@ export function layerWithOptions(options: RpcSession.RpcSessionOptions) {
const platformSource = yield* PlatformConnectionSource.PlatformConnectionSource;
yield* watchDiscoveredCompatibility().pipe(Effect.forkScoped);
yield* registry.start;
yield* platformSource.registrations.pipe(
Stream.runForEach(registry.reconcilePlatform),
yield* platformSource.snapshots.pipe(
Stream.runForEach(({ registrations, discoveryComplete }) =>
registry.reconcilePlatform(registrations, discoveryComplete),
),
Effect.forkScoped,
);
}).pipe(Effect.withSpan("clientRuntime.connection.application.start")),
Expand Down
37 changes: 37 additions & 0 deletions packages/client-runtime/src/connection/registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1595,6 +1595,43 @@ describe("EnvironmentRegistry", () => {
}),
);

it.effect("publishes the catalog only once platform discovery completes", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([], [], [], {
beforeCredentialPut: () =>
Effect.fail(
new ConnectionTransientError({
reason: "remote-unavailable",
detail: "Storage unavailable",
}),
),
});

yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
const discoveredNow = registry.entriesAfterPlatformDiscovery.pipe(
Stream.runHead,
Effect.map(Option.getOrThrow),
);
yield* registry.reconcilePlatform([], false);
expect(yield* discoveredNow).toBeNull();

// A failed credential write must not keep discovery pending.
yield* registry.reconcilePlatform([
new BearerConnectionRegistration({
target: BEARER_TARGET,
profile: BEARER_PROFILE,
credential: new BearerConnectionCredential({ token: "platform-bearer" }),
}),
]);

const discovered = yield* discoveredNow;
expect(discovered?.has(BEARER_TARGET.environmentId)).toBe(true);
expect(discovered?.has(TARGET.environmentId)).toBe(false);
}).pipe(Effect.provide(harness.layer), Effect.scoped);
}),
);

it.effect("applies overlapping platform snapshots in order", () =>
Effect.gen(function* () {
const started = yield* Deferred.make<void>();
Expand Down
36 changes: 32 additions & 4 deletions packages/client-runtime/src/connection/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ export class EnvironmentRegistry extends Context.Service<
readonly entries: SubscriptionRef.SubscriptionRef<
ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>
>;
/** Catalog snapshots, with null while platform discovery cannot rule out an unknown target. */
readonly entriesAfterPlatformDiscovery: Stream.Stream<ReadonlyMap<
EnvironmentId,
ConnectionCatalogEntry
> | null>;
readonly networkStatus: SubscriptionRef.SubscriptionRef<NetworkStatus>;
readonly start: Effect.Effect<void>;
/**
Expand All @@ -119,6 +124,7 @@ export class EnvironmentRegistry extends Context.Service<
) => Effect.Effect<void, ConnectionBlockedError>;
readonly reconcilePlatform: (
registrations: ReadonlyArray<PlatformConnectionRegistration>,
discoveryComplete?: boolean,
) => Effect.Effect<void>;
readonly remove: (
environmentId: EnvironmentId,
Expand Down Expand Up @@ -270,6 +276,7 @@ export const make = Effect.gen(function* () {
);
const entries =
yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(initialEntries);
const platformDiscoveryComplete = yield* SubscriptionRef.make(false);
const networkStatus = yield* SubscriptionRef.make(yield* connectivity.status);
const serviceScopes = yield* SubscriptionRef.make<
ReadonlyMap<EnvironmentId, EnvironmentServiceScope>
Expand Down Expand Up @@ -852,11 +859,16 @@ export const make = Effect.gen(function* () {
// span per poll would make idle clients export traces continuously.
const reconcilePlatform = Effect.fnUntraced(function* (
platformRegistrations: ReadonlyArray<PlatformConnectionRegistration>,
discoveryComplete = true,
) {
if (Equal.equals(appliedPlatformRegistrations, platformRegistrations)) return;
appliedPlatformRegistrations = undefined;
if (yield* applyPlatformRegistrations(platformRegistrations)) {
appliedPlatformRegistrations = platformRegistrations;
if (!Equal.equals(appliedPlatformRegistrations, platformRegistrations)) {
appliedPlatformRegistrations = undefined;
if (yield* applyPlatformRegistrations(platformRegistrations)) {
appliedPlatformRegistrations = platformRegistrations;
}
}
if ((yield* SubscriptionRef.get(platformDiscoveryComplete)) !== discoveryComplete) {
yield* SubscriptionRef.set(platformDiscoveryComplete, discoveryComplete);
}
}, reconcileLock.withPermits(1));

Expand Down Expand Up @@ -1196,6 +1208,22 @@ export const make = Effect.gen(function* () {

return EnvironmentRegistry.of({
entries,
entriesAfterPlatformDiscovery: Stream.merge(
SubscriptionRef.changes(entries),
SubscriptionRef.changes(platformDiscoveryComplete),
).pipe(
// A poll can change catalog membership and discovery status together.
Stream.mapEffect(() =>
reconcileLock.withPermits(1)(
SubscriptionRef.get(platformDiscoveryComplete).pipe(
Effect.flatMap((complete) =>
complete ? SubscriptionRef.get(entries) : Effect.succeed(null),
),
),
),
),
Stream.changes,
),
networkStatus,
start,
register,
Expand Down
9 changes: 5 additions & 4 deletions packages/client-runtime/src/platform/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import type { PlatformConnectionRegistration } from "../connection/catalog.ts";
export class PlatformConnectionSource extends Context.Service<
PlatformConnectionSource,
{
// Each emission is the full current set of platform-managed environments
// (the primary local environment plus any desktop-local backends running
// alongside it).
readonly registrations: Stream.Stream<ReadonlyArray<PlatformConnectionRegistration>>;
readonly snapshots: Stream.Stream<{
readonly registrations: ReadonlyArray<PlatformConnectionRegistration>;
/** Every target named by the current platform topology has been resolved. */
readonly discoveryComplete: boolean;
}>;
}
>()("@t3tools/client-runtime/platform/source/PlatformConnectionSource") {}
1 change: 1 addition & 0 deletions packages/client-runtime/src/state/threads-atoms.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?
entries: yield* SubscriptionRef.make<ReadonlyMap<EnvironmentId, ConnectionCatalogEntry>>(
new Map(),
),
entriesAfterPlatformDiscovery: Stream.empty,
networkStatus: yield* SubscriptionRef.make<NetworkStatus>("online"),
start: Effect.void,
register: () => Effect.die("Unexpected environment registration"),
Expand Down
Loading
Loading