TypeScript
fix(web): refresh stale desktop endpoints when Connections reopens (#16026)
Arthur Katcher7686c5731132
diff --git a/apps/web/src/state/desktopNetworkAccess.test.ts b/apps/web/src/state/desktopNetworkAccess.test.tsindex 25c522522ef..e38d9012fa6 100644--- a/apps/web/src/state/desktopNetworkAccess.test.ts+++ b/apps/web/src/state/desktopNetworkAccess.test.ts@@ -1,8 +1,10 @@+import { it } from "@effect/vitest";import type { AdvertisedEndpoint, DesktopServerExposureState } from "@t3tools/contracts";import * as Cause from "effect/Cause";+import * as Effect from "effect/Effect";import * as AsyncResult from "effect/reactivity/AsyncResult";import { AtomRegistry } from "effect/reactivity";-import { describe, expect, it, vi } from "vite-plus/test";+import { describe, expect, vi } from "vite-plus/test";import { createDesktopNetworkAccessStateAtom } from "./desktopNetworkAccess";@@ -15,43 +17,144 @@ const serverExposureState: DesktopServerExposureState = {};const advertisedEndpoints: ReadonlyArray<AdvertisedEndpoint> = [];+const tailscaleEndpoint: AdvertisedEndpoint = {+ id: "tailscale-ip:100.74.126.34",+ httpBaseUrl: "http://100.74.126.34:37737/",+ wsBaseUrl: "ws://100.74.126.34:37737/",+ label: "Tailscale IP",+ provider: { id: "tailscale", kind: "private-network", label: "Tailscale", isAddon: true },+ reachability: "private-network",+ status: "available",+ source: "desktop-addon",+ compatibility: { hostedHttpsApp: "mixed-content-blocked", desktopApp: "compatible" },+};const serverExposureLoadCause = new Error("exposure failed");const advertisedEndpointsLoadCause = new Error("endpoints failed");describe("desktopNetworkAccessState", () => {- it("retains the loaded snapshot when the settings screen remounts", async () => {- const getServerExposureState = vi.fn(async () => serverExposureState);- const getAdvertisedEndpoints = vi.fn(async () => advertisedEndpoints);- const atom = createDesktopNetworkAccessStateAtom(() => ({- getAdvertisedEndpoints,- getServerExposureState,- }));- const registry = AtomRegistry.make();+ it.effect("retains a fresh snapshot after the settings screen unmounts and remounts", () =>+ Effect.gen(function* () {+ const now = vi.spyOn(Date, "now").mockReturnValue(1_000_000);+ const getServerExposureState = vi.fn(async () => serverExposureState);+ const getAdvertisedEndpoints = vi.fn(async () => advertisedEndpoints);+ const atom = createDesktopNetworkAccessStateAtom(() => ({+ getAdvertisedEndpoints,+ getServerExposureState,+ }));+ const registry = AtomRegistry.make();- const unmount = registry.mount(atom);- await vi.waitFor(() => {- expect(AsyncResult.value(registry.get(atom))).toEqual(- expect.objectContaining({ _tag: "Some" }),- );- });- unmount();+ let unmount = registry.mount(atom);+ try {+ yield* AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true });+ unmount();+ yield* Effect.yieldNow;+ now.mockReturnValue(1_029_999);++ unmount = registry.mount(atom);+ expect(AsyncResult.value(registry.get(atom))).toEqual(+ expect.objectContaining({+ _tag: "Some",+ value: { advertisedEndpoints, serverExposureState },+ }),+ );+ expect(getServerExposureState).toHaveBeenCalledTimes(1);+ expect(getAdvertisedEndpoints).toHaveBeenCalledTimes(1);+ } finally {+ unmount();+ registry.dispose();+ now.mockRestore();+ }+ }),+ );++ it.effect("keeps the previous snapshot while an explicit refresh loads current endpoints", () =>+ Effect.gen(function* () {+ let resolveEndpoints!: (value: ReadonlyArray<AdvertisedEndpoint>) => void;+ const nextEndpoints = new Promise<ReadonlyArray<AdvertisedEndpoint>>((resolve) => {+ resolveEndpoints = resolve;+ });+ const getAdvertisedEndpoints = vi+ .fn(async () => advertisedEndpoints)+ .mockResolvedValueOnce(advertisedEndpoints)+ .mockReturnValueOnce(nextEndpoints);+ const atom = createDesktopNetworkAccessStateAtom(() => ({+ getAdvertisedEndpoints,+ getServerExposureState: async () => serverExposureState,+ }));+ const registry = AtomRegistry.make();+ let unmount = registry.mount(atom);- const remount = registry.mount(atom);- const result = registry.get(atom);- expect(AsyncResult.value(result)).toEqual(- expect.objectContaining({- _tag: "Some",- value: { advertisedEndpoints, serverExposureState },- }),- );- expect(getServerExposureState).toHaveBeenCalledTimes(1);- expect(getAdvertisedEndpoints).toHaveBeenCalledTimes(1);+ try {+ yield* AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true });+ registry.refresh(atom);+ unmount();+ yield* Effect.yieldNow;+ unmount = registry.mount(atom);- remount();- registry.dispose();- });+ expect(AsyncResult.value(registry.get(atom))).toEqual(+ expect.objectContaining({+ _tag: "Some",+ value: { advertisedEndpoints, serverExposureState },+ }),+ );+ resolveEndpoints([tailscaleEndpoint]);+ const refreshed = yield* AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true });+ expect(refreshed.advertisedEndpoints).toEqual([tailscaleEndpoint]);+ expect(getAdvertisedEndpoints).toHaveBeenCalledTimes(2);+ } finally {+ resolveEndpoints([]);+ unmount();+ registry.dispose();+ }+ }),+ );- it.each([+ it.effect.each([+ { change: "appears", before: [], after: [tailscaleEndpoint] },+ { change: "disappears", before: [tailscaleEndpoint], after: [] },+ ])("revalidates a stale snapshot when Tailscale $change between visits", ({ before, after }) =>+ Effect.gen(function* () {+ const now = vi.spyOn(Date, "now").mockReturnValue(1_000_000);+ const getServerExposureState = vi.fn(async () => serverExposureState);+ const getAdvertisedEndpoints = vi.fn(async () => before);+ const atom = createDesktopNetworkAccessStateAtom(() => ({+ getAdvertisedEndpoints,+ getServerExposureState,+ }));+ const registry = AtomRegistry.make();+ let unmount = registry.mount(atom);++ try {+ const initial = yield* AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true });+ expect(initial.advertisedEndpoints).toEqual(before);+ unmount();+ yield* Effect.yieldNow;+ let markRefreshStarted!: () => void;+ const refreshStarted = new Promise<void>((resolve) => {+ markRefreshStarted = resolve;+ });+ getAdvertisedEndpoints.mockImplementation(async () => {+ markRefreshStarted();+ return after;+ });+ now.mockReturnValue(1_030_000);++ unmount = registry.mount(atom);+ // SWR schedules stale revalidation after the initial cached read.+ yield* Effect.promise(() => refreshStarted);+ const refreshed = yield* AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true });+ expect(refreshed.advertisedEndpoints).toEqual(after);+ expect(getServerExposureState).toHaveBeenCalledTimes(2);+ expect(getAdvertisedEndpoints).toHaveBeenCalledTimes(2);+ } finally {+ unmount();+ registry.dispose();+ now.mockRestore();+ }+ }),+ );++ it.effect.each([{cause: serverExposureLoadCause,expectedTag: "DesktopServerExposureStateLoadError",@@ -64,24 +167,26 @@ describe("desktopNetworkAccessState", () => {getAdvertisedEndpoints: async () => Promise.reject(advertisedEndpointsLoadCause),getServerExposureState: async () => serverExposureState,},- ])("retains the $expectedTag cause", async (testCase) => {- const atom = createDesktopNetworkAccessStateAtom(() => ({- getAdvertisedEndpoints: testCase.getAdvertisedEndpoints,- getServerExposureState: testCase.getServerExposureState,- }));- const registry = AtomRegistry.make();- registry.mount(atom);+ ])("retains the $expectedTag cause", (testCase) =>+ Effect.gen(function* () {+ const atom = createDesktopNetworkAccessStateAtom(() => ({+ getAdvertisedEndpoints: testCase.getAdvertisedEndpoints,+ getServerExposureState: testCase.getServerExposureState,+ }));+ const registry = AtomRegistry.make();+ registry.mount(atom);- await vi.waitFor(() => expect(AsyncResult.isFailure(registry.get(atom))).toBe(true));- const result = registry.get(atom);- if (!AsyncResult.isFailure(result)) throw new Error("Expected network access load to fail.");+ yield* Effect.exit(AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true }));+ const result = registry.get(atom);+ if (!AsyncResult.isFailure(result)) throw new Error("Expected network access load to fail.");- expect(Cause.squash(result.cause)).toEqual(- expect.objectContaining({- _tag: testCase.expectedTag,- cause: testCase.cause,- }),- );- registry.dispose();- });+ expect(Cause.squash(result.cause)).toEqual(+ expect.objectContaining({+ _tag: testCase.expectedTag,+ cause: testCase.cause,+ }),+ );+ registry.dispose();+ }),+ );});diff --git a/apps/web/src/state/desktopNetworkAccess.ts b/apps/web/src/state/desktopNetworkAccess.tsindex e94752f8ced..bd5f13fe634 100644--- a/apps/web/src/state/desktopNetworkAccess.ts+++ b/apps/web/src/state/desktopNetworkAccess.ts@@ -80,11 +80,12 @@ export function createDesktopNetworkAccessStateAtom(});return Atom.make(loadDesktopNetworkAccess()).pipe(+ // Retain the snapshot, but let the SWR wrapper revalidate when Settings remounts.+ Atom.keepAlive,Atom.swr({staleTime: DESKTOP_NETWORK_ACCESS_STALE_TIME_MS,revalidateOnMount: true,}),- Atom.keepAlive,Atom.withLabel("desktop:network-access"),);}