diff --git a/apps/mobile/src/connection/platform.ts b/apps/mobile/src/connection/platform.ts index 12d6bafe7c953..da2ab9a333c78 100644 --- a/apps/mobile/src/connection/platform.ts +++ b/apps/mobile/src/connection/platform.ts @@ -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 }), }), ); diff --git a/apps/web/src/connection/catalog.ts b/apps/web/src/connection/catalog.ts index 971fa891106fc..2e093db4b59e0 100644 --- a/apps/web/src/connection/catalog.ts +++ b/apps/web/src/connection/catalog.ts @@ -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), + ), + ), +); diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index ee28ca37202f9..faa765a8c1fab 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -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()); const rejectedRef = yield* Ref.make(new Map()); - 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(); const registrations: Array = []; + let discoveryComplete = true; const primaryTopologyRead = readPrimaryEnvironmentTargetResult(); const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead( @@ -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, }); @@ -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; } } } @@ -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, }); @@ -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 && @@ -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; + 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), ), }); }), diff --git a/apps/web/src/providerAuthDelivery.ts b/apps/web/src/providerAuthDelivery.ts index 41115118de615..61ad2cbe1219d 100644 --- a/apps/web/src/providerAuthDelivery.ts +++ b/apps/web/src/providerAuthDelivery.ts @@ -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"; @@ -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 { + 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, @@ -60,10 +76,14 @@ async function completeProviderAuth(delivery: ProviderAuthDelivery): Promise + registry.reconcilePlatform(registrations, discoveryComplete), + ), Effect.forkScoped, ); }).pipe(Effect.withSpan("clientRuntime.connection.application.start")), diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts index 512f7e30d3cc8..9d4773d570d74 100644 --- a/packages/client-runtime/src/connection/registry.test.ts +++ b/packages/client-runtime/src/connection/registry.test.ts @@ -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(); diff --git a/packages/client-runtime/src/connection/registry.ts b/packages/client-runtime/src/connection/registry.ts index ec1f2d0fedbe1..dfa3a5a149f68 100644 --- a/packages/client-runtime/src/connection/registry.ts +++ b/packages/client-runtime/src/connection/registry.ts @@ -99,6 +99,11 @@ export class EnvironmentRegistry extends Context.Service< readonly entries: SubscriptionRef.SubscriptionRef< ReadonlyMap >; + /** Catalog snapshots, with null while platform discovery cannot rule out an unknown target. */ + readonly entriesAfterPlatformDiscovery: Stream.Stream | null>; readonly networkStatus: SubscriptionRef.SubscriptionRef; readonly start: Effect.Effect; /** @@ -119,6 +124,7 @@ export class EnvironmentRegistry extends Context.Service< ) => Effect.Effect; readonly reconcilePlatform: ( registrations: ReadonlyArray, + discoveryComplete?: boolean, ) => Effect.Effect; readonly remove: ( environmentId: EnvironmentId, @@ -270,6 +276,7 @@ export const make = Effect.gen(function* () { ); const entries = yield* SubscriptionRef.make>(initialEntries); + const platformDiscoveryComplete = yield* SubscriptionRef.make(false); const networkStatus = yield* SubscriptionRef.make(yield* connectivity.status); const serviceScopes = yield* SubscriptionRef.make< ReadonlyMap @@ -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, + 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)); @@ -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, diff --git a/packages/client-runtime/src/platform/source.ts b/packages/client-runtime/src/platform/source.ts index 050e0828e6971..bbe2d6454d96c 100644 --- a/packages/client-runtime/src/platform/source.ts +++ b/packages/client-runtime/src/platform/source.ts @@ -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>; + readonly snapshots: Stream.Stream<{ + readonly registrations: ReadonlyArray; + /** Every target named by the current platform topology has been resolved. */ + readonly discoveryComplete: boolean; + }>; } >()("@t3tools/client-runtime/platform/source/PlatformConnectionSource") {} diff --git a/packages/client-runtime/src/state/threads-atoms.test.ts b/packages/client-runtime/src/state/threads-atoms.test.ts index 460f7e593990a..12c9316c36691 100644 --- a/packages/client-runtime/src/state/threads-atoms.test.ts +++ b/packages/client-runtime/src/state/threads-atoms.test.ts @@ -129,6 +129,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options? entries: yield* SubscriptionRef.make>( new Map(), ), + entriesAfterPlatformDiscovery: Stream.empty, networkStatus: yield* SubscriptionRef.make("online"), start: Effect.void, register: () => Effect.die("Unexpected environment registration"), diff --git a/scripts/scenarios/chatgpt-return-reaches-primary-environment.e2e.ts b/scripts/scenarios/chatgpt-return-reaches-primary-environment.e2e.ts new file mode 100644 index 0000000000000..3ef711a6e3021 --- /dev/null +++ b/scripts/scenarios/chatgpt-return-reaches-primary-environment.e2e.ts @@ -0,0 +1,57 @@ +import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; +import { codexAuthDeliveryUrl } from "@t3tools/shared/codexAuthHandoff"; +import { expect } from "e2e"; + +import { environmentId, runPromise, test, WEB } from "./t3.ts"; + +test( + "A ChatGPT sign-in return reaches the primary environment after a failed discovery request", + WEB, + async ({ t3, app, browser, screen }) => { + const primaryId = EnvironmentId.make(await runPromise(environmentId(app.baseUrl))); + const state = "scenario-auth-state"; + const redirectUri = "http://127.0.0.1:1455/auth/callback"; + const authorization = new URL("https://auth.openai.com/api/accounts/authorize"); + authorization.search = new URLSearchParams({ + state, + redirect_uri: redirectUri, + response_type: "code", + code_challenge_method: "S256", + code_challenge: "a".repeat(43), + client_id: "dynamic_agent_client", + }).toString(); + const callback = new URL(redirectUri); + callback.search = new URLSearchParams({ state, code: "scenario-code" }).toString(); + const returnUrl = new URL("/welcome", app.baseUrl); + returnUrl.hash = `agents:${primaryId}`; + const delivery = new URL( + codexAuthDeliveryUrl( + { + authorizationUrl: authorization.href, + returnUrl: returnUrl.href, + environmentId: primaryId, + instanceId: ProviderInstanceId.make("codex"), + flowId: "scenario-flow", + }, + callback.href, + ), + ); + + await t3.open(); + let firstDescriptorAborted = false; + await browser.route("**/.well-known/t3/environment", async (route) => { + if (firstDescriptorAborted) { + await route.fallback(); + return; + } + firstDescriptorAborted = true; + await route.abort(); + }); + await app.open(`${delivery.pathname}${delivery.search}${delivery.hash}`); + // The server rejects the fake flow before any request to the identity provider. + await expect( + screen.getByText("Return to the provider and try again.", { exact: true }), + ).toBeVisible(); + expect(firstDescriptorAborted).toBe(true); + }, +); diff --git a/scripts/scenarios/chatgpt-return-reports-removed-environment.e2e.ts b/scripts/scenarios/chatgpt-return-reports-removed-environment.e2e.ts new file mode 100644 index 0000000000000..4fdd05252de29 --- /dev/null +++ b/scripts/scenarios/chatgpt-return-reports-removed-environment.e2e.ts @@ -0,0 +1,52 @@ +import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts"; +import { codexAuthDeliveryUrl } from "@t3tools/shared/codexAuthHandoff"; +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A ChatGPT sign-in return reports that it cannot finish on a removed environment", + WEB, + async ({ t3, app, screen }) => { + await t3.project("demo"); + const environmentId = EnvironmentId.make("removed-sign-in-machine"); + const instanceId = ProviderInstanceId.make("codex"); + const returnUrl = new URL("/welcome", app.baseUrl); + returnUrl.hash = `agents:${environmentId}`; + + // Start at the helper's return link. The missing machine makes the code unusable, + // so this does not contact the identity provider. + const callback = new URL("http://127.0.0.1:1455/auth/callback"); + callback.searchParams.set("state", "scenario-auth-state"); + const authorization = new URL("https://auth.openai.com/api/accounts/authorize"); + authorization.search = new URLSearchParams({ + state: "scenario-auth-state", + redirect_uri: "http://127.0.0.1:1455/auth/callback", + response_type: "code", + code_challenge_method: "S256", + code_challenge: "a".repeat(43), + client_id: "dynamic_agent_client", + }).toString(); + callback.searchParams.set("code", "scenario-code"); + const delivery = new URL( + codexAuthDeliveryUrl( + { + authorizationUrl: authorization.href, + returnUrl: returnUrl.href, + environmentId, + instanceId, + flowId: "scenario-flow", + }, + callback.href, + ), + ); + await t3.open(`${delivery.pathname}${delivery.search}${delivery.hash}`); + try { + await expect( + screen.getByText("ChatGPT sign-in couldn't finish", { exact: true }), + ).toBeVisible(); + } finally { + await app.screenshot("return-to-removed-environment"); + } + }, +);