diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.ts index dcd50342f1c91..98335f5090c51 100644 --- a/apps/web/src/connection/platform.ts +++ b/apps/web/src/connection/platform.ts @@ -142,6 +142,24 @@ const layerWakeups = Wakeups.layer({ }), ).pipe(Effect.asVoid), ), + // A window left visible beside another app never fires visibilitychange when refocused. + Stream.callback<"application-focused">((queue) => + Effect.acquireRelease( + Effect.sync(() => { + const listener = () => { + if (document.visibilityState === "visible") { + Queue.offerUnsafe(queue, "application-focused"); + } + }; + window.addEventListener("focus", listener); + return listener; + }), + (listener) => + Effect.sync(() => { + window.removeEventListener("focus", listener); + }), + ).pipe(Effect.asVoid), + ), managedRelayAccountChanges(appAtomRegistry).pipe( Stream.map(() => "credentials-changed" as const), ), diff --git a/packages/client-runtime/src/connection/supervisor.ts b/packages/client-runtime/src/connection/supervisor.ts index bbeffd1cb7bc2..1d74dee227290 100644 --- a/packages/client-runtime/src/connection/supervisor.ts +++ b/packages/client-runtime/src/connection/supervisor.ts @@ -1259,6 +1259,7 @@ export const make = Effect.fn("EnvironmentSupervisor.make")(function* ( Effect.forkScoped, ); yield* wakeups.changes.pipe( + Stream.filter(ConnectionWakeups.reachesConnectionSupervisor), Stream.runForEach((reason) => // A long suspension can hide a network change the platform never reported. (reason === "network-changed" || reason === "application-active-long" diff --git a/packages/client-runtime/src/connection/wakeups.ts b/packages/client-runtime/src/connection/wakeups.ts index c407c1b3a7dd9..746160681ee9d 100644 --- a/packages/client-runtime/src/connection/wakeups.ts +++ b/packages/client-runtime/src/connection/wakeups.ts @@ -6,6 +6,7 @@ export type ConnectionWakeup = | "application-active" | "application-active-probe" | "application-active-long" + | "application-focused" | "credentials-changed" | "network-changed"; @@ -25,6 +26,20 @@ export function shouldResubscribeAfterWakeup(reason: ConnectionWakeup): boolean return isApplicationActiveWakeup(reason); } +// A brief app switch (the mobile probe) does not justify listing the whole account again. +export function shouldRelistAccountAfterWakeup(reason: ConnectionWakeup): boolean { + return ( + reason === "application-active" || + reason === "application-active-long" || + reason === "application-focused" + ); +} + +// Focus fires on every window switch; any wakeup would arm a running probe's silent-socket check. +export function reachesConnectionSupervisor(reason: ConnectionWakeup): boolean { + return reason !== "application-focused"; +} + export class ConnectionWakeups extends Context.Service< ConnectionWakeups, { diff --git a/packages/client-runtime/src/relay/discovery.test.ts b/packages/client-runtime/src/relay/discovery.test.ts index 2d1f20b79fcbe..f0445e4968faf 100644 --- a/packages/client-runtime/src/relay/discovery.test.ts +++ b/packages/client-runtime/src/relay/discovery.test.ts @@ -61,6 +61,7 @@ function status( const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () { const networkStatus = yield* SubscriptionRef.make("online"); const listCalls = yield* Ref.make(0); + const statusCalls = yield* Ref.make(0); const listedEnvironments = yield* Ref.make>(environments); const listFailure = yield* Ref.make(null); @@ -69,7 +70,7 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () { const sessionIdentity = { accountId: "account-1" }; const wakeups = yield* SubscriptionRef.make<{ readonly sequence: number; - readonly reason: "application-active" | "credentials-changed"; + readonly reason: ConnectionWakeups.ConnectionWakeup; }>({ sequence: 0, reason: "application-active", @@ -107,7 +108,8 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () { return yield* Ref.get(listedEnvironments); }), getEnvironmentStatus: ({ environmentId }) => - Ref.get(statusRequests).pipe( + Ref.update(statusCalls, (current) => current + 1).pipe( + Effect.andThen(Ref.get(statusRequests)), Effect.flatMap((requests) => Deferred.await(requests.get(environmentId)!)), ), listDevices: () => Effect.die("unused"), @@ -174,8 +176,9 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () { clerkToken, networkStatus, secondListCall, + statusCalls, statusRequests, - wake: (reason: "application-active" | "credentials-changed") => + wake: (reason: ConnectionWakeups.ConnectionWakeup) => SubscriptionRef.update(wakeups, (event) => ({ sequence: event.sequence + 1, reason, @@ -471,6 +474,188 @@ describe("RelayEnvironmentDiscovery", () => { }), ); + it.effect.each(["application-active", "application-active-long", "application-focused"] as const)( + "lists the account again when the app returns to the foreground (%s)", + (reason) => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* Ref.set(harness.listedEnvironments, [environments[0]!]); + yield* Effect.gen(function* () { + const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery; + const requests = yield* Ref.get(harness.statusRequests); + for (const environment of environments) { + yield* Deferred.succeed( + requests.get(environment.environmentId)!, + status(environment, "online"), + ); + } + // Let the scoped connectivity and wakeup subscriptions start before signing in. + yield* Effect.yieldNow; + yield* harness.wake("credentials-changed"); + const signedIn = yield* SubscriptionRef.changes(discovery.state).pipe( + Stream.filter((state) => state.listed && !state.refreshing), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + expect([...signedIn.environments.keys()]).toEqual([environments[0]!.environmentId]); + + yield* Ref.set(harness.listedEnvironments, environments); + yield* harness.wake(reason); + const relisted = yield* SubscriptionRef.changes(discovery.state).pipe( + Stream.filter( + (state) => state.environments.size === environments.length && !state.refreshing, + ), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + expect([...relisted.environments.keys()]).toEqual( + environments.map((environment) => environment.environmentId), + ); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }), + ); + + it.effect("lists a registration that lands while an earlier refresh checks statuses", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* Ref.set(harness.listedEnvironments, [environments[0]!]); + yield* Effect.gen(function* () { + const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery; + yield* Effect.yieldNow; + const refreshFiber = yield* Effect.forkChild(discovery.refresh); + yield* SubscriptionRef.changes(discovery.state).pipe( + Stream.filter((state) => state.listed), + Stream.runHead, + ); + + yield* Ref.set(harness.listedEnvironments, environments); + yield* harness.wake("application-active"); + // Let the wakeup reach discovery while the first refresh still holds the lock. + yield* Effect.yieldNow; + const requests = yield* Ref.get(harness.statusRequests); + for (const environment of environments) { + yield* Deferred.succeed( + requests.get(environment.environmentId)!, + status(environment, "online"), + ); + } + yield* Fiber.join(refreshFiber); + + const relisted = yield* SubscriptionRef.changes(discovery.state).pipe( + Stream.filter( + (state) => state.environments.size === environments.length && !state.refreshing, + ), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + expect([...relisted.environments.keys()]).toEqual( + environments.map((environment) => environment.environmentId), + ); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }), + ); + + it.effect("coalesces foreground checks that arrive during an in-flight refresh", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* Effect.gen(function* () { + const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery; + yield* Effect.yieldNow; + const refreshFiber = yield* Effect.forkChild(discovery.refresh); + yield* SubscriptionRef.changes(discovery.state).pipe( + Stream.filter((state) => state.listed), + Stream.runHead, + ); + + for (const reason of [ + "application-active", + "application-focused", + "application-active", + "application-focused", + "application-active-long", + ] as const) { + yield* harness.wake(reason); + yield* Effect.yieldNow; + } + // Waits on the lock behind every refresh the wakeups queued. + const lastRefresh = yield* Effect.forkChild(discovery.refresh); + yield* Effect.yieldNow; + const requests = yield* Ref.get(harness.statusRequests); + for (const environment of environments) { + yield* Deferred.succeed( + requests.get(environment.environmentId)!, + status(environment, "online"), + ); + } + yield* Fiber.join(refreshFiber); + yield* Fiber.join(lastRefresh); + + // The first refresh, one queued refresh, one trailing check's listing, and the last refresh. + expect(yield* Ref.get(harness.listCalls)).toBe(4); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }), + ); + + it.effect("keeps listed rows when the foreground check cannot list the account", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* Effect.gen(function* () { + const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery; + const requests = yield* Ref.get(harness.statusRequests); + for (const environment of environments) { + yield* Deferred.succeed( + requests.get(environment.environmentId)!, + status(environment, "online"), + ); + } + yield* Effect.yieldNow; + yield* discovery.refresh; + const settled = yield* SubscriptionRef.get(discovery.state); + + yield* Ref.set( + harness.listFailure, + new ManagedRelay.ManagedRelayRequestFailedError({ + action: "list relay-managed environments", + cause: new Error("Relay request failed."), + }), + ); + yield* harness.wake("application-active"); + yield* Deferred.await(harness.secondListCall); + + const after = yield* SubscriptionRef.get(discovery.state); + expect(after).toBe(settled); + expect(after.environments.size).toBe(environments.length); + expect(Option.isNone(after.error)).toBe(true); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }), + ); + + it.effect("leaves an unchanged account list untouched when the app returns", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* Effect.gen(function* () { + const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery; + const requests = yield* Ref.get(harness.statusRequests); + for (const environment of environments) { + yield* Deferred.succeed( + requests.get(environment.environmentId)!, + status(environment, "online"), + ); + } + yield* Effect.yieldNow; + yield* discovery.refresh; + const settled = yield* SubscriptionRef.get(discovery.state); + + yield* harness.wake("application-active"); + yield* Deferred.await(harness.secondListCall); + + expect(yield* SubscriptionRef.get(discovery.state)).toBe(settled); + expect(yield* Ref.get(harness.listCalls)).toBe(2); + expect(yield* Ref.get(harness.statusCalls)).toBe(environments.length); + }).pipe(Effect.provide(harness.layer), Effect.scoped); + }), + ); + it.effect("settles to a clean empty state when refreshed while signed out", () => Effect.gen(function* () { const harness = yield* makeHarness(); diff --git a/packages/client-runtime/src/relay/discovery.ts b/packages/client-runtime/src/relay/discovery.ts index 63dadc6cadfc6..7daf599ffcbfa 100644 --- a/packages/client-runtime/src/relay/discovery.ts +++ b/packages/client-runtime/src/relay/discovery.ts @@ -121,6 +121,8 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () { const wakeups = yield* ConnectionWakeups.ConnectionWakeups; const state = yield* SubscriptionRef.make(EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE); const refreshLock = yield* Semaphore.make(1); + const foregroundCheckLock = yield* Semaphore.make(1); + const registrationCheckRequested = yield* Ref.make(false); const hasRefreshed = yield* Ref.make(false); const accountGeneration = yield* Ref.make(0); const activeAccountId = yield* Ref.make>(Option.none()); @@ -320,6 +322,52 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () { ), ); + // Refreshes only when the account's registrations changed, so foregrounding keeps unchanged rows. + const checkRegistrations = Effect.fn("RelayEnvironmentDiscovery.checkRegistrations")( + function* () { + if ( + !(yield* Ref.get(hasRefreshed)) || + (yield* connectivity.status) === "offline" || + Option.isNone(yield* session.identity) + ) { + return; + } + const current = yield* SubscriptionRef.get(state); + if (!current.listed || current.refreshing || Option.isSome(current.error)) { + return yield* refresh; + } + const generation = yield* Ref.get(accountGeneration); + const clerkToken = yield* session.clerkToken; + const listed = yield* relay.listEnvironments({ clerkToken }); + if ((yield* Ref.get(accountGeneration)) !== generation) { + return; + } + const known = (yield* SubscriptionRef.get(state)).environments; + if ( + listed.length === known.size && + listed.every((environment) => known.has(environment.environmentId)) + ) { + return; + } + yield* refresh; + }, + Effect.catch((error) => + Effect.logDebug("Relay foreground registration check failed", { error }), + ), + ); + // A wakeup during a running check is answered by one more check once that one finishes. + const requestRegistrationCheck = Ref.set(registrationCheckRequested, true).pipe( + Effect.andThen( + foregroundCheckLock.withPermitsIfAvailable(1)( + Effect.gen(function* () { + while (yield* Ref.getAndSet(registrationCheckRequested, false)) { + yield* checkRegistrations(); + } + }), + ), + ), + ); + yield* connectivity.changes.pipe( Stream.changes, Stream.runForEach((networkStatus) => @@ -345,7 +393,9 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () { yield* SubscriptionRef.set(state, EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE); yield* refresh.pipe(Effect.forkScoped); }) - : Effect.void, + : ConnectionWakeups.shouldRelistAccountAfterWakeup(reason) + ? requestRegistrationCheck.pipe(Effect.forkScoped) + : Effect.void, ), Effect.forkScoped, );