From 021db1307c713c992b4107dd09bed295db58fe92 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 24 Oct 2026 23:19:44 +0000 Subject: [PATCH 1/7] test(web): cover relay environment cleanup across Clerk auth transitions An offline launch where Clerk loads signed out must keep saved T3 Connect environments, while a real sign-out or account switch still removes them. Co-Authored-By: Claude Opus 5.5 --- .../src/cloud/managedAuth.browser.test.tsx | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 apps/web/src/cloud/managedAuth.browser.test.tsx diff --git a/apps/web/src/cloud/managedAuth.browser.test.tsx b/apps/web/src/cloud/managedAuth.browser.test.tsx new file mode 100644 index 0000000000000..220d67f601dc5 --- /dev/null +++ b/apps/web/src/cloud/managedAuth.browser.test.tsx @@ -0,0 +1,81 @@ +import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay"; +import * as Exit from "effect/Exit"; +import { AsyncResult } from "effect/reactivity"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../test/render"; +import { appAtomRegistry } from "../rpc/atomRegistry"; + +type ClerkAuth = { isLoaded: boolean; isSignedIn: boolean; userId: string | null }; + +const testState = vi.hoisted(() => ({ + auth: { isLoaded: false, isSignedIn: false, userId: null } as ClerkAuth, + getToken: async () => "clerk-token", + removeRelayEnvironments: vi.fn(), +})); + +vi.mock(import("@clerk/react"), async (original) => ({ + ...(await original()), + useAuth: (() => ({ ...testState.auth, getToken: testState.getToken })) as never, +})); +vi.mock(import("../state/use-atom-command"), async (original) => ({ + ...(await original()), + useAtomCommand: (() => testState.removeRelayEnvironments) as never, +})); +vi.mock(import("../lib/runtime"), async (original) => ({ + ...(await original()), + runtime: { runPromiseExit: async () => Exit.void } as never, +})); +// The Clerk JWT template is build-time config the test environment does not set. +vi.mock(import("./publicConfig"), async (original) => ({ + ...(await original()), + resolveRelayClerkTokenOptions: () => ({}) as never, +})); + +import { ManagedRelayAuthProvider } from "./managedAuth"; + +const loading: ClerkAuth = { isLoaded: false, isSignedIn: false, userId: null }; +const signedOut: ClerkAuth = { isLoaded: true, isSignedIn: false, userId: null }; +const signedInAs = (userId: string): ClerkAuth => ({ isLoaded: true, isSignedIn: true, userId }); + +async function mountAuth(...states: ReadonlyArray) { + testState.removeRelayEnvironments.mockReset().mockResolvedValue(AsyncResult.success(undefined)); + const [first = loading, ...rest] = states; + testState.auth = first; + const screen = await render({null}, { + router: false, + }); + for (const state of rest) { + testState.auth = state; + await screen.rerender({null}); + } + // Account cleanup is queued behind a promise, so let it start before asserting. + await act(() => Promise.resolve()); + return screen; +} + +const activeAccount = () => appAtomRegistry.get(managedRelaySessionAtom)?.accountId ?? null; + +describe("ManagedRelayAuthProvider", () => { + it("keeps saved relay environments when launching offline and Clerk loads signed out", async () => { + using _offline = vi.spyOn(navigator, "onLine", "get").mockReturnValue(false); + await using _screen = await mountAuth(loading, signedOut); + + expect(testState.removeRelayEnvironments).not.toHaveBeenCalled(); + expect(activeAccount()).toBeNull(); + }); + + it("removes relay environments when the signed-in account signs out", async () => { + await using _screen = await mountAuth(signedInAs("account-1"), signedOut); + + await vi.waitFor(() => expect(testState.removeRelayEnvironments).toHaveBeenCalledTimes(1)); + expect(activeAccount()).toBeNull(); + }); + + it("removes the previous account's relay environments before activating the next account", async () => { + await using _screen = await mountAuth(signedInAs("account-1"), signedInAs("account-2")); + + await vi.waitFor(() => expect(activeAccount()).toBe("account-2")); + expect(testState.removeRelayEnvironments).toHaveBeenCalledTimes(1); + }); +}); From 0588da6e438ba19c76dbec542e3a816ef93b5dfb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 24 Oct 2026 23:21:43 +0000 Subject: [PATCH 2/7] fix(web): offline launch no longer deletes T3 Connect environments Clerk can finish loading signed out while the device is offline. The managed relay provider treated that first observation as a sign-out and removed every saved relay environment. Only clean up after a signed-in account was observed in this session. Co-Authored-By: Otavio Salvador Co-Authored-By: Claude Opus 5.5 --- apps/web/src/cloud/managedAuth.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx index f9bf1c966f40b..71f0aca7f544b 100644 --- a/apps/web/src/cloud/managedAuth.tsx +++ b/apps/web/src/cloud/managedAuth.tsx @@ -71,7 +71,8 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac if (!isSignedIn || !userId) { deactivateManagedRelayAuthentication(); - if (previousAccount !== null) { + // Clerk also loads signed out offline, so only a sign-out seen in this session clears. + if (previousAccount !== undefined && previousAccount !== null) { void queueAccountCleanup(); } } else { From 2f0715672a8b4264763be9f392256411076b2609 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 24 Oct 2026 23:31:57 +0000 Subject: [PATCH 3/7] fix(web): a launch Clerk's API confirms signed out still clears T3 Connect environments Offline, Clerk loads "degraded" from local state and often reports signed out, so cleanup now waits for a "ready" status before treating a cold sign-out as real, and stays unresolved until then. Co-Authored-By: Claude Opus 5.5 --- .../src/cloud/managedAuth.browser.test.tsx | 98 +++++++++++++++---- apps/web/src/cloud/managedAuth.tsx | 24 +++-- 2 files changed, 96 insertions(+), 26 deletions(-) diff --git a/apps/web/src/cloud/managedAuth.browser.test.tsx b/apps/web/src/cloud/managedAuth.browser.test.tsx index 220d67f601dc5..9f71b9349e780 100644 --- a/apps/web/src/cloud/managedAuth.browser.test.tsx +++ b/apps/web/src/cloud/managedAuth.browser.test.tsx @@ -1,3 +1,4 @@ +import type { useClerk } from "@clerk/react"; import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay"; import * as Exit from "effect/Exit"; import { AsyncResult } from "effect/reactivity"; @@ -6,17 +7,34 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { act, render } from "../../test/render"; import { appAtomRegistry } from "../rpc/atomRegistry"; -type ClerkAuth = { isLoaded: boolean; isSignedIn: boolean; userId: string | null }; +type ClerkAuth = { + status: ReturnType["status"]; + isLoaded: boolean; + isSignedIn: boolean; + userId: string | null; +}; -const testState = vi.hoisted(() => ({ - auth: { isLoaded: false, isSignedIn: false, userId: null } as ClerkAuth, - getToken: async () => "clerk-token", - removeRelayEnvironments: vi.fn(), -})); +const testState = vi.hoisted(() => { + const statusListeners = new Set<() => void>(); + return { + auth: { status: "loading", isLoaded: false, isSignedIn: false, userId: null } as ClerkAuth, + statusListeners, + clerk: { + get status() { + return testState.auth.status; + }, + on: (_event: "status", listener: () => void) => void statusListeners.add(listener), + off: (_event: "status", listener: () => void) => void statusListeners.delete(listener), + }, + getToken: async () => "clerk-token", + removeRelayEnvironments: vi.fn(), + }; +}); vi.mock(import("@clerk/react"), async (original) => ({ ...(await original()), useAuth: (() => ({ ...testState.auth, getToken: testState.getToken })) as never, + useClerk: (() => testState.clerk) as never, })); vi.mock(import("../state/use-atom-command"), async (original) => ({ ...(await original()), @@ -34,20 +52,44 @@ vi.mock(import("./publicConfig"), async (original) => ({ import { ManagedRelayAuthProvider } from "./managedAuth"; -const loading: ClerkAuth = { isLoaded: false, isSignedIn: false, userId: null }; -const signedOut: ClerkAuth = { isLoaded: true, isSignedIn: false, userId: null }; -const signedInAs = (userId: string): ClerkAuth => ({ isLoaded: true, isSignedIn: true, userId }); +const loading: ClerkAuth = { status: "loading", isLoaded: false, isSignedIn: false, userId: null }; +const signedOut = (status: "ready" | "degraded"): ClerkAuth => ({ + status, + isLoaded: true, + isSignedIn: false, + userId: null, +}); +const signedInAs = (userId: string): ClerkAuth => ({ + status: "ready", + isLoaded: true, + isSignedIn: true, + userId, +}); -async function mountAuth(...states: ReadonlyArray) { - testState.removeRelayEnvironments.mockReset().mockResolvedValue(AsyncResult.success(undefined)); +async function mountAuth( + states: ReadonlyArray, + cleanup: Promise> = Promise.resolve( + AsyncResult.success(undefined), + ), +) { + testState.removeRelayEnvironments.mockReset().mockReturnValue(cleanup); const [first = loading, ...rest] = states; testState.auth = first; const screen = await render({null}, { router: false, }); - for (const state of rest) { - testState.auth = state; - await screen.rerender({null}); + try { + for (const state of rest) { + testState.auth = state; + // Clerk announces status through its status event and auth state through a render. + await act(() => { + for (const listener of testState.statusListeners) listener(); + }); + await screen.rerender({null}); + } + } catch (error) { + await screen[Symbol.asyncDispose](); + throw error; } // Account cleanup is queued behind a promise, so let it start before asserting. await act(() => Promise.resolve()); @@ -57,25 +99,41 @@ async function mountAuth(...states: ReadonlyArray) { const activeAccount = () => appAtomRegistry.get(managedRelaySessionAtom)?.accountId ?? null; describe("ManagedRelayAuthProvider", () => { - it("keeps saved relay environments when launching offline and Clerk loads signed out", async () => { - using _offline = vi.spyOn(navigator, "onLine", "get").mockReturnValue(false); - await using _screen = await mountAuth(loading, signedOut); + it("keeps saved relay environments when Clerk cannot reach its API at launch", async () => { + await using _screen = await mountAuth([loading, signedOut("degraded")]); expect(testState.removeRelayEnvironments).not.toHaveBeenCalled(); expect(activeAccount()).toBeNull(); }); + it("removes relay environments once Clerk's API confirms there is no session", async () => { + await using _screen = await mountAuth([loading, signedOut("degraded"), signedOut("ready")]); + + await vi.waitFor(() => expect(testState.removeRelayEnvironments).toHaveBeenCalledTimes(1)); + expect(activeAccount()).toBeNull(); + }); + it("removes relay environments when the signed-in account signs out", async () => { - await using _screen = await mountAuth(signedInAs("account-1"), signedOut); + await using _screen = await mountAuth([signedInAs("account-1"), signedOut("ready")]); await vi.waitFor(() => expect(testState.removeRelayEnvironments).toHaveBeenCalledTimes(1)); expect(activeAccount()).toBeNull(); }); it("removes the previous account's relay environments before activating the next account", async () => { - await using _screen = await mountAuth(signedInAs("account-1"), signedInAs("account-2")); + let releaseCleanup = () => {}; + const cleanup = new Promise>((resolve) => { + releaseCleanup = () => resolve(AsyncResult.success(undefined)); + }); + await using _screen = await mountAuth( + [signedInAs("account-1"), signedInAs("account-2")], + cleanup, + ); - await vi.waitFor(() => expect(activeAccount()).toBe("account-2")); expect(testState.removeRelayEnvironments).toHaveBeenCalledTimes(1); + expect(activeAccount()).toBeNull(); + + await act(releaseCleanup); + await vi.waitFor(() => expect(activeAccount()).toBe("account-2")); }); }); diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx index 71f0aca7f544b..496850dacdf00 100644 --- a/apps/web/src/cloud/managedAuth.tsx +++ b/apps/web/src/cloud/managedAuth.tsx @@ -1,4 +1,4 @@ -import { useAuth } from "@clerk/react"; +import { useAuth, useClerk } from "@clerk/react"; import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay"; import { reportAtomCommandResult, @@ -6,7 +6,7 @@ import { settlePromise, } from "@t3tools/client-runtime/state/runtime"; import * as Effect from "effect/Effect"; -import { useEffect, useRef, type ReactNode } from "react"; +import { useEffect, useRef, useSyncExternalStore, type ReactNode } from "react"; import { environmentCatalog } from "../connection/catalog"; import { runtime } from "../lib/runtime"; @@ -32,6 +32,17 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac const { getToken, isLoaded, isSignedIn, userId } = useAuth({ treatPendingAsSignedOut: false, }); + const clerk = useClerk(); + const clerkStatus = useSyncExternalStore( + (onChange) => { + clerk.on("status", onChange); + return () => clerk.off("status", onChange); + }, + () => clerk.status, + ); + // Clerk loads "degraded" from local state when its API is unreachable, often signed out, + // so only a "ready" load is Clerk's answer that no session exists. + const signedOutByClerkApi = !(isSignedIn && userId) && clerkStatus === "ready"; const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, { reportFailure: false, reportDefect: false, @@ -47,7 +58,9 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac let cancelled = false; const previousAccount = observedAccountRef.current; const nextAccount = isSignedIn && userId ? userId : null; - observedAccountRef.current = nextAccount; + // An unconfirmed sign-out stays unobserved so a later confirmed one still cleans up. + const resolved = nextAccount !== null || previousAccount !== undefined || signedOutByClerkApi; + observedAccountRef.current = resolved ? nextAccount : undefined; const queueAccountCleanup = () => { const previousTransition = accountTransitionRef.current ?? Promise.resolve(); @@ -71,8 +84,7 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac if (!isSignedIn || !userId) { deactivateManagedRelayAuthentication(); - // Clerk also loads signed out offline, so only a sign-out seen in this session clears. - if (previousAccount !== undefined && previousAccount !== null) { + if (resolved && previousAccount !== null) { void queueAccountCleanup(); } } else { @@ -101,7 +113,7 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac return () => { cancelled = true; }; - }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, userId]); + }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, signedOutByClerkApi, userId]); useEffect(() => () => deactivateManagedRelayAuthentication(), []); From 4deb386fa8e66ef78ce8a2b4322dd43e06d5f67c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 24 Oct 2026 23:44:19 +0000 Subject: [PATCH 4/7] fix(web): an offline "ready" Clerk load no longer clears T3 Connect environments Clerk 6.40 resolves fetches that fail while navigator.onLine is false to null, so initialization still reports "ready" with an empty client. Only treat a signed-out "ready" load as Clerk's answer when the client carries the id every /v1/client response includes. Co-Authored-By: Claude Opus 5.5 --- .../src/cloud/managedAuth.browser.test.tsx | 42 +++++++++++++++---- apps/web/src/cloud/managedAuth.tsx | 17 +++++--- vite.config.ts | 1 + 3 files changed, 45 insertions(+), 15 deletions(-) diff --git a/apps/web/src/cloud/managedAuth.browser.test.tsx b/apps/web/src/cloud/managedAuth.browser.test.tsx index 9f71b9349e780..a957d7ac7c5e0 100644 --- a/apps/web/src/cloud/managedAuth.browser.test.tsx +++ b/apps/web/src/cloud/managedAuth.browser.test.tsx @@ -12,19 +12,27 @@ type ClerkAuth = { isLoaded: boolean; isSignedIn: boolean; userId: string | null; + clientId?: string | undefined; }; const testState = vi.hoisted(() => { - const statusListeners = new Set<() => void>(); + const clerkListeners = new Set<() => void>(); return { auth: { status: "loading", isLoaded: false, isSignedIn: false, userId: null } as ClerkAuth, - statusListeners, + clerkListeners, clerk: { get status() { return testState.auth.status; }, - on: (_event: "status", listener: () => void) => void statusListeners.add(listener), - off: (_event: "status", listener: () => void) => void statusListeners.delete(listener), + get client() { + return { id: testState.auth.clientId }; + }, + addListener: (listener: () => void) => { + clerkListeners.add(listener); + return () => void clerkListeners.delete(listener); + }, + on: (_event: "status", listener: () => void) => void clerkListeners.add(listener), + off: (_event: "status", listener: () => void) => void clerkListeners.delete(listener), }, getToken: async () => "clerk-token", removeRelayEnvironments: vi.fn(), @@ -53,17 +61,19 @@ vi.mock(import("./publicConfig"), async (original) => ({ import { ManagedRelayAuthProvider } from "./managedAuth"; const loading: ClerkAuth = { status: "loading", isLoaded: false, isSignedIn: false, userId: null }; -const signedOut = (status: "ready" | "degraded"): ClerkAuth => ({ +const signedOut = (status: "ready" | "degraded", clientId?: string): ClerkAuth => ({ status, isLoaded: true, isSignedIn: false, userId: null, + clientId, }); const signedInAs = (userId: string): ClerkAuth => ({ status: "ready", isLoaded: true, isSignedIn: true, userId, + clientId: "client-1", }); async function mountAuth( @@ -81,9 +91,9 @@ async function mountAuth( try { for (const state of rest) { testState.auth = state; - // Clerk announces status through its status event and auth state through a render. + // Clerk announces status and client changes through listeners and auth state through a render. await act(() => { - for (const listener of testState.statusListeners) listener(); + for (const listener of testState.clerkListeners) listener(); }); await screen.rerender({null}); } @@ -106,15 +116,29 @@ describe("ManagedRelayAuthProvider", () => { expect(activeAccount()).toBeNull(); }); + it("keeps saved relay environments when Clerk reports ready after offline fetches", async () => { + await using _screen = await mountAuth([loading, signedOut("ready")]); + + expect(testState.removeRelayEnvironments).not.toHaveBeenCalled(); + expect(activeAccount()).toBeNull(); + }); + it("removes relay environments once Clerk's API confirms there is no session", async () => { - await using _screen = await mountAuth([loading, signedOut("degraded"), signedOut("ready")]); + await using _screen = await mountAuth([ + loading, + signedOut("degraded"), + signedOut("ready", "client-1"), + ]); await vi.waitFor(() => expect(testState.removeRelayEnvironments).toHaveBeenCalledTimes(1)); expect(activeAccount()).toBeNull(); }); it("removes relay environments when the signed-in account signs out", async () => { - await using _screen = await mountAuth([signedInAs("account-1"), signedOut("ready")]); + await using _screen = await mountAuth([ + signedInAs("account-1"), + signedOut("ready", "client-1"), + ]); await vi.waitFor(() => expect(testState.removeRelayEnvironments).toHaveBeenCalledTimes(1)); expect(activeAccount()).toBeNull(); diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx index 496850dacdf00..ca628009a864b 100644 --- a/apps/web/src/cloud/managedAuth.tsx +++ b/apps/web/src/cloud/managedAuth.tsx @@ -33,16 +33,21 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac treatPendingAsSignedOut: false, }); const clerk = useClerk(); - const clerkStatus = useSyncExternalStore( + // "degraded" loads from local state when Clerk's API fails. "ready" alone is not proof either: + // while the browser reports offline, Clerk turns failed fetches into empty resources, leaving + // the client without the id every /v1/client response carries. + const clerkApiAnswered = useSyncExternalStore( (onChange) => { clerk.on("status", onChange); - return () => clerk.off("status", onChange); + const removeListener = clerk.addListener(onChange); + return () => { + clerk.off("status", onChange); + removeListener(); + }; }, - () => clerk.status, + () => clerk.status === "ready" && Boolean(clerk.client?.id), ); - // Clerk loads "degraded" from local state when its API is unreachable, often signed out, - // so only a "ready" load is Clerk's answer that no session exists. - const signedOutByClerkApi = !(isSignedIn && userId) && clerkStatus === "ready"; + const signedOutByClerkApi = !(isSignedIn && userId) && clerkApiAnswered; const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, { reportFailure: false, reportDefect: false, diff --git a/vite.config.ts b/vite.config.ts index 92a8d215c3bcb..b2216fa762e8d 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -305,6 +305,7 @@ export default defineConfig({ }, { files: [ + "apps/web/src/cloud/managedAuth.tsx", "apps/web/src/components/settings/AuthorizedClientsSettings.tsx", "apps/web/src/components/settings/ConnectionsSettings.tsx", "apps/mobile/src/features/updates/app-updates.ts", From 8c3f2e14e2269e1a0c75deb4b48eea1304eedbc8 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 24 Oct 2026 23:50:30 +0000 Subject: [PATCH 5/7] fix(web): a real Clerk client fetch after a degraded launch clears T3 Connect environments Clerk's status cannot prove its API answered. A real /v1/client response can arrive while the status stays degraded, so recognize it by its client id and exclude the client_init placeholder Clerk builds from the session cookie. Co-Authored-By: Claude Opus 5.5 --- .../src/cloud/managedAuth.browser.test.tsx | 26 ++++++++++++------- apps/web/src/cloud/managedAuth.tsx | 19 ++++++-------- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/apps/web/src/cloud/managedAuth.browser.test.tsx b/apps/web/src/cloud/managedAuth.browser.test.tsx index a957d7ac7c5e0..ce4a03696fafb 100644 --- a/apps/web/src/cloud/managedAuth.browser.test.tsx +++ b/apps/web/src/cloud/managedAuth.browser.test.tsx @@ -1,4 +1,3 @@ -import type { useClerk } from "@clerk/react"; import { managedRelaySessionAtom } from "@t3tools/client-runtime/relay"; import * as Exit from "effect/Exit"; import { AsyncResult } from "effect/reactivity"; @@ -8,7 +7,7 @@ import { act, render } from "../../test/render"; import { appAtomRegistry } from "../rpc/atomRegistry"; type ClerkAuth = { - status: ReturnType["status"]; + status: "loading" | "ready" | "degraded"; isLoaded: boolean; isSignedIn: boolean; userId: string | null; @@ -21,9 +20,6 @@ const testState = vi.hoisted(() => { auth: { status: "loading", isLoaded: false, isSignedIn: false, userId: null } as ClerkAuth, clerkListeners, clerk: { - get status() { - return testState.auth.status; - }, get client() { return { id: testState.auth.clientId }; }, @@ -31,8 +27,6 @@ const testState = vi.hoisted(() => { clerkListeners.add(listener); return () => void clerkListeners.delete(listener); }, - on: (_event: "status", listener: () => void) => void clerkListeners.add(listener), - off: (_event: "status", listener: () => void) => void clerkListeners.delete(listener), }, getToken: async () => "clerk-token", removeRelayEnvironments: vi.fn(), @@ -91,7 +85,7 @@ async function mountAuth( try { for (const state of rest) { testState.auth = state; - // Clerk announces status and client changes through listeners and auth state through a render. + // Clerk announces client changes through listeners and auth state through a render. await act(() => { for (const listener of testState.clerkListeners) listener(); }); @@ -110,7 +104,7 @@ const activeAccount = () => appAtomRegistry.get(managedRelaySessionAtom)?.accoun describe("ManagedRelayAuthProvider", () => { it("keeps saved relay environments when Clerk cannot reach its API at launch", async () => { - await using _screen = await mountAuth([loading, signedOut("degraded")]); + await using _screen = await mountAuth([loading, signedOut("degraded", "client_init")]); expect(testState.removeRelayEnvironments).not.toHaveBeenCalled(); expect(activeAccount()).toBeNull(); @@ -134,6 +128,20 @@ describe("ManagedRelayAuthProvider", () => { expect(activeAccount()).toBeNull(); }); + it("removes relay environments once Clerk's API answers while its status stays degraded", async () => { + await using _screen = await mountAuth([loading, signedOut("degraded", "client_init")]); + expect(testState.removeRelayEnvironments).not.toHaveBeenCalled(); + + // The retried client fetch only notifies resource listeners; Clerk's status and auth stay put. + testState.auth = signedOut("degraded", "client-1"); + await act(() => { + for (const listener of testState.clerkListeners) listener(); + }); + + await vi.waitFor(() => expect(testState.removeRelayEnvironments).toHaveBeenCalledTimes(1)); + expect(activeAccount()).toBeNull(); + }); + it("removes relay environments when the signed-in account signs out", async () => { await using _screen = await mountAuth([ signedInAs("account-1"), diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx index ca628009a864b..e35a8029c86ab 100644 --- a/apps/web/src/cloud/managedAuth.tsx +++ b/apps/web/src/cloud/managedAuth.tsx @@ -33,19 +33,16 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac treatPendingAsSignedOut: false, }); const clerk = useClerk(); - // "degraded" loads from local state when Clerk's API fails. "ready" alone is not proof either: - // while the browser reports offline, Clerk turns failed fetches into empty resources, leaving - // the client without the id every /v1/client response carries. + // Clerk's status cannot prove its API answered: while offline it reports "ready" with an empty, + // id-less client, and a failed launch fetch reports "degraded" with a "client_init" placeholder + // built from the session cookie. A real /v1/client response always carries its own id, and can + // arrive later while the status stays "degraded". const clerkApiAnswered = useSyncExternalStore( - (onChange) => { - clerk.on("status", onChange); - const removeListener = clerk.addListener(onChange); - return () => { - clerk.off("status", onChange); - removeListener(); - }; + (onChange) => clerk.addListener(onChange), + () => { + const clientId = clerk.client?.id; + return Boolean(clientId) && clientId !== "client_init"; }, - () => clerk.status === "ready" && Boolean(clerk.client?.id), ); const signedOutByClerkApi = !(isSignedIn && userId) && clerkApiAnswered; const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, { From 65637ec020438e9bf200645d36910374f3870279 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 25 Oct 2026 01:15:11 +0000 Subject: [PATCH 6/7] fix(web): signing out of T3 Connect removes relay environments from the open app ManagedRelayAuthProvider mounts above AppAtomRegistryProvider, so its context-bound cleanup command ran on the default registry. IndexedDB lost the relay environments while the rendered app kept showing them until reload. Run the cleanup on appAtomRegistry, like session activation already does. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/cloud/managedAuth.browser.test.tsx | 6 ++++-- apps/web/src/cloud/managedAuth.tsx | 15 ++++++++------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/apps/web/src/cloud/managedAuth.browser.test.tsx b/apps/web/src/cloud/managedAuth.browser.test.tsx index ce4a03696fafb..f0b84fd615578 100644 --- a/apps/web/src/cloud/managedAuth.browser.test.tsx +++ b/apps/web/src/cloud/managedAuth.browser.test.tsx @@ -38,9 +38,9 @@ vi.mock(import("@clerk/react"), async (original) => ({ useAuth: (() => ({ ...testState.auth, getToken: testState.getToken })) as never, useClerk: (() => testState.clerk) as never, })); -vi.mock(import("../state/use-atom-command"), async (original) => ({ +vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({ ...(await original()), - useAtomCommand: (() => testState.removeRelayEnvironments) as never, + runAtomCommand: ((registry: unknown) => testState.removeRelayEnvironments(registry)) as never, })); vi.mock(import("../lib/runtime"), async (original) => ({ ...(await original()), @@ -149,6 +149,8 @@ describe("ManagedRelayAuthProvider", () => { ]); await vi.waitFor(() => expect(testState.removeRelayEnvironments).toHaveBeenCalledTimes(1)); + // The provider renders outside AppAtomRegistryProvider, yet the app reads this registry. + expect(testState.removeRelayEnvironments).toHaveBeenCalledWith(appAtomRegistry); expect(activeAccount()).toBeNull(); }); diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx index e35a8029c86ab..bfafb5f5556aa 100644 --- a/apps/web/src/cloud/managedAuth.tsx +++ b/apps/web/src/cloud/managedAuth.tsx @@ -2,6 +2,7 @@ import { useAuth, useClerk } from "@clerk/react"; import { ManagedRelay, setManagedRelaySession } from "@t3tools/client-runtime/relay"; import { reportAtomCommandResult, + runAtomCommand, settleAsyncResult, settlePromise, } from "@t3tools/client-runtime/state/runtime"; @@ -11,7 +12,6 @@ import { useEffect, useRef, useSyncExternalStore, type ReactNode } from "react"; import { environmentCatalog } from "../connection/catalog"; import { runtime } from "../lib/runtime"; import { appAtomRegistry } from "../rpc/atomRegistry"; -import { useAtomCommand } from "../state/use-atom-command"; import { resolveRelayClerkTokenOptions } from "./publicConfig"; export function deactivateManagedRelayAuthentication(): void { @@ -45,10 +45,6 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac }, ); const signedOutByClerkApi = !(isSignedIn && userId) && clerkApiAnswered; - const removeRelayEnvironments = useAtomCommand(environmentCatalog.removeRelayEnvironments, { - reportFailure: false, - reportDefect: false, - }); const observedAccountRef = useRef(undefined); const accountTransitionRef = useRef | null>(null); @@ -68,7 +64,12 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac const previousTransition = accountTransitionRef.current ?? Promise.resolve(); accountTransitionRef.current = previousTransition.then(async () => { const results = await Promise.all([ - removeRelayEnvironments(), + // This provider mounts above AppAtomRegistryProvider, so a context-bound command would + // clear a registry the rendered app never reads. + runAtomCommand(appAtomRegistry, environmentCatalog.removeRelayEnvironments, undefined, { + reportFailure: false, + reportDefect: false, + }), settleAsyncResult(() => runtime.runPromiseExit( ManagedRelay.ManagedRelayClient.pipe( @@ -115,7 +116,7 @@ export function ManagedRelayAuthProvider({ children }: { readonly children: Reac return () => { cancelled = true; }; - }, [getToken, isLoaded, isSignedIn, removeRelayEnvironments, signedOutByClerkApi, userId]); + }, [getToken, isLoaded, isSignedIn, signedOutByClerkApi, userId]); useEffect(() => () => deactivateManagedRelayAuthentication(), []); From dd612baea156ac40428c991e0dcdffc90bc331b9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 22:00:16 +0000 Subject: [PATCH 7/7] fix(client): offline launch no longer deletes T3 Connect environments Clerk emits a signed-out user when its API is unreachable at launch: an id-less client while offline, or a "client_init" placeholder built from the session cookie. The cloud account service treated that first emission as a confirmed sign-out and removed every saved relay environment. It now stays unobserved until a real Clerk client arrives, while a sign-out after a signed-in emission still cleans up immediately. AI-assisted; verified with the tests and tools listed above. Co-Authored-By: Claude Opus 5.5 --- .../src/relay/cloudAccountService.test.ts | 271 +++++++++++++++++ .../src/relay/cloudAccountService.ts | 236 +++++++++++++++ .../src/relay/discovery.test.ts | 111 ++++++- .../client-runtime/src/relay/discovery.ts | 42 ++- .../src/relay/dpopProof.test.ts | 78 +++++ .../client-runtime/src/relay/dpopProof.ts | 111 +++++++ .../src/relay/errorPresentation.ts | 12 +- packages/client-runtime/src/relay/index.ts | 2 + .../src/relay/managedRelay.test.ts | 2 +- .../client-runtime/src/relay/managedRelay.ts | 82 ++++- .../src/relay/managedRelayState.test.ts | 90 +++++- .../src/relay/managedRelayState.ts | 283 ++++++++---------- 12 files changed, 1133 insertions(+), 187 deletions(-) create mode 100644 packages/client-runtime/src/relay/cloudAccountService.test.ts create mode 100644 packages/client-runtime/src/relay/cloudAccountService.ts create mode 100644 packages/client-runtime/src/relay/dpopProof.test.ts create mode 100644 packages/client-runtime/src/relay/dpopProof.ts diff --git a/packages/client-runtime/src/relay/cloudAccountService.test.ts b/packages/client-runtime/src/relay/cloudAccountService.test.ts new file mode 100644 index 0000000000000..1549f9e4f6a62 --- /dev/null +++ b/packages/client-runtime/src/relay/cloudAccountService.test.ts @@ -0,0 +1,271 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + type CloudAccountSource, + createCloudAccountService, + planCloudAccountStep, +} from "./cloudAccountService.ts"; + +type Emit = (user: { readonly id: string } | null | undefined, clientId?: string) => void; + +function makeSource() { + let listener: Parameters[0] | null = null; + const source: CloudAccountSource = { + addListener: (next) => { + listener = next; + return () => { + listener = null; + }; + }, + }; + const emit: Emit = (user, clientId = "client_1") => + listener?.({ user, client: { id: clientId } }); + return { source, emit, isSubscribed: () => listener !== null }; +} + +function makeService() { + const log: string[] = []; + const activated: Array> = []; + const cleanedUp: Array> = []; + const gates = new Map< + string, + { readonly started: PromiseWithResolvers; readonly release: PromiseWithResolvers } + >(); + const service = createCloudAccountService({ + deactivate: () => log.push("deactivate"), + detach: () => log.push("detach"), + onSignOutTransition: () => log.push("signOutTransition"), + cleanUp: async ({ accountId, wasActive }) => { + log.push(`cleanUp:${accountId}:${wasActive}`); + cleanedUp.shift()?.resolve(); + }, + prepare: async ({ accountId }) => { + log.push(`prepare:${accountId}`); + const gate = gates.get(accountId); + gate?.started.resolve(); + await gate?.release.promise; + }, + activate: ({ accountId, isAccountTransition }) => { + log.push(`activate:${accountId}:${isAccountTransition}`); + activated.shift()?.resolve(); + }, + }); + const nextActivation = () => { + const deferred = Promise.withResolvers(); + activated.push(deferred); + return deferred.promise; + }; + const nextCleanUp = () => { + const deferred = Promise.withResolvers(); + cleanedUp.push(deferred); + return deferred.promise; + }; + const gate = (accountId: string) => { + const deferred = { + started: Promise.withResolvers(), + release: Promise.withResolvers(), + }; + gates.set(accountId, deferred); + return deferred; + }; + return { service, log, nextActivation, nextCleanUp, gate }; +} + +describe("planCloudAccountStep", () => { + it("treats the first observation as a non-transition", () => { + expect(planCloudAccountStep(undefined, "a")).toEqual({ + _tag: "SignIn", + accountId: "a", + switchFromAccountId: null, + isAccountTransition: false, + }); + expect(planCloudAccountStep(undefined, null)).toEqual({ + _tag: "SignOut", + previousAccountId: null, + isAccountTransition: false, + }); + }); + + it("ignores repeats and switches from the previous account", () => { + expect(planCloudAccountStep("a", "a")).toEqual({ _tag: "None" }); + expect(planCloudAccountStep(null, null)).toEqual({ _tag: "None" }); + expect(planCloudAccountStep("a", "b")).toEqual({ + _tag: "SignIn", + accountId: "b", + switchFromAccountId: "a", + isAccountTransition: true, + }); + }); +}); + +describe("createCloudAccountService", () => { + it("activates once per account however often Clerk emits", async () => { + const { service, log, nextActivation } = makeService(); + const { source, emit } = makeSource(); + service.attach(source); + + emit(undefined); + expect(service.getState()).toEqual({ _tag: "Unobserved" }); + const activation = nextActivation(); + emit({ id: "a" }); + emit({ id: "a" }); + expect(service.getState()).toEqual({ _tag: "Activating", accountId: "a" }); + await activation; + + expect(service.getState()).toEqual({ _tag: "Active", accountId: "a" }); + expect(log).toEqual(["prepare:a", "activate:a:false"]); + }); + + it("drops credentials synchronously and cleans up before activating the next account", async () => { + const { service, log, nextActivation } = makeService(); + const { source, emit } = makeSource(); + service.attach(source); + const first = nextActivation(); + emit({ id: "a" }); + await first; + log.length = 0; + + const second = nextActivation(); + emit({ id: "b" }); + expect(log).toEqual(["deactivate"]); + await second; + + expect(log).toEqual(["deactivate", "cleanUp:a:true", "prepare:b", "activate:b:true"]); + }); + + it("cleans up on sign-out, including a signed-out first observation", async () => { + const { service, log, nextActivation, nextCleanUp } = makeService(); + const { source, emit } = makeSource(); + service.attach(source); + + const initialCleanUp = nextCleanUp(); + emit(null); + await initialCleanUp; + expect(log).toEqual(["deactivate", "cleanUp:null:false"]); + + const activation = nextActivation(); + emit({ id: "a" }); + await activation; + log.length = 0; + + const cleanUp = nextCleanUp(); + emit(null); + await cleanUp; + expect(service.getState()).toEqual({ _tag: "SignedOut" }); + expect(log).toEqual(["signOutTransition", "deactivate", "cleanUp:a:true"]); + }); + + it("waits for Clerk's API to confirm a signed-out launch before cleaning up", async () => { + const { service, log, nextActivation, nextCleanUp } = makeService(); + const { source, emit } = makeSource(); + service.attach(source); + + // Offline: an id-less client, or the placeholder built from the session cookie. + emit(null, ""); + emit(null, "client_init"); + expect(service.getState()).toEqual({ _tag: "Unobserved" }); + expect(log).toEqual([]); + + const cleanUp = nextCleanUp(); + emit(null); + await cleanUp; + expect(log).toEqual(["deactivate", "cleanUp:null:false"]); + + const activation = nextActivation(); + emit({ id: "a" }); + await activation; + log.length = 0; + const signOut = nextCleanUp(); + emit(null, "client_init"); + await signOut; + expect(log).toEqual(["signOutTransition", "deactivate", "cleanUp:a:true"]); + }); + + it("never activates an account that signed out while it was activating", async () => { + const { service, log, nextCleanUp, gate } = makeService(); + const { source, emit } = makeSource(); + service.attach(source); + const prepared = gate("a"); + emit({ id: "a" }); + await prepared.started.promise; + const cleanUp = nextCleanUp(); + emit(null); + prepared.release.resolve(); + await cleanUp; + + expect(service.getState()).toEqual({ _tag: "SignedOut" }); + expect(log).toEqual(["prepare:a", "signOutTransition", "deactivate", "cleanUp:a:false"]); + }); + + it("retries a rejected activation on the next emission for the same account", async () => { + const log: string[] = []; + const failed = Promise.withResolvers(); + const activated = Promise.withResolvers(); + let attempts = 0; + const service = createCloudAccountService({ + deactivate: () => log.push("deactivate"), + detach: () => log.push("detach"), + cleanUp: async ({ accountId, wasActive }) => { + log.push(`cleanUp:${accountId}:${wasActive}`); + }, + prepare: async ({ accountId }) => { + attempts += 1; + log.push(`prepare:${accountId}`); + if (attempts === 1) { + // Queued before the rejection, so the service's catch runs before + // the test's `await failed.promise` continuation. + queueMicrotask(failed.resolve); + throw new Error("restore failed"); + } + }, + activate: ({ accountId, isAccountTransition }) => { + log.push(`activate:${accountId}:${isAccountTransition}`); + activated.resolve(); + }, + }); + const { source, emit } = makeSource(); + service.attach(source); + emit(null); + emit({ id: "a" }); + await failed.promise; + expect(service.getState()).toMatchObject({ _tag: "Failed", accountId: "a" }); + + emit({ id: "a" }); + await activated.promise; + + expect(service.getState()).toEqual({ _tag: "Active", accountId: "a" }); + expect(log).toEqual([ + "deactivate", + "cleanUp:null:false", + "prepare:a", + "prepare:a", + "activate:a:true", + ]); + }); + + it("detaches from a replaced Clerk instance", () => { + const { service, log } = makeService(); + const first = makeSource(); + const second = makeSource(); + service.attach(first.source); + service.attach(second.source); + + expect(first.isSubscribed()).toBe(false); + expect(second.isSubscribed()).toBe(true); + expect(log).toEqual(["detach"]); + }); + + it("releases credentials and stops observing when detached", async () => { + const { service, log, nextActivation } = makeService(); + const { source, emit, isSubscribed } = makeSource(); + const detach = service.attach(source); + const activation = nextActivation(); + emit({ id: "a" }); + await activation; + + detach(); + expect(isSubscribed()).toBe(false); + expect(service.getState()).toEqual({ _tag: "Unobserved" }); + expect(log).toEqual(["prepare:a", "activate:a:false", "detach"]); + }); +}); diff --git a/packages/client-runtime/src/relay/cloudAccountService.ts b/packages/client-runtime/src/relay/cloudAccountService.ts new file mode 100644 index 0000000000000..7f885281d3b90 --- /dev/null +++ b/packages/client-runtime/src/relay/cloudAccountService.ts @@ -0,0 +1,236 @@ +import { reportAtomCommandResult, settlePromise } from "../state/runtime.ts"; + +/** + * The slice of a Clerk instance the account service needs. Clerk emits on + * every resource change (token refreshes, profile edits), so the service + * dedupes emissions down to account changes. + */ +export interface CloudAccountSource { + readonly addListener: ( + listener: (resources: { + readonly client?: { readonly id?: string | null | undefined } | null | undefined; + readonly user?: { readonly id: string } | null | undefined; + }) => void, + ) => () => void; +} + +/** + * Clerk's load status cannot prove its API answered: offline it emits an + * id-less client, and a failed launch fetch emits a "client_init" placeholder + * built from the session cookie. Only a real /v1/client response has an id. + */ +const isClientFromClerkApi = ( + client: { readonly id?: string | null | undefined } | null | undefined, +) => Boolean(client?.id) && client?.id !== "client_init"; + +interface CloudAccountSignIn { + readonly _tag: "SignIn"; + readonly accountId: string; + /** Signed-in account being replaced; its data is removed before activation. */ + readonly switchFromAccountId: string | null; + readonly isAccountTransition: boolean; +} + +export type CloudAccountStep = + | { readonly _tag: "None" } + | { + readonly _tag: "SignOut"; + /** Account whose data is removed; null removes data of any account. */ + readonly previousAccountId: string | null; + readonly isAccountTransition: boolean; + } + | CloudAccountSignIn; + +/** + * `previous` is undefined until Clerk's first emission. A first emission that + * is signed out still cleans up, so data left by an account that signed out + * while the app was closed does not linger. The service only plans that step + * once Clerk's API has confirmed the sign-out. + */ +export function planCloudAccountStep( + previous: string | null | undefined, + next: string | null, +): CloudAccountStep { + if (previous === next) return { _tag: "None" }; + const isAccountTransition = previous !== undefined; + if (next === null) { + return { _tag: "SignOut", previousAccountId: previous ?? null, isAccountTransition }; + } + return { + _tag: "SignIn", + accountId: next, + switchFromAccountId: previous ?? null, + isAccountTransition, + }; +} + +export interface CloudAccountHandlers { + /** Synchronously drops every credential so nothing reads the old account during cleanup. */ + readonly deactivate: () => void; + readonly cleanUp: (input: { + readonly source: S; + readonly accountId: string | null; + /** Whether `accountId` finished activating, so per-account registrations exist. */ + readonly wasActive: boolean; + }) => Promise; + /** Async work that must finish before the session is visible (draft restore etc.). */ + readonly prepare?: (input: { + readonly source: S; + readonly accountId: string; + readonly isCurrent: () => boolean; + }) => Promise; + readonly activate: (input: { + readonly source: S; + readonly accountId: string; + readonly isAccountTransition: boolean; + }) => void; + readonly onSignOutTransition?: () => void; + /** Releases credentials when the service stops observing a Clerk instance. */ + readonly detach: () => void; +} + +export type CloudAccountState = + | { readonly _tag: "Unobserved" } + | { readonly _tag: "SignedOut" } + | { readonly _tag: "Activating"; readonly accountId: string } + | { readonly _tag: "Active"; readonly accountId: string } + /** + * Activation rejected. The next emission for the same account retries the + * original step, so a transient failure recovers on Clerk's next resource + * change (token refreshes emit regularly) without re-requesting onboarding. + */ + | { + readonly _tag: "Failed"; + readonly accountId: string; + readonly step: CloudAccountSignIn; + readonly wasActive: boolean; + }; + +export interface CloudAccountService { + /** + * Observes `source` until the returned function runs. Attaching while another + * source is attached detaches that one first. + */ + readonly attach: (source: S) => () => void; + readonly getState: () => CloudAccountState; +} + +export function createCloudAccountService( + handlers: CloudAccountHandlers, +): CloudAccountService { + let attached: { readonly source: S; readonly unsubscribe: () => void } | null = null; + let state: CloudAccountState = { _tag: "Unobserved" }; + // Bumped on every account change so a superseded activation never applies. + let generation = 0; + let tail: Promise = Promise.resolve(); + + const enqueue = (label: string, operation: () => Promise) => { + const run = tail.then(operation, operation); + tail = run.then( + () => undefined, + () => undefined, + ); + void settlePromise(() => run).then((result) => reportAtomCommandResult(result, { label })); + }; + + const observedAccount = (): string | null | undefined => { + switch (state._tag) { + case "Unobserved": + return undefined; + case "SignedOut": + return null; + default: + return state.accountId; + } + }; + + const activate = (source: S, step: CloudAccountSignIn, wasActive: boolean) => { + const activation = generation; + const isCurrent = () => activation === generation; + state = { _tag: "Activating", accountId: step.accountId }; + if (step.switchFromAccountId !== null) handlers.deactivate(); + enqueue("cloud account activation", async () => { + try { + if (step.switchFromAccountId !== null) { + await handlers.cleanUp({ source, accountId: step.switchFromAccountId, wasActive }); + } + if (!isCurrent()) return; + await handlers.prepare?.({ source, accountId: step.accountId, isCurrent }); + } catch (error) { + if (isCurrent()) state = { _tag: "Failed", accountId: step.accountId, step, wasActive }; + throw error; + } + if (!isCurrent()) return; + state = { _tag: "Active", accountId: step.accountId }; + handlers.activate({ + source, + accountId: step.accountId, + isAccountTransition: step.isAccountTransition, + }); + }); + }; + + const observe = (source: S, next: string | null) => { + const previousState = state; + if (previousState._tag === "Failed" && previousState.accountId === next) { + generation += 1; + activate(source, previousState.step, previousState.wasActive); + return; + } + const step = planCloudAccountStep(observedAccount(), next); + if (step._tag === "None") return; + generation += 1; + const wasActive = previousState._tag === "Active"; + + if (step._tag === "SignOut") { + state = { _tag: "SignedOut" }; + if (step.isAccountTransition) handlers.onSignOutTransition?.(); + handlers.deactivate(); + enqueue("cloud account cleanup", () => + handlers.cleanUp({ source, accountId: step.previousAccountId, wasActive }), + ); + return; + } + + activate(source, step, wasActive); + }; + + const detach = () => { + if (!attached) return; + attached.unsubscribe(); + attached = null; + generation += 1; + state = { _tag: "Unobserved" }; + handlers.detach(); + }; + + return { + attach(source) { + detach(); + const current = { + source, + unsubscribe: source.addListener((resources) => { + // Clerk reports `user: undefined` until it loads; pending sessions + // still carry a user and count as signed in. + if (resources.user === undefined) return; + const next = resources.user?.id ?? null; + // An unreachable Clerk API at launch looks signed out; stay unobserved + // until Clerk confirms it, so saved environments survive offline starts. + if ( + next === null && + state._tag === "Unobserved" && + !isClientFromClerkApi(resources.client) + ) { + return; + } + observe(source, next); + }), + }; + attached = current; + return () => { + if (attached === current) detach(); + }; + }, + getState: () => state, + }; +} diff --git a/packages/client-runtime/src/relay/discovery.test.ts b/packages/client-runtime/src/relay/discovery.test.ts index 53ded8855bddb..9332652df39b5 100644 --- a/packages/client-runtime/src/relay/discovery.test.ts +++ b/packages/client-runtime/src/relay/discovery.test.ts @@ -12,6 +12,7 @@ import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; +import { Atom, AtomRegistry } from "effect/reactivity"; import * as ManagedRelay from "./managedRelay.ts"; import * as ClientCapabilities from "../platform/capabilities.ts"; @@ -20,6 +21,7 @@ import { ConnectionBlockedError, type NetworkStatus } from "../connection/model. import * as ConnectionWakeups from "../connection/wakeups.ts"; import * as RelayEnvironmentDiscovery from "./discovery.ts"; import { NETWORK_BLOCKING_HINT } from "../errors/network.ts"; +import { createRelayEnvironmentDiscoveryAtoms } from "../state/relayDiscovery.ts"; const environments = [ { @@ -59,6 +61,8 @@ function status( const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () { const networkStatus = yield* SubscriptionRef.make("online"); const listCalls = yield* Ref.make(0); + const listedEnvironments = + yield* Ref.make>(environments); const listFailure = yield* Ref.make(null); const secondListCall = yield* Deferred.make(); const clerkToken = yield* Ref.make("clerk-token"); @@ -100,7 +104,7 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () { if (failure) { return yield* failure; } - return environments; + return yield* Ref.get(listedEnvironments); }), getEnvironmentStatus: ({ environmentId }) => Ref.get(statusRequests).pipe( @@ -110,6 +114,9 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () { createEnvironmentLinkChallenge: () => Effect.die("unused"), linkEnvironment: () => Effect.die("unused"), unlinkEnvironment: () => Effect.die("unused"), + getT3ChatLink: () => Effect.die("unused"), + createT3ChatLinkRequest: () => Effect.die("unused"), + unlinkT3Chat: () => Effect.die("unused"), connectEnvironment: () => Effect.die("unused"), registerDevice: () => Effect.die("unused"), unregisterDevice: () => Effect.die("unused"), @@ -162,6 +169,7 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () { return { layer, listCalls, + listedEnvironments, listFailure, clerkToken, networkStatus, @@ -176,6 +184,51 @@ const makeHarness = Effect.fn("RelayDiscoveryTest.makeHarness")(function* () { }); describe("RelayEnvironmentDiscovery", () => { + it.effect("fetches a fresh list after removal while an older refresh is checking statuses", () => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* Effect.gen(function* () { + const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery; + const atoms = createRelayEnvironmentDiscoveryAtoms( + Atom.runtime( + Layer.succeed(RelayEnvironmentDiscovery.RelayEnvironmentDiscovery, discovery), + ), + ); + const registry = AtomRegistry.make(); + yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); + + const refresh = atoms.refresh.run(registry, undefined); + yield* SubscriptionRef.changes(discovery.state).pipe( + Stream.filter((state) => state.environments.size === environments.length), + Stream.runHead, + ); + const coalescedRefresh = atoms.refresh.run(registry, undefined); + yield* Ref.set(harness.listedEnvironments, [environments[1]!]); + const mutationRefresh = atoms.refreshAfterMutation.run(registry, undefined); + + const requests = yield* Ref.get(harness.statusRequests); + for (const environment of environments) { + yield* Deferred.succeed( + requests.get(environment.environmentId)!, + status(environment, "online"), + ); + } + const results = yield* Effect.promise(() => + Promise.all([refresh, coalescedRefresh, mutationRefresh]), + ); + for (const result of results) { + expect(result._tag).toBe("Success"); + } + expect(yield* Ref.get(harness.listCalls)).toBe(2); + const complete = yield* SubscriptionRef.get(discovery.state); + expect([...complete.environments.keys()]).toEqual([environments[1]!.environmentId]); + expect(complete.refreshing).toBe(false); + }).pipe(Effect.provide(harness.layer)); + }), + ), + ); + it.effect("publishes each environment status as soon as that lookup completes", () => Effect.gen(function* () { const harness = yield* makeHarness(); @@ -225,6 +278,38 @@ describe("RelayEnvironmentDiscovery", () => { }), ); + it.effect("reports an environment as unregistered only once the relay list has loaded", () => + Effect.gen(function* () { + const harness = yield* makeHarness(); + yield* Effect.gen(function* () { + const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery; + const listed = environments[0]!.environmentId; + const deregistered = "deregistered-environment"; + const before = yield* SubscriptionRef.get(discovery.state); + expect(RelayEnvironmentDiscovery.relayEnvironmentRegistration(before, deregistered)).toBe( + "unknown", + ); + + const requests = yield* Ref.get(harness.statusRequests); + for (const environment of environments) { + yield* Deferred.succeed( + requests.get(environment.environmentId)!, + status(environment, "online"), + ); + } + yield* discovery.refresh; + + const after = yield* SubscriptionRef.get(discovery.state); + expect(RelayEnvironmentDiscovery.relayEnvironmentRegistration(after, listed)).toBe( + "registered", + ); + expect(RelayEnvironmentDiscovery.relayEnvironmentRegistration(after, deregistered)).toBe( + "unregistered", + ); + }).pipe(Effect.provide(harness.layer)); + }), + ); + it.effect( "preserves discovered rows while offline and refreshes after connectivity returns", () => @@ -275,6 +360,9 @@ describe("RelayEnvironmentDiscovery", () => { createEnvironmentLinkChallenge: () => Effect.die("unused"), linkEnvironment: () => Effect.die("unused"), unlinkEnvironment: () => Effect.die("unused"), + getT3ChatLink: () => Effect.die("unused"), + createT3ChatLinkRequest: () => Effect.die("unused"), + unlinkT3Chat: () => Effect.die("unused"), connectEnvironment: () => Effect.die("unused"), registerDevice: () => Effect.die("unused"), unregisterDevice: () => Effect.die("unused"), @@ -344,6 +432,12 @@ describe("RelayEnvironmentDiscovery", () => { const failed = yield* SubscriptionRef.get(discovery.state); expect(failed.environments.size).toBe(0); expect(Option.isSome(failed.error)).toBe(true); + expect( + RelayEnvironmentDiscovery.relayEnvironmentRegistration( + failed, + environments[0]!.environmentId, + ), + ).toBe("unknown"); }).pipe(Effect.provide(harness.layer)); }), ); @@ -391,6 +485,12 @@ describe("RelayEnvironmentDiscovery", () => { expect(state.environments.size).toBe(0); expect(state.refreshing).toBe(false); expect(Option.isNone(state.error)).toBe(true); + expect( + RelayEnvironmentDiscovery.relayEnvironmentRegistration( + state, + environments[0]!.environmentId, + ), + ).toBe("unknown"); }).pipe(Effect.provide(harness.layer)); }), ); @@ -423,7 +523,14 @@ describe("RelayEnvironmentDiscovery", () => { yield* Fiber.join(refreshFiber); yield* Effect.yieldNow; - expect((yield* SubscriptionRef.get(discovery.state)).environments.size).toBe(0); + const signedOut = yield* SubscriptionRef.get(discovery.state); + expect(signedOut.environments.size).toBe(0); + expect( + RelayEnvironmentDiscovery.relayEnvironmentRegistration( + signedOut, + environments[0]!.environmentId, + ), + ).toBe("unknown"); }).pipe(Effect.provide(harness.layer), Effect.scoped); }), ); diff --git a/packages/client-runtime/src/relay/discovery.ts b/packages/client-runtime/src/relay/discovery.ts index bd7126f7f2b61..63dadc6cadfc6 100644 --- a/packages/client-runtime/src/relay/discovery.ts +++ b/packages/client-runtime/src/relay/discovery.ts @@ -34,6 +34,8 @@ export interface RelayDiscoveredEnvironment { export interface RelayEnvironmentDiscoveryState { readonly environments: ReadonlyMap; + // Only a loaded account list distinguishes a missing registration from an unknown one. + readonly listed: boolean; readonly refreshing: boolean; readonly offline: boolean; readonly error: Option.Option; @@ -49,11 +51,22 @@ export class RelayEnvironmentDiscovery extends Context.Service< export const EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE: RelayEnvironmentDiscoveryState = { environments: new Map(), + listed: false, refreshing: false, offline: false, error: Option.none(), }; +export type RelayEnvironmentRegistration = "registered" | "unregistered" | "unknown"; + +export function relayEnvironmentRegistration( + state: RelayEnvironmentDiscoveryState, + environmentId: string, +): RelayEnvironmentRegistration { + if (state.environments.has(environmentId)) return "registered"; + return state.listed ? "unregistered" : "unknown"; +} + function validateStatus( environment: RelayClientEnvironmentRecord, status: RelayEnvironmentStatusResponse, @@ -92,17 +105,15 @@ function validateStatus( return Effect.succeed(status); } -function relayAccountId(clerkToken: string): Option.Option { - try { - return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe( - Option.filter((subject) => subject.length > 0), - ); - } catch { - return Option.none(); - } -} +const relayAccountId = Effect.fn("clientRuntime.discovery.relayAccountId")(function* ( + clerkToken: string, +) { + const claims = yield* decodeRelayJwt(clerkToken).pipe(Effect.option); + const sub = Option.isSome(claims) ? claims.value.sub : undefined; + return typeof sub === "string" && sub.length > 0 ? Option.some(sub) : Option.none(); +}); -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () { const relay = yield* ManagedRelay.ManagedRelayClient; const session = yield* ClientCapabilities.CloudSession; @@ -218,16 +229,14 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () { yield* Ref.set(refreshGeneration, generation); yield* SubscriptionRef.set(state, { environments: new Map(), + listed: false, refreshing: true, offline: false, error: Option.none(), }); - // Signed out is the idle state, not a failure: the proactive refresh on - // credentials-changed also runs on sign-out and must settle back to a - // clean empty list. Only the session-level "no credentials" error is - // benign — relay-side auth failures (expired/invalid tokens) happen - // after this point and must surface as errors. + // Sign-out triggers credentials-changed refreshes and must settle to an empty list. + // Only session-level missing credentials are benign; relay-side auth failures must surface. const tokenResult = yield* Effect.result(session.clerkToken); if (tokenResult._tag === "Failure") { const failure = tokenResult.failure; @@ -247,7 +256,7 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () { if ((yield* Ref.get(accountGeneration)) !== generation) { return; } - const accountId = relayAccountId(clerkToken); + const accountId = yield* relayAccountId(clerkToken); const previousAccountId = yield* Ref.get(activeAccountId); if ( Option.isSome(previousAccountId) && @@ -276,6 +285,7 @@ export const make = Effect.fn("RelayEnvironmentDiscovery.make")(function* () { yield* SubscriptionRef.update(state, (current) => ({ ...current, environments: next, + listed: true, })); yield* Effect.forEach( diff --git a/packages/client-runtime/src/relay/dpopProof.test.ts b/packages/client-runtime/src/relay/dpopProof.test.ts new file mode 100644 index 0000000000000..bced68c504b00 --- /dev/null +++ b/packages/client-runtime/src/relay/dpopProof.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from "@effect/vitest"; +import { DpopPublicJwk, verifyDpopProof } from "@t3tools/shared/dpop"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Signature from "effect/crypto/Signature"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as TestClock from "effect/testing/TestClock"; + +import * as DpopProof from "./dpopProof.ts"; + +const decodePublicJwk = Schema.decodeUnknownEffect(DpopPublicJwk); + +const layer = Layer.mergeAll(Digest.layerWebCrypto, Signature.layerWebCrypto).pipe( + Layer.provideMerge(SecureRandom.layerWebCrypto), +); + +// Mirrors the web adapter: a non-extractable WebCrypto key signed through Signature. +const webCryptoProofKey = Effect.gen(function* () { + const signature = yield* Signature.Signature; + const pair = yield* Effect.promise( + () => + crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, [ + "sign", + "verify", + ]) as Promise, + ); + const publicJwk = yield* Effect.promise(() => + crypto.subtle.exportKey("jwk", pair.publicKey), + ).pipe(Effect.flatMap(decodePublicJwk), Effect.orDie); + const privateKey = yield* Signature.privateKeyFromCryptoKey( + Signature.ecdsaP256, + pair.privateKey, + ).pipe(Effect.orDie); + return { + publicJwk, + sign: (data) => signature.sign(privateKey, data).pipe(Effect.orDie), + } satisfies DpopProof.DpopProofKey; +}); + +describe("DpopProof", () => { + it.effect("creates proofs the relay verifier accepts, with htu normalized and ath bound", () => + Effect.gen(function* () { + yield* TestClock.setTime(1_700_000_000_000); + const key = yield* webCryptoProofKey; + const thumbprint = yield* DpopProof.thumbprint(key.publicJwk); + const url = "https://relay.example.test/v1/environments/env-1/connect?debug=1#ignored"; + const proof = yield* DpopProof.createProof({ + method: "post", + url, + accessToken: "relay-access-token", + key, + }); + + expect( + verifyDpopProof({ + proof, + method: "POST", + url, + expectedThumbprint: thumbprint, + expectedAccessToken: "relay-access-token", + nowEpochSeconds: 1_700_000_000, + }), + ).toMatchObject({ ok: true, thumbprint }); + }).pipe(Effect.provide(layer)), + ); + + it.effect("rejects an unparseable URL before signing", () => + Effect.gen(function* () { + const key = yield* webCryptoProofKey; + const error = yield* Effect.flip( + DpopProof.createProof({ method: "GET", url: "not a url", key }), + ); + expect(error.message).toBe("DPoP URL is invalid."); + }).pipe(Effect.provide(layer)), + ); +}); diff --git a/packages/client-runtime/src/relay/dpopProof.ts b/packages/client-runtime/src/relay/dpopProof.ts new file mode 100644 index 0000000000000..295f58f89125a --- /dev/null +++ b/packages/client-runtime/src/relay/dpopProof.ts @@ -0,0 +1,111 @@ +// RFC 9449 DPoP proofs for relay requests. Platforms supply the key: web keeps a +// non-extractable WebCrypto key, mobile signs with the platform's P-256 through a native module. +import { normalizeDpopHtu, type DpopPublicJwk } from "@t3tools/shared/dpopCommon"; +import * as Cache from "effect/Cache"; +import * as Clock from "effect/Clock"; +import * as Digest from "effect/crypto/Digest"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Schema from "effect/Schema"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Base64Url from "effect/encoding/Base64Url"; +import * as Exit from "effect/Exit"; +import * as Layer from "effect/Layer"; + +import { + ManagedRelayDpopKeyLoadError, + ManagedRelayDpopProofCreationError, + ManagedRelayDpopSigner, +} from "./managedRelay.ts"; + +export class DpopProofError extends Schema.TaggedError()("DpopProofError", { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), +}) {} + +/** A P-256 proof key. `sign` returns the raw `r‖s` ES256 signature over the JWS signing input. */ +export interface DpopProofKey { + readonly publicJwk: DpopPublicJwk; + readonly sign: (signingInput: Uint8Array) => Effect.Effect; +} + +const utf8 = (value: string) => new TextEncoder().encode(value); +const encodeSegment = (value: unknown) => Base64Url.encode(utf8(JSON.stringify(value))); + +const sha256Base64Url = (data: Uint8Array) => + Effect.flatMap(Digest.Digest, (digest) => digest.digest(Digest.sha256, data)).pipe( + Effect.map(Base64Url.encode), + ); + +/** RFC 7638 thumbprint: SHA-256 over the required members in lexicographic order. */ +export const thumbprint = (jwk: DpopPublicJwk) => + sha256Base64Url(utf8(JSON.stringify({ crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y }))); + +export const createProof = Effect.fn("DpopProof.createProof")(function* (input: { + readonly method: string; + readonly url: string; + readonly accessToken?: string | undefined; + readonly key: DpopProofKey; +}) { + const htu = normalizeDpopHtu(input.url); + if (htu === null) return yield* new DpopProofError({ message: "DPoP URL is invalid." }); + const random = yield* SecureRandom.SecureRandom; + const header = encodeSegment({ typ: "dpop+jwt", alg: "ES256", jwk: input.key.publicJwk }); + const payload = encodeSegment({ + htm: input.method.toUpperCase(), + htu, + jti: yield* random.uuidV4(), + iat: Math.floor((yield* Clock.currentTimeMillis) / 1_000), + ...(input.accessToken ? { ath: yield* sha256Base64Url(utf8(input.accessToken)) } : {}), + }); + const signature = yield* input.key.sign(utf8(`${header}.${payload}`)); + return `${header}.${payload}.${Base64Url.encode(signature)}`; +}); + +/** A relay DPoP signer that loads its key once and keeps it; a failed load is retried. */ +export const layerSigner = (options: { + readonly keyStore: ManagedRelayDpopKeyLoadError["keyStore"]; + readonly loadOrCreateKey: Effect.Effect; +}) => + Layer.effect( + ManagedRelayDpopSigner, + Effect.gen(function* () { + const random = yield* SecureRandom.SecureRandom; + const digest = yield* Digest.Digest; + const context = yield* Effect.context(); + const keyCache = yield* Cache.makeWith( + () => + options.loadOrCreateKey.pipe( + Effect.flatMap((key) => + thumbprint(key.publicJwk).pipe(Effect.map((value) => ({ key, thumbprint: value }))), + ), + Effect.provideService(Digest.Digest, digest), + Effect.provideContext(context), + ), + { + capacity: 1, + timeToLive: (exit) => (Exit.isSuccess(exit) ? Duration.infinity : Duration.zero), + }, + ); + const loadKey = Cache.get(keyCache, undefined); + return ManagedRelayDpopSigner.of({ + thumbprint: loadKey.pipe( + Effect.map((loaded) => loaded.thumbprint), + Effect.mapError( + (cause) => new ManagedRelayDpopKeyLoadError({ keyStore: options.keyStore, cause }), + ), + Effect.withSpan("managedRelayDpopSigner.loadThumbprint"), + ), + createProof: Effect.fn("managedRelayDpopSigner.createProof")(function* (input) { + const creationError = (cause: unknown) => + new ManagedRelayDpopProofCreationError({ method: input.method, url: input.url, cause }); + const loaded = yield* loadKey.pipe(Effect.mapError(creationError)); + return yield* createProof({ ...input, key: loaded.key }).pipe( + Effect.provideService(SecureRandom.SecureRandom, random), + Effect.provideService(Digest.Digest, digest), + Effect.mapError(creationError), + ); + }), + }); + }), + ); diff --git a/packages/client-runtime/src/relay/errorPresentation.ts b/packages/client-runtime/src/relay/errorPresentation.ts index ddf01e1e7ec20..a446cb2489361 100644 --- a/packages/client-runtime/src/relay/errorPresentation.ts +++ b/packages/client-runtime/src/relay/errorPresentation.ts @@ -1,5 +1,9 @@ import type { DpopFailureReason } from "@t3tools/contracts"; -import type { RelayEnvironmentStatusResponse, RelayProtectedError } from "@t3tools/contracts/relay"; +import { + T3CHAT_PLAN_TUNNEL_LIMITS, + type RelayEnvironmentStatusResponse, + type RelayProtectedError, +} from "@t3tools/contracts/relay"; export const DPOP_CLOCK_HINT = "Hint: Check that automatic date and time is enabled on both devices, then try again."; @@ -47,7 +51,7 @@ export function relayProtectedErrorMessage(error: RelayProtectedError): string { return "The environment's T3 Connect tunnel is still being set up."; } if (error.reason === "endpoint_provider_not_managed") { - return "This environment is linked only to publish agent activity, so it cannot accept connections. On that computer, open Settings > Connections and turn T3 Connect on."; + return "This environment is linked only to publish agent activity, so it cannot accept connections. On that computer, open Settings > Sharing & access and turn T3 Connect on."; } return error.reason ? `Relay rejected the environment connection request (${error.reason}).` @@ -63,7 +67,9 @@ export function relayProtectedErrorMessage(error: RelayProtectedError): string { error.provisioningStage ? ` Failed stage: ${error.provisioningStage}.` : "" }`; case "RelayEnvironmentLinkLimitExceededError": - return `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`; + return error.maxTunnels < T3CHAT_PLAN_TUNNEL_LIMITS.premier + ? `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment, or link a paid T3 Chat account in your T3 Connect account settings on web or desktop. Pro raises the default limit to ${T3CHAT_PLAN_TUNNEL_LIMITS.pro} and Premier to ${T3CHAT_PLAN_TUNNEL_LIMITS.premier}.` + : `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`; case "RelayAgentActivityPublishProofExpiredError": return "Relay rejected an expired agent activity publish proof."; case "RelayAgentActivityPublishProofInvalidError": diff --git a/packages/client-runtime/src/relay/index.ts b/packages/client-runtime/src/relay/index.ts index 4c8104eb44bc2..9a6635a5f9b95 100644 --- a/packages/client-runtime/src/relay/index.ts +++ b/packages/client-runtime/src/relay/index.ts @@ -1,4 +1,6 @@ export * as Discovery from "./discovery.ts"; +export * as DpopProof from "./dpopProof.ts"; +export * from "./cloudAccountService.ts"; export * from "./errorPresentation.ts"; export * as ManagedRelay from "./managedRelay.ts"; export * from "./managedRelayState.ts"; diff --git a/packages/client-runtime/src/relay/managedRelay.test.ts b/packages/client-runtime/src/relay/managedRelay.test.ts index 0506609229aab..76c6cb905a7a9 100644 --- a/packages/client-runtime/src/relay/managedRelay.test.ts +++ b/packages/client-runtime/src/relay/managedRelay.test.ts @@ -36,7 +36,7 @@ function layerManagedRelayTest( function clerkToken(subject: string, nonce: string): string { const encode = (value: unknown) => btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", ""); - return `${encode({ alg: "none" })}.${encode({ sub: subject, nonce })}.signature`; + return `${encode({ alg: "RS256" })}.${encode({ sub: subject, nonce })}.c2lnbmF0dXJl`; } describe("ManagedRelayClient", () => { diff --git a/packages/client-runtime/src/relay/managedRelay.ts b/packages/client-runtime/src/relay/managedRelay.ts index b6e37fd7afa8c..c10e2d5a5eca5 100644 --- a/packages/client-runtime/src/relay/managedRelay.ts +++ b/packages/client-runtime/src/relay/managedRelay.ts @@ -22,6 +22,8 @@ import { RelayMobileRegistrationScope, type RelayOkResponse, type RelayPublicClientId, + type RelayT3ChatLinkRequestResponse, + type RelayT3ChatLinkResponse, RelayRegisterDeviceEndpoint, RelayAgentActivitySnapshotEndpoint, RelayRegisterLiveActivityEndpoint, @@ -45,6 +47,7 @@ import * as HttpClientError from "effect/http/HttpClientError"; import type * as HttpMethod from "effect/http/HttpMethod"; import * as HttpApiClient from "effect/http-api/HttpApiClient"; import { NETWORK_BLOCKING_HINT } from "../errors/network.ts"; +import { relayRequestFailureDetail } from "./errorPresentation.ts"; export interface ManagedRelayDpopProofInput { readonly method: HttpMethod.HttpMethod; @@ -96,6 +99,9 @@ export const ManagedRelayRequestAction = Schema.Literals([ "unregister relay mobile device", "register relay live activity", "read relay agent activity snapshot", + "read linked T3 Chat account", + "start T3 Chat linking", + "unlink T3 Chat account", ]); export type ManagedRelayRequestAction = typeof ManagedRelayRequestAction.Type; @@ -112,6 +118,9 @@ export const ManagedRelayRequestActivity = Schema.Literals([ "Relay mobile device unregistration", "Relay Live Activity registration", "Relay agent activity snapshot", + "Relay T3 Chat link lookup", + "Relay T3 Chat link request", + "Relay T3 Chat unlinking", ]); export type ManagedRelayRequestActivity = typeof ManagedRelayRequestActivity.Type; @@ -151,8 +160,9 @@ export class ManagedRelayRequestFailedError extends Schema.TaggedError Effect.Effect; + readonly getT3ChatLink: (input: { + readonly clerkToken: string; + }) => Effect.Effect; + readonly createT3ChatLinkRequest: (input: { + readonly clerkToken: string; + }) => Effect.Effect; + readonly unlinkT3Chat: (input: { + readonly clerkToken: string; + }) => Effect.Effect; readonly getEnvironmentStatus: (input: { readonly clerkToken: string; readonly scopes: ReadonlyArray; @@ -391,15 +410,13 @@ function tokenMatches( ); } -function relayAccountId(clerkToken: string): Option.Option { - try { - return Option.fromNullishOr(decodeRelayJwt(clerkToken).sub).pipe( - Option.filter((subject) => subject.length > 0), - ); - } catch { - return Option.none(); - } -} +const relayAccountId = Effect.fn("clientRuntime.managedRelay.relayAccountId")(function* ( + clerkToken: string, +) { + const claims = yield* decodeRelayJwt(clerkToken).pipe(Effect.option); + const sub = Option.isSome(claims) ? claims.value.sub : undefined; + return typeof sub === "string" && sub.length > 0 ? Option.some(sub) : Option.none(); +}); function bearerHeaders(clerkToken: string) { return { authorization: `Bearer ${clerkToken}` }; @@ -426,6 +443,9 @@ function disabledManagedRelayClient(relayUrl: string): ManagedRelayClient["Servi ), linkEnvironment: unavailable("clientRuntime.managedRelay.linkEnvironment"), unlinkEnvironment: unavailable("clientRuntime.managedRelay.unlinkEnvironment"), + getT3ChatLink: unavailable("clientRuntime.managedRelay.getT3ChatLink"), + createT3ChatLinkRequest: unavailable("clientRuntime.managedRelay.createT3ChatLinkRequest"), + unlinkT3Chat: unavailable("clientRuntime.managedRelay.unlinkT3Chat"), getEnvironmentStatus: unavailable("clientRuntime.managedRelay.getEnvironmentStatus"), connectEnvironment: unavailable("clientRuntime.managedRelay.connectEnvironment"), registerDevice: unavailable("clientRuntime.managedRelay.registerDevice"), @@ -438,7 +458,7 @@ function disabledManagedRelayClient(relayUrl: string): ManagedRelayClient["Servi }); } -/** @public Service construction is part of the canonical Effect module API. */ +/** @public */ export const make = Effect.fn("ManagedRelayClient.make")(function* ( options: ManagedRelayClientLayerOptions, ) { @@ -544,7 +564,7 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* ( "relay.scopes": input.scopes.join(" "), }); const nowMillis = yield* Clock.currentTimeMillis; - const accountId = relayAccountId(input.clerkToken); + const accountId = yield* relayAccountId(input.clerkToken); if (Option.isNone(accountId)) { yield* Effect.annotateCurrentSpan({ "relay.token_cache.result": "bypass", @@ -791,6 +811,42 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* ( Effect.withSpan("clientRuntime.managedRelay.unlinkEnvironment"), withRelayClientTracing, ), + getT3ChatLink: Effect.fnUntraced( + function* (input) { + return yield* client.client + .getT3ChatLink({ headers: bearerHeaders(input.clerkToken) }) + .pipe( + Effect.mapError(relayRequestError("read linked T3 Chat account")), + timeoutRelayRequest("Relay T3 Chat link lookup"), + ); + }, + Effect.withSpan("clientRuntime.managedRelay.getT3ChatLink"), + withRelayClientTracing, + ), + createT3ChatLinkRequest: Effect.fnUntraced( + function* (input) { + return yield* client.client + .createT3ChatLinkRequest({ headers: bearerHeaders(input.clerkToken) }) + .pipe( + Effect.mapError(relayRequestError("start T3 Chat linking")), + timeoutRelayRequest("Relay T3 Chat link request"), + ); + }, + Effect.withSpan("clientRuntime.managedRelay.createT3ChatLinkRequest"), + withRelayClientTracing, + ), + unlinkT3Chat: Effect.fnUntraced( + function* (input) { + return yield* client.client + .unlinkT3Chat({ headers: bearerHeaders(input.clerkToken) }) + .pipe( + Effect.mapError(relayRequestError("unlink T3 Chat account")), + timeoutRelayRequest("Relay T3 Chat unlinking"), + ); + }, + Effect.withSpan("clientRuntime.managedRelay.unlinkT3Chat"), + withRelayClientTracing, + ), getEnvironmentStatus: Effect.fnUntraced( function* (input) { yield* Effect.annotateCurrentSpan({ diff --git a/packages/client-runtime/src/relay/managedRelayState.test.ts b/packages/client-runtime/src/relay/managedRelayState.test.ts index 3b2410f179ae9..41d7327ac14e4 100644 --- a/packages/client-runtime/src/relay/managedRelayState.test.ts +++ b/packages/client-runtime/src/relay/managedRelayState.test.ts @@ -6,11 +6,15 @@ import { import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; -import { AtomRegistry } from "effect/reactivity"; +import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; +import * as TestClock from "effect/testing/TestClock"; +import { Atom, AtomRegistry } from "effect/reactivity"; import { afterEach, vi } from "vite-plus/test"; import * as ManagedRelay from "./managedRelay.ts"; import { + createManagedRelayQueryManager, createManagedRelaySession, deregisterManagedRelayEnvironment, ManagedRelaySessionError, @@ -63,6 +67,9 @@ function createClient(overrides?: Partial Effect.die("unused"), linkEnvironment: () => Effect.die("unused"), unlinkEnvironment: () => Effect.die("unused"), + getT3ChatLink: () => Effect.die("unused"), + createT3ChatLinkRequest: () => Effect.die("unused"), + unlinkT3Chat: () => Effect.die("unused"), getEnvironmentStatus: () => Effect.succeed({ environmentId: environment.environmentId, @@ -90,12 +97,55 @@ function setSession() { function clerkToken(expiresAtSeconds: number): string { const encode = (value: unknown) => btoa(JSON.stringify(value)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, ""); - return `${encode({ alg: "none" })}.${encode({ exp: expiresAtSeconds })}.signature`; + return `${encode({ alg: "RS256" })}.${encode({ exp: expiresAtSeconds })}.c2lnbmF0dXJl`; } describe("createManagedRelayQueryManager", () => { afterEach(resetRegistry); + it.effect("logs a failed device listing once however many readers mount it", () => + Effect.gen(function* () { + const logs: Array = []; + const runtime = Atom.runtime( + Layer.mergeAll( + Layer.succeed( + ManagedRelay.ManagedRelayClient, + createClient({ + listDevices: () => + Effect.fail( + new ManagedRelay.ManagedRelayRequestFailedError({ + action: "list relay client devices", + cause: new Error("relay down"), + }), + ), + }), + ), + Logger.layer([Logger.make(({ message }) => logs.push(message))], { + mergeWithExisting: false, + }), + ), + ); + const manager = createManagedRelayQueryManager(runtime); + setSession(); + const atom = manager.devicesAtom("account-1"); + + const failed = Promise.withResolvers(); + const readers = [0, 1].map(() => + registry.subscribe( + atom, + (result) => { + if (result._tag === "Failure") failed.resolve(); + }, + { immediate: true }, + ), + ); + yield* Effect.promise(() => failed.promise); + for (const unsubscribe of readers) unsubscribe(); + + expect(logs).toEqual([["[t3-cloud] Relay device listing failed"]]); + }), + ); + it.effect("rejects deregistration after the account changes", () => Effect.gen(function* () { const unlinkEnvironment = vi.fn(() => Effect.succeed({ ok: true })); @@ -142,6 +192,42 @@ describe("createManagedRelayQueryManager", () => { }), ); + it.effect("replaces a Clerk token read that has not answered after 4 seconds", () => + Effect.gen(function* () { + const token = clerkToken(4_102_444_800); + const readClerkToken = vi + .fn<() => Promise>() + .mockReturnValueOnce(new Promise(() => {})) + .mockResolvedValue(token); + const session = createManagedRelaySession({ accountId: "account-1", readClerkToken }); + + const readsFiber = yield* Effect.all([session.readClerkToken(), session.readClerkToken()], { + concurrency: "unbounded", + }).pipe(Effect.forkChild); + yield* TestClock.adjust("3999 millis"); + expect(readClerkToken).toHaveBeenCalledTimes(1); + + yield* TestClock.adjust("1 millis"); + expect(yield* Fiber.join(readsFiber)).toEqual([token, token]); + expect(readClerkToken).toHaveBeenCalledTimes(2); + }), + ); + + it.effect("fails a Clerk token read that never answers after three tries", () => + Effect.gen(function* () { + const readClerkToken = vi.fn(() => new Promise(() => {})); + const session = createManagedRelaySession({ accountId: "account-1", readClerkToken }); + + const readFiber = yield* session.readClerkToken().pipe(Effect.flip, Effect.forkChild); + yield* TestClock.adjust("12 seconds"); + + expect((yield* Fiber.join(readFiber)).message).toBe( + "Timed out obtaining the T3 Connect session token.", + ); + expect(readClerkToken).toHaveBeenCalledTimes(3); + }), + ); + it.effect("updates the token provider without replacing a same-account session", () => Effect.gen(function* () { const firstRead = vi.fn(() => Promise.resolve(null)); diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.ts index cfe99e8abceae..90e635f4e328a 100644 --- a/packages/client-runtime/src/relay/managedRelayState.ts +++ b/packages/client-runtime/src/relay/managedRelayState.ts @@ -1,16 +1,7 @@ -import type { - RelayClientEnvironmentRecord, - RelayEnvironmentStatusResponse, -} from "@t3tools/contracts/relay"; import type { EnvironmentId } from "@t3tools/contracts"; -import { - RelayEnvironmentConnectScope, - RelayEnvironmentStatusScope, -} from "@t3tools/contracts/relay"; import { decodeRelayJwt } from "@t3tools/shared/relayJwt"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; -import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -24,6 +15,11 @@ import { relayProtectedErrorMessage } from "./errorPresentation.ts"; const DEFAULT_STALE_TIME_MS = 15_000; const DEFAULT_IDLE_TTL_MS = 5 * 60_000; const CLERK_TOKEN_EXPIRY_SKEW_MS = 5_000; +// Clerk retries a failed token request itself, but waits 3 s before the first +// retry and longer before each next one. A fresh request usually answers at +// once, so a slow read is replaced instead of waited out. +const CLERK_TOKEN_READ_TIMEOUT_MS = 4_000; +const CLERK_TOKEN_READ_ATTEMPTS = 3; const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError); export interface ManagedRelaySession { @@ -50,8 +46,8 @@ export interface ManagedRelaySnapshotState { } export interface ManagedRelayQueryEvent { - readonly operation: "environments" | "devices" | "environment-status"; - readonly stage: "clerk-token" | "relay-request" | "validation"; + readonly operation: "environments" | "devices" | "t3chat-link"; + readonly stage: "clerk-token" | "relay-request"; readonly phase: "start" | "success" | "failure"; readonly accountId: string; readonly environmentId?: string; @@ -59,14 +55,13 @@ export interface ManagedRelayQueryEvent { readonly traceId?: string | null; } -export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{ - readonly message: string; - readonly cause?: unknown; -}> {} - -export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySnapshotError")<{ - readonly message: string; -}> {} +export class ManagedRelaySessionError extends Schema.TaggedError()( + "ManagedRelaySessionError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} export const managedRelaySessionAtom = Atom.make(null).pipe( Atom.keepAlive, @@ -77,7 +72,10 @@ const managedRelaySessionControls = new WeakMap | null = null; + let pendingToken: { + readonly operation: Promise; + readonly startedAtMillis: number; + } | null = null; let readClerkToken = input.readClerkToken; let tokenProviderGeneration = 0; @@ -85,8 +83,10 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Mana if (cachedToken && cachedToken.expiresAtMillis > nowMillis + CLERK_TOKEN_EXPIRY_SKEW_MS) { return cachedToken.token; } - if (pendingToken) { - return await pendingToken; + // A read that outlived its timeout is left running, since it still fills + // the cache, but later readers start a fresh one instead of joining it. + if (pendingToken && nowMillis - pendingToken.startedAtMillis < CLERK_TOKEN_READ_TIMEOUT_MS) { + return await pendingToken.operation; } const operationGeneration = tokenProviderGeneration; @@ -98,22 +98,24 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Mana cachedToken = null; return null; } - try { - const expiresAtSeconds = decodeRelayJwt(token).exp; - cachedToken = - typeof expiresAtSeconds === "number" - ? { token, expiresAtMillis: expiresAtSeconds * 1_000 } - : null; - } catch { - cachedToken = null; - } + const expiresAtSeconds = Effect.runSync( + decodeRelayJwt(token).pipe( + Effect.map((claims) => claims.exp), + Effect.orElseSucceed(() => undefined), + ), + ); + cachedToken = + typeof expiresAtSeconds === "number" + ? { token, expiresAtMillis: expiresAtSeconds * 1_000 } + : null; return token; }); - pendingToken = operation; + const pending = { operation, startedAtMillis: nowMillis }; + pendingToken = pending; try { return await operation; } finally { - if (pendingToken === operation) { + if (pendingToken === pending) { pendingToken = null; } } @@ -122,14 +124,20 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Mana const session: ManagedRelaySession = { accountId: input.accountId, readClerkToken: Effect.fn("clientRuntime.managedRelaySession.readClerkToken")(function* () { - const nowMillis = yield* Clock.currentTimeMillis; - return yield* Effect.tryPromise({ - try: () => readCachedClerkToken(nowMillis), - catch: (cause) => - new ManagedRelaySessionError({ - message: "Could not obtain the T3 Connect session token.", - cause, - }), + for (let attempt = 0; attempt < CLERK_TOKEN_READ_ATTEMPTS; attempt += 1) { + const nowMillis = yield* Clock.currentTimeMillis; + const token = yield* Effect.tryPromise({ + try: () => readCachedClerkToken(nowMillis), + catch: (cause) => + new ManagedRelaySessionError({ + message: "Could not obtain the T3 Connect session token.", + cause, + }), + }).pipe(Effect.timeoutOption(CLERK_TOKEN_READ_TIMEOUT_MS)); + if (Option.isSome(token)) return token.value; + } + return yield* new ManagedRelaySessionError({ + message: "Timed out obtaining the T3 Connect session token.", }); }), }; @@ -190,23 +198,56 @@ function readSessionClerkToken( ); } +function requireSessionClerkToken( + registry: AtomRegistry.AtomRegistry, + accountId: string, + action: string, +): Effect.Effect { + const session = registry.get(managedRelaySessionAtom); + if (!session || session.accountId !== accountId) { + return Effect.fail( + new ManagedRelaySessionError({ message: `Sign in to T3 Connect before ${action}.` }), + ); + } + return readSessionClerkToken(session); +} + export const deregisterManagedRelayEnvironment = Effect.fn( "clientRuntime.managedRelaySession.deregisterEnvironment", )(function* ( registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string; readonly environmentId: EnvironmentId }, ) { - const session = registry.get(managedRelaySessionAtom); - if (!session || session.accountId !== input.accountId) { - return yield* new ManagedRelaySessionError({ - message: "Sign in to T3 Connect before deregistering an environment.", - }); - } - const clerkToken = yield* readSessionClerkToken(session); + const clerkToken = yield* requireSessionClerkToken( + registry, + input.accountId, + "deregistering an environment", + ); const relay = yield* ManagedRelay.ManagedRelayClient; yield* relay.unlinkEnvironment({ clerkToken, environmentId: input.environmentId }); }); +/** Returns the T3 Chat page URL where the signed-in user confirms the link. */ +export const createManagedRelayT3ChatLinkRequest = Effect.fn( + "clientRuntime.managedRelaySession.createT3ChatLinkRequest", +)(function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) { + const clerkToken = yield* requireSessionClerkToken(registry, input.accountId, "linking T3 Chat"); + const relay = yield* ManagedRelay.ManagedRelayClient; + return (yield* relay.createT3ChatLinkRequest({ clerkToken })).url; +}); + +export const unlinkManagedRelayT3Chat = Effect.fn("clientRuntime.managedRelaySession.unlinkT3Chat")( + function* (registry: AtomRegistry.AtomRegistry, input: { readonly accountId: string }) { + const clerkToken = yield* requireSessionClerkToken( + registry, + input.accountId, + "unlinking T3 Chat", + ); + const relay = yield* ManagedRelay.ManagedRelayClient; + yield* relay.unlinkT3Chat({ clerkToken }); + }, +); + function requireClerkToken( get: Atom.AtomContext, accountId: string, @@ -222,85 +263,49 @@ function requireClerkToken( return readSessionClerkToken(session); } -function statusKey(input: { - readonly accountId: string; - readonly environment: RelayClientEnvironmentRecord; -}): string { - return JSON.stringify(input); -} - -function parseStatusKey(key: string): { - readonly accountId: string; - readonly environment: RelayClientEnvironmentRecord; +function describeManagedRelayFailure(cause: Cause.Cause): { + readonly message: string; + readonly traceId: string | null; } { - return JSON.parse(key) as { - readonly accountId: string; - readonly environment: RelayClientEnvironmentRecord; + const error = Cause.squash(cause); + return { + message: + isManagedRelayRequestFailedError(error) && error.relayError + ? relayProtectedErrorMessage(error.relayError) + : error instanceof Error + ? error.message + : "Could not load T3 Connect data.", + traceId: findErrorTraceId(error), }; } -function endpointMatches( - left: RelayClientEnvironmentRecord["endpoint"], - right: RelayClientEnvironmentRecord["endpoint"], -): boolean { - return ( - left.httpBaseUrl === right.httpBaseUrl && - left.wsBaseUrl === right.wsBaseUrl && - left.providerKind === right.providerKind - ); -} - -function validateEnvironmentStatus( - environment: RelayClientEnvironmentRecord, - status: RelayEnvironmentStatusResponse, -): Effect.Effect { - if (status.environmentId !== environment.environmentId) { - return Effect.fail( - new ManagedRelaySnapshotError({ - message: "Relay returned status for a different environment.", - }), - ); - } - if (!endpointMatches(status.endpoint, environment.endpoint)) { - return Effect.fail( - new ManagedRelaySnapshotError({ - message: "Relay returned status for a different endpoint.", - }), - ); - } - if (status.descriptor && status.descriptor.environmentId !== environment.environmentId) { - return Effect.fail( - new ManagedRelaySnapshotError({ - message: "Relay returned status descriptor for a different environment.", - }), - ); - } - return Effect.succeed(status); -} - export function readManagedRelaySnapshotState( result: AsyncResult.AsyncResult, ): ManagedRelaySnapshotState { - let error: string | null = null; - let errorTraceId: string | null = null; - if (result._tag === "Failure") { - const cause = Cause.squash(result.cause); - error = - isManagedRelayRequestFailedError(cause) && cause.relayError - ? relayProtectedErrorMessage(cause.relayError) - : cause instanceof Error - ? cause.message - : "Could not load T3 Connect data."; - errorTraceId = findErrorTraceId(cause); - } + const failure = result._tag === "Failure" ? describeManagedRelayFailure(result.cause) : null; return { - data: Option.getOrNull(AsyncResult.value(result)), - error, - errorTraceId, + data: AsyncResult.getOrElse(result, () => null), + error: failure?.message ?? null, + errorTraceId: failure?.traceId ?? null, isPending: result.waiting, }; } +// Logged where the listing runs so each failed fetch reports once, however many +// components read the atom. +const logListingFailure = + (label: string) => + (self: Effect.Effect): Effect.Effect => + self.pipe( + Effect.tapCause((cause) => { + if (Cause.hasInterruptsOnly(cause)) return Effect.void; + const { message, traceId } = describeManagedRelayFailure(cause); + return Effect.logError(`[t3-cloud] Relay ${label} listing failed`).pipe( + Effect.annotateLogs({ message, traceId }), + ); + }), + ); + export function createManagedRelayQueryManager( runtime: Atom.AtomRuntime, options?: { @@ -349,7 +354,7 @@ export function createManagedRelayQueryManager( { ...base, stage: "relay-request" }, relay.listEnvironments({ clerkToken }), ); - }), + }).pipe(logListingFailure("environment")), ) .pipe( Atom.swr({ staleTime, revalidateOnMount: true }), @@ -372,7 +377,7 @@ export function createManagedRelayQueryManager( { ...base, stage: "relay-request" }, relay.listDevices({ clerkToken }), ); - }), + }).pipe(logListingFailure("device")), ) .pipe( Atom.swr({ staleTime, revalidateOnMount: true }), @@ -381,63 +386,41 @@ export function createManagedRelayQueryManager( ), ); - const environmentStatusAtom = Atom.family((key: string) => { - const { accountId, environment } = parseStatusKey(key); - return runtime + const t3ChatLinkAtom = Atom.family((accountId: string) => + runtime .atom((get) => Effect.gen(function* () { - const base = { - operation: "environment-status" as const, - accountId, - environmentId: environment.environmentId, - }; + const base = { operation: "t3chat-link" as const, accountId }; const clerkToken = yield* observe( { ...base, stage: "clerk-token" }, requireClerkToken(get, accountId), ); const relay = yield* ManagedRelay.ManagedRelayClient; - const status = yield* observe( - { ...base, stage: "relay-request" }, - relay.getEnvironmentStatus({ - clerkToken, - scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope], - environmentId: environment.environmentId, - }), - ); return yield* observe( - { ...base, stage: "validation" }, - validateEnvironmentStatus(environment, status), + { ...base, stage: "relay-request" }, + relay.getT3ChatLink({ clerkToken }), ); }), ) .pipe( Atom.swr({ staleTime, revalidateOnMount: true }), Atom.setIdleTTL(idleTtl), - Atom.withLabel(`managed-relay:environment-status:${key}`), - ); - }); + Atom.withLabel(`managed-relay:t3chat-link:${accountId}`), + ), + ); return { environmentsAtom, devicesAtom, - environmentStatusAtom: (input: { - readonly accountId: string; - readonly environment: RelayClientEnvironmentRecord; - }) => environmentStatusAtom(statusKey(input)), + t3ChatLinkAtom, refreshEnvironments(registry: AtomRegistry.AtomRegistry, accountId: string): void { registry.refresh(environmentsAtom(accountId)); }, refreshDevices(registry: AtomRegistry.AtomRegistry, accountId: string): void { registry.refresh(devicesAtom(accountId)); }, - refreshEnvironmentStatus( - registry: AtomRegistry.AtomRegistry, - input: { - readonly accountId: string; - readonly environment: RelayClientEnvironmentRecord; - }, - ): void { - registry.refresh(environmentStatusAtom(statusKey(input))); + refreshT3ChatLink(registry: AtomRegistry.AtomRegistry, accountId: string): void { + registry.refresh(t3ChatLinkAtom(accountId)); }, }; }