From 4453bd0fd930bac0bfc6b972774a5afe420761c1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 1 Jun 2026 17:40:46 -0700 Subject: [PATCH] refactor(cloud): retain relay queries with atoms Co-authored-by: codex --- apps/mobile/src/app/settings/environments.tsx | 111 +- apps/mobile/src/app/settings/index.tsx | 3 + .../src/features/cloud/CloudAuthProvider.tsx | 12 + .../features/cloud/linkEnvironment.test.ts | 1 + .../src/features/cloud/linkEnvironment.ts | 1 + .../src/features/cloud/managedRelayState.ts | 88 ++ .../connection/ConnectionEnvironmentRow.tsx | 102 +- apps/mobile/src/lib/connection.test.ts | 15 +- apps/mobile/src/lib/connection.ts | 7 + apps/mobile/src/state/remote-runtime-types.ts | 1 + .../state/use-remote-environment-registry.ts | 9 +- apps/server/src/http.ts | 18 +- apps/server/src/server.test.ts | 40 +- apps/web/src/cloud/linkEnvironment.ts | 16 +- apps/web/src/cloud/managedAuth.tsx | 17 +- apps/web/src/cloud/managedRelayState.ts | 83 ++ apps/web/src/cloud/primaryCloudLinkState.ts | 67 + .../src/components/settings/CloudSettings.tsx | 185 +-- .../settings/ConnectionsSettings.tsx | 243 ++-- .../settings/SettingsPanels.browser.tsx | 4 +- .../src/environments/primary/requestInit.ts | 7 + apps/web/src/lib/runtime.ts | 3 +- infra/relay/alchemy.run.ts | 2 - .../20260527044716_baseline/migration.sql | 3 +- .../20260527044716_baseline/snapshot.json | 13 - .../migration.sql | 1 + .../snapshot.json | 1280 +++++++++++++++++ infra/relay/src/db.ts | 2 +- packages/client-runtime/src/index.ts | 1 + .../src/managedRelayState.test.ts | 144 ++ .../client-runtime/src/managedRelayState.ts | 253 ++++ patches/alchemy@2.0.0-beta.49.patch | 356 +++++ pnpm-workspace.yaml | 1 + 33 files changed, 2734 insertions(+), 355 deletions(-) create mode 100644 apps/mobile/src/features/cloud/managedRelayState.ts create mode 100644 apps/web/src/cloud/managedRelayState.ts create mode 100644 apps/web/src/cloud/primaryCloudLinkState.ts create mode 100644 apps/web/src/environments/primary/requestInit.ts create mode 100644 infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/migration.sql create mode 100644 infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/snapshot.json create mode 100644 packages/client-runtime/src/managedRelayState.test.ts create mode 100644 packages/client-runtime/src/managedRelayState.ts create mode 100644 patches/alchemy@2.0.0-beta.49.patch diff --git a/apps/mobile/src/app/settings/environments.tsx b/apps/mobile/src/app/settings/environments.tsx index ba6ddeea98..d5a503bc62 100644 --- a/apps/mobile/src/app/settings/environments.tsx +++ b/apps/mobile/src/app/settings/environments.tsx @@ -2,20 +2,19 @@ import { useAuth } from "@clerk/expo"; import { Link, Stack } from "expo-router"; import { SymbolView } from "expo-symbols"; import type { EnvironmentId } from "@t3tools/contracts"; +import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay"; import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; import * as Effect from "effect/Effect"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useMemo, useState } from "react"; import { ActivityIndicator, Alert, Pressable, ScrollView, View } from "react-native"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { AppText as Text } from "../../components/AppText"; +import { connectCloudEnvironment } from "../../features/cloud/linkEnvironment"; import { - cloudEnvironmentsPendingStatus, - type CloudEnvironmentRecordWithStatus, - connectCloudEnvironment, - listCloudEnvironments, - loadCloudEnvironmentStatuses, -} from "../../features/cloud/linkEnvironment"; + useManagedRelayEnvironments, + useManagedRelayEnvironmentStatus, +} from "../../features/cloud/managedRelayState"; import { ConnectionEnvironmentRow } from "../../features/connection/ConnectionEnvironmentRow"; import { cn } from "../../lib/cn"; import { mobileRuntime } from "../../lib/runtime"; @@ -27,9 +26,7 @@ import { } from "../../state/use-remote-environment-registry"; export default function SettingsEnvironmentsRouteScreen() { - const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); - const getTokenRef = useRef(getToken); - getTokenRef.current = getToken; + const { getToken, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); const { connectedEnvironments, onReconnectEnvironment, @@ -40,11 +37,7 @@ export default function SettingsEnvironmentsRouteScreen() { const insets = useSafeAreaInsets(); const hasEnvironments = connectedEnvironments.length > 0; const [expandedId, setExpandedId] = useState(null); - const [cloudEnvironments, setCloudEnvironments] = useState< - ReadonlyArray - >([]); - const [cloudStatus, setCloudStatus] = useState<"idle" | "loading" | "error">("idle"); - const [cloudError, setCloudError] = useState(null); + const cloudEnvironmentsState = useManagedRelayEnvironments(); const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState( null, ); @@ -58,53 +51,15 @@ export default function SettingsEnvironmentsRouteScreen() { const availableCloudEnvironments = useMemo( () => - cloudEnvironments.filter( - (record) => savedConnectionsById[record.environment.environmentId] === undefined, + (cloudEnvironmentsState.data ?? []).filter( + (environment) => savedConnectionsById[environment.environmentId] === undefined, ), - [cloudEnvironments, savedConnectionsById], + [cloudEnvironmentsState.data, savedConnectionsById], ); - const refreshCloudEnvironments = useCallback(async () => { - if (!isLoaded || !isSignedIn) { - setCloudEnvironments([]); - setCloudStatus("idle"); - setCloudError(null); - return; - } - - setCloudStatus("loading"); - setCloudError(null); - try { - const token = await getTokenRef.current(RELAY_CLERK_TOKEN_OPTIONS); - if (!token) { - setCloudEnvironments([]); - setCloudStatus("idle"); - return; - } - const environments = await mobileRuntime.runPromise( - listCloudEnvironments({ clerkToken: token }), - ); - setCloudEnvironments(cloudEnvironmentsPendingStatus(environments)); - const records = await mobileRuntime.runPromise( - loadCloudEnvironmentStatuses({ clerkToken: token, environments }), - ); - setCloudEnvironments(records); - setCloudStatus("idle"); - } catch (error) { - setCloudStatus("error"); - setCloudError( - error instanceof Error ? error.message : "Could not load T3 Cloud environments.", - ); - } - }, [isLoaded, isSignedIn]); - - useEffect(() => { - void refreshCloudEnvironments(); - }, [refreshCloudEnvironments]); - const handleConnectCloudEnvironment = useCallback( - async (record: CloudEnvironmentRecordWithStatus) => { - setConnectingCloudEnvironmentId(record.environment.environmentId); + async (environment: RelayClientEnvironmentRecord) => { + setConnectingCloudEnvironmentId(environment.environmentId); try { const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS); if (!token) { @@ -113,14 +68,9 @@ export default function SettingsEnvironmentsRouteScreen() { await mobileRuntime.runPromise( connectCloudEnvironment({ clerkToken: token, - environment: record.environment, + environment, }).pipe(Effect.flatMap(connectSavedEnvironment)), ); - setCloudEnvironments((records) => - records.filter( - (candidate) => candidate.environment.environmentId !== record.environment.environmentId, - ), - ); } catch (error) { Alert.alert( "Connect failed", @@ -214,11 +164,11 @@ export default function SettingsEnvironmentsRouteScreen() { - {cloudStatus === "loading" ? ( + {cloudEnvironmentsState.isPending ? ( ) : ( 0 ? ( - {availableCloudEnvironments.map((record, index) => ( + {availableCloudEnvironments.map((environment, index) => ( handleConnectCloudEnvironment(record)} + isConnecting={connectingCloudEnvironmentId === environment.environmentId} + onConnect={() => handleConnectCloudEnvironment(environment)} /> ))} - ) : cloudStatus === "loading" ? ( + ) : cloudEnvironmentsState.data === null ? ( - ) : cloudStatus === "error" ? ( + ) : cloudEnvironmentsState.error ? ( Could not load T3 Cloud environments - {cloudError} + {cloudEnvironmentsState.error} ) : ( @@ -277,17 +227,18 @@ export default function SettingsEnvironmentsRouteScreen() { } function CloudEnvironmentRow(props: { - readonly record: CloudEnvironmentRecordWithStatus; + readonly environment: RelayClientEnvironmentRecord; readonly borderTop: boolean; readonly isConnecting: boolean; readonly onConnect: () => void; }) { const mutedColor = useThemeColor("--color-icon-muted"); - const { environment, status, statusError } = props.record; + const statusState = useManagedRelayEnvironmentStatus(props.environment); + const status = statusState.data; const disabled = props.isConnecting; const statusText = status === null - ? (statusError ?? "Status unavailable") + ? (statusState.error ?? (statusState.isPending ? "Checking status..." : "Status unavailable")) : status.status === "online" ? "Online" : (status.error ?? "Offline"); @@ -311,10 +262,10 @@ function CloudEnvironmentRow(props: { - {environment.label} + {props.environment.label} - {environment.endpoint.httpBaseUrl} + {props.environment.endpoint.httpBaseUrl} {statusText} diff --git a/apps/mobile/src/app/settings/index.tsx b/apps/mobile/src/app/settings/index.tsx index 917c8db8a2..85d09a1851 100644 --- a/apps/mobile/src/app/settings/index.tsx +++ b/apps/mobile/src/app/settings/index.tsx @@ -13,6 +13,7 @@ import { AppText as Text } from "../../components/AppText"; import { setLiveActivityUpdatesEnabled } from "../../features/agent-awareness/liveActivityPreferences"; import { requestAgentNotificationPermission } from "../../features/agent-awareness/notificationPermissions"; import { refreshAgentAwarenessRegistration } from "../../features/agent-awareness/remoteRegistration"; +import { refreshManagedRelayEnvironments } from "../../features/cloud/managedRelayState"; import { mobileRuntime } from "../../lib/runtime"; import { loadPreferences } from "../../lib/storage"; import { useThemeColor } from "../../lib/useThemeColor"; @@ -151,6 +152,7 @@ export default function SettingsRouteScreen() { connections, }), ); + refreshManagedRelayEnvironments(); setLiveActivityStatus("enabled"); Alert.alert( "Live Activities enabled", @@ -200,6 +202,7 @@ export default function SettingsRouteScreen() { connections, }), ); + refreshManagedRelayEnvironments(); } catch { // The switch is optimistic; a future refresh reconciles relay state. } diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx index 8748117a3a..aada03d5c9 100644 --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx @@ -1,10 +1,12 @@ import { ClerkProvider, useAuth } from "@clerk/expo"; import { tokenCache } from "@clerk/expo/token-cache"; +import { createManagedRelaySession, setManagedRelaySession } from "@t3tools/client-runtime"; import Constants from "expo-constants"; import { type ReactNode, useEffect, useRef } from "react"; import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; import { mobileRuntime } from "../../lib/runtime"; +import { appAtomRegistry } from "../../state/atom-registry"; import { setAgentAwarenessRelayTokenProvider, unregisterAgentAwarenessDeviceForCurrentUser, @@ -38,6 +40,7 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) { .catch(() => undefined); } setAgentAwarenessRelayTokenProvider(null); + setManagedRelaySession(appAtomRegistry, null); return; } @@ -50,6 +53,13 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) { const tokenProvider = () => getToken(RELAY_CLERK_TOKEN_OPTIONS); previousTokenProviderRef.current = { userId, provider: tokenProvider }; setAgentAwarenessRelayTokenProvider(tokenProvider, userId); + setManagedRelaySession( + appAtomRegistry, + createManagedRelaySession({ + accountId: userId, + readClerkToken: tokenProvider, + }), + ); if (!previous || previous.userId !== userId) { void mobileRuntime .runPromise(refreshActiveLiveActivityRemoteRegistration()) @@ -61,6 +71,7 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) { () => () => { previousTokenProviderRef.current = null; setAgentAwarenessRelayTokenProvider(null); + setManagedRelaySession(appAtomRegistry, null); }, [], ); @@ -74,6 +85,7 @@ export function CloudAuthProvider(props: { readonly children: ReactNode }) { useEffect(() => { if (!publishableKey) { setAgentAwarenessRelayTokenProvider(null); + setManagedRelaySession(appAtomRegistry, null); } }, [publishableKey]); diff --git a/apps/mobile/src/features/cloud/linkEnvironment.test.ts b/apps/mobile/src/features/cloud/linkEnvironment.test.ts index e2e3df4eb6..95a603a008 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.test.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.test.ts @@ -825,6 +825,7 @@ describe("mobile cloud link environment client", () => { expect(connection.bearerToken).toBeNull(); expect(connection.authenticationMethod).toBe("dpop"); expect(connection.dpopAccessToken).toBe("environment-dpop-token"); + expect(connection.relayManaged).toBe(true); // @effect-diagnostics-next-line preferSchemaOverJson:off expect(JSON.parse(connectRequestBody)).toMatchObject({ deviceId: "device-1", diff --git a/apps/mobile/src/features/cloud/linkEnvironment.ts b/apps/mobile/src/features/cloud/linkEnvironment.ts index e13e31bf19..e4d24b132d 100644 --- a/apps/mobile/src/features/cloud/linkEnvironment.ts +++ b/apps/mobile/src/features/cloud/linkEnvironment.ts @@ -547,6 +547,7 @@ export function connectCloudEnvironment(input: { bearerToken: null, authenticationMethod: "dpop", dpopAccessToken: bootstrap.access_token, + relayManaged: true, }; }); } diff --git a/apps/mobile/src/features/cloud/managedRelayState.ts b/apps/mobile/src/features/cloud/managedRelayState.ts new file mode 100644 index 0000000000..a1ecc8b4ea --- /dev/null +++ b/apps/mobile/src/features/cloud/managedRelayState.ts @@ -0,0 +1,88 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + createManagedRelayQueryManager, + ManagedRelayClient, + managedRelaySessionAtom, + readManagedRelaySnapshotState, +} from "@t3tools/client-runtime"; +import type { + RelayClientEnvironmentRecord, + RelayEnvironmentStatusResponse, +} from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { AsyncResult, Atom } from "effect/unstable/reactivity"; +import { useCallback } from "react"; + +import { mobileRuntime } from "../../lib/runtime"; +import { appAtomRegistry } from "../../state/atom-registry"; + +const managedRelayAtomRuntime = Atom.runtime( + Layer.effect( + ManagedRelayClient, + mobileRuntime.contextEffect.pipe( + Effect.map((context) => Context.get(context, ManagedRelayClient)), + ), + ), +); + +export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime); + +const EMPTY_ENVIRONMENTS_ATOM = Atom.make( + AsyncResult.success>([]), +).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environments:null")); + +const EMPTY_ENVIRONMENT_STATUS_ATOM = Atom.make( + AsyncResult.initial(false), +).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environment-status:null")); + +export function useManagedRelayEnvironments() { + const session = useAtomValue(managedRelaySessionAtom); + const accountId = session?.accountId ?? null; + const atom = accountId + ? managedRelayQueryManager.environmentsAtom(accountId) + : EMPTY_ENVIRONMENTS_ATOM; + const result = useAtomValue(atom); + const refresh = useCallback(() => { + if (accountId) { + managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId); + } + }, [accountId]); + + return { + ...readManagedRelaySnapshotState(result), + accountId, + refresh, + }; +} + +export function useManagedRelayEnvironmentStatus(environment: RelayClientEnvironmentRecord) { + const session = useAtomValue(managedRelaySessionAtom); + const accountId = session?.accountId ?? null; + const atom = accountId + ? managedRelayQueryManager.environmentStatusAtom({ accountId, environment }) + : EMPTY_ENVIRONMENT_STATUS_ATOM; + const result = useAtomValue(atom); + const refresh = useCallback(() => { + if (accountId) { + managedRelayQueryManager.refreshEnvironmentStatus(appAtomRegistry, { + accountId, + environment, + }); + } + }, [accountId, environment]); + + return { + ...readManagedRelaySnapshotState(result), + accountId, + refresh, + }; +} + +export function refreshManagedRelayEnvironments(): void { + const session = appAtomRegistry.get(managedRelaySessionAtom); + if (session) { + managedRelayQueryManager.refreshEnvironments(appAtomRegistry, session.accountId); + } +} diff --git a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx index 1dc6db74cc..dd26e2e6ff 100644 --- a/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx +++ b/apps/mobile/src/features/connection/ConnectionEnvironmentRow.tsx @@ -113,56 +113,66 @@ export function ConnectionEnvironmentRow(props: { exiting={FadeOut.duration(150)} className="gap-3 px-4 pb-4" > - - - Label + {props.environment.isRelayManaged ? ( + + Managed by T3 Cloud. Tunnel details update automatically. - - + ) : ( + <> + + + Label + + + - - - URL - - - + + + URL + + + + + )} - - - - + {props.environment.isRelayManaged ? null : ( + - Save - - + + + Save + + + )} ({ mobileRuntime: { @@ -39,4 +43,13 @@ describe("mobile remote connection records", () => { ), ).toBe("https://app.t3.codes/pair?host=https%3A%2F%2Fdesktop.example&label=Desktop"); }); + + it("recognizes explicitly managed relay connections", () => { + expect(isRelayManagedConnection({ relayManaged: true })).toBe(true); + }); + + it("keeps existing DPoP tunnel records read-only after upgrading", () => { + expect(isRelayManagedConnection({ authenticationMethod: "dpop" })).toBe(true); + expect(isRelayManagedConnection({ authenticationMethod: "bearer" })).toBe(false); + }); }); diff --git a/apps/mobile/src/lib/connection.ts b/apps/mobile/src/lib/connection.ts index 8500a80873..8bfd34a10e 100644 --- a/apps/mobile/src/lib/connection.ts +++ b/apps/mobile/src/lib/connection.ts @@ -24,6 +24,7 @@ export interface SavedRemoteConnection { readonly bearerToken: string | null; readonly authenticationMethod?: "bearer" | "dpop"; readonly dpopAccessToken?: string; + readonly relayManaged?: true; } export type RemoteClientConnectionState = @@ -42,6 +43,12 @@ export function redactPairingCredential(pairingUrl: string): string { } } +export function isRelayManagedConnection( + connection: Pick, +): boolean { + return connection.relayManaged === true || connection.authenticationMethod === "dpop"; +} + export async function bootstrapRemoteConnection( input: RemoteConnectionInput, ): Promise { diff --git a/apps/mobile/src/state/remote-runtime-types.ts b/apps/mobile/src/state/remote-runtime-types.ts index 74d2cc8d99..054203715b 100644 --- a/apps/mobile/src/state/remote-runtime-types.ts +++ b/apps/mobile/src/state/remote-runtime-types.ts @@ -11,6 +11,7 @@ export interface ConnectedEnvironmentSummary { readonly environmentId: EnvironmentId; readonly environmentLabel: string; readonly displayUrl: string; + readonly isRelayManaged: boolean; readonly connectionState: EnvironmentConnectionState; readonly connectionError: string | null; } diff --git a/apps/mobile/src/state/use-remote-environment-registry.ts b/apps/mobile/src/state/use-remote-environment-registry.ts index 97d95609a6..d0900c05fb 100644 --- a/apps/mobile/src/state/use-remote-environment-registry.ts +++ b/apps/mobile/src/state/use-remote-environment-registry.ts @@ -23,7 +23,11 @@ import * as Order from "effect/Order"; import * as Option from "effect/Option"; import { pipe } from "effect/Function"; import { Atom } from "effect/unstable/reactivity"; -import { type SavedRemoteConnection, bootstrapRemoteConnection } from "../lib/connection"; +import { + type SavedRemoteConnection, + bootstrapRemoteConnection, + isRelayManagedConnection, +} from "../lib/connection"; import { terminalDebugLog } from "../features/terminal/terminalDebugLog"; import { clearCachedShellSnapshot, @@ -444,6 +448,7 @@ function deriveConnectedEnvironments( environmentId: connection.environmentId, environmentLabel: connection.environmentLabel, displayUrl: connection.displayUrl, + isRelayManaged: isRelayManagedConnection(connection), connectionState: runtime?.connectionState ?? "idle", connectionError: runtime?.connectionError ?? null, }; @@ -612,7 +617,7 @@ export function useRemoteConnections() { updates: { readonly label: string; readonly displayUrl: string }, ) => { const connection = getSavedConnectionsById()[environmentId]; - if (!connection) { + if (!connection || isRelayManagedConnection(connection)) { return; } diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index 0e521ecca9..4e815aae8c 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -8,6 +8,7 @@ import { decodeOtlpTraceRecords } from "@t3tools/shared/observability"; import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import { cast } from "effect/Function"; @@ -47,11 +48,18 @@ const FALLBACK_PROJECT_FAVICON_SVG = ` const assertBrowserApiCorsResponseHeaders = ( headers: Readonly>, + options?: { + readonly origin?: string; + readonly credentials?: boolean; + }, ) => { - assert.equal(headers["access-control-allow-origin"], "*"); + assert.equal(headers["access-control-allow-origin"], options?.origin ?? "*"); + assert.equal( + headers["access-control-allow-credentials"], + options?.credentials ? "true" : undefined, + ); }; const assertBrowserApiCorsPreflightHeaders = ( headers: Readonly>, + options?: { + readonly origin?: string; + readonly credentials?: boolean; + }, ) => { - assertBrowserApiCorsResponseHeaders(headers); + assertBrowserApiCorsResponseHeaders(headers, options); assert.deepEqual(splitHeaderTokens(headers["access-control-allow-methods"] ?? null), [ "GET", "OPTIONS", @@ -3166,6 +3178,30 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + it.effect("allows credentialed cloud link proof preflights from the configured dev UI", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { devUrl: new URL(crossOriginClientOrigin) }, + }); + + const linkProofUrl = yield* getHttpServerUrl("/api/cloud/link-proof"); + const response = yield* fetchEffect(linkProofUrl, { + method: "OPTIONS", + headers: { + origin: crossOriginClientOrigin, + "access-control-request-method": "POST", + "access-control-request-headers": "content-type", + }, + }); + + assert.equal(response.status, 204); + assertBrowserApiCorsPreflightHeaders(response.headers, { + origin: crossOriginClientOrigin, + credentials: true, + }); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + it.effect("includes CORS headers on remote websocket-ticket auth failures", () => Effect.gen(function* () { yield* buildAppUnderTest(); diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts index 8888d40020..b6981e06f6 100644 --- a/apps/web/src/cloud/linkEnvironment.ts +++ b/apps/web/src/cloud/linkEnvironment.ts @@ -1,7 +1,7 @@ import * as Data from "effect/Data"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; -import { FetchHttpClient, HttpClient } from "effect/unstable/http"; +import { HttpClient } from "effect/unstable/http"; import { EnvironmentCloudEndpointUnavailableError, type EnvironmentCloudLinkStateResult, @@ -36,6 +36,7 @@ import { readPrimaryEnvironmentTarget, resolvePrimaryEnvironmentHttpUrl, } from "../environments/primary"; +import { withPrimaryEnvironmentRequestInit } from "../environments/primary/requestInit"; export function normalizeRelayBaseUrl(value: string | null | undefined): string | null { const trimmed = value?.trim(); @@ -142,9 +143,6 @@ const environmentApiError = (message: string) => (cause: unknown) => { }); }; -const withPrimaryEnvironmentCookies = (effect: Effect.Effect) => - effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, { credentials: "include" })); - function endpointOrigin(httpBaseUrl: string) { const url = new URL(httpBaseUrl); return { @@ -399,7 +397,7 @@ export function readPrimaryCloudLinkState(): Effect.Effect< return yield* client.cloud .linkState({ headers: {} }) .pipe( - withPrimaryEnvironmentCookies, + withPrimaryEnvironmentRequestInit, Effect.mapError(environmentApiError("Could not read environment cloud link state.")), ); }); @@ -416,7 +414,7 @@ export function updatePrimaryCloudPreferences(input: { payload: input, }) .pipe( - withPrimaryEnvironmentCookies, + withPrimaryEnvironmentRequestInit, Effect.mapError(environmentApiError("Could not update environment cloud preferences.")), ); }); @@ -453,7 +451,7 @@ export function unlinkPrimaryEnvironmentFromCloud(input: { yield* client.cloud .unlink({ headers: {} }) .pipe( - withPrimaryEnvironmentCookies, + withPrimaryEnvironmentRequestInit, Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")), ); }); @@ -605,7 +603,7 @@ export function linkPrimaryEnvironmentToCloud(input: { }, }) .pipe( - withPrimaryEnvironmentCookies, + withPrimaryEnvironmentRequestInit, Effect.mapError(environmentApiError("Could not obtain environment link proof.")), ); const link = yield* relayClient @@ -642,7 +640,7 @@ export function linkPrimaryEnvironmentToCloud(input: { }, }) .pipe( - withPrimaryEnvironmentCookies, + withPrimaryEnvironmentRequestInit, Effect.mapError(environmentApiError("Could not configure environment relay access.")), ); }); diff --git a/apps/web/src/cloud/managedAuth.tsx b/apps/web/src/cloud/managedAuth.tsx index 9bc3a69a3a..df4e06a97c 100644 --- a/apps/web/src/cloud/managedAuth.tsx +++ b/apps/web/src/cloud/managedAuth.tsx @@ -1,7 +1,10 @@ import { useAuth } from "@clerk/react"; +import { createManagedRelaySession, setManagedRelaySession } from "@t3tools/client-runtime"; import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; import { useEffect, type ReactNode } from "react"; +import { appAtomRegistry } from "../rpc/atomRegistry"; + let relayTokenProvider: (() => Promise) | null = null; export async function readManagedRelayClerkToken(): Promise { @@ -9,14 +12,24 @@ export async function readManagedRelayClerkToken(): Promise { } export function ManagedRelayAuthProvider({ children }: { readonly children: ReactNode }) { - const { getToken, isSignedIn } = useAuth(); + const { getToken, isSignedIn, userId } = useAuth(); useEffect(() => { relayTokenProvider = isSignedIn ? () => getToken(RELAY_CLERK_TOKEN_OPTIONS) : null; + setManagedRelaySession( + appAtomRegistry, + isSignedIn && userId + ? createManagedRelaySession({ + accountId: userId, + readClerkToken: () => getToken(RELAY_CLERK_TOKEN_OPTIONS), + }) + : null, + ); return () => { relayTokenProvider = null; + setManagedRelaySession(appAtomRegistry, null); }; - }, [getToken, isSignedIn]); + }, [getToken, isSignedIn, userId]); return children; } diff --git a/apps/web/src/cloud/managedRelayState.ts b/apps/web/src/cloud/managedRelayState.ts new file mode 100644 index 0000000000..a31ee9e16f --- /dev/null +++ b/apps/web/src/cloud/managedRelayState.ts @@ -0,0 +1,83 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + createManagedRelayQueryManager, + ManagedRelayClient, + managedRelaySessionAtom, + readManagedRelaySnapshotState, +} from "@t3tools/client-runtime"; +import type { + RelayClientDeviceRecord, + RelayClientEnvironmentRecord, +} from "@t3tools/contracts/relay"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { AsyncResult, Atom } from "effect/unstable/reactivity"; +import { useCallback } from "react"; + +import { webRuntime } from "../lib/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; + +const managedRelayAtomRuntime = Atom.runtime( + Layer.effect( + ManagedRelayClient, + webRuntime.contextEffect.pipe( + Effect.map((context) => Context.get(context, ManagedRelayClient)), + ), + ), +); + +export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime); + +const EMPTY_ENVIRONMENTS_ATOM = Atom.make( + AsyncResult.success>([]), +).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:environments:null")); + +const EMPTY_DEVICES_ATOM = Atom.make( + AsyncResult.success>([]), +).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:devices:null")); + +export function useManagedRelayEnvironments() { + const session = useAtomValue(managedRelaySessionAtom); + const accountId = session?.accountId ?? null; + const atom = accountId + ? managedRelayQueryManager.environmentsAtom(accountId) + : EMPTY_ENVIRONMENTS_ATOM; + const result = useAtomValue(atom); + const refresh = useCallback(() => { + if (accountId) { + managedRelayQueryManager.refreshEnvironments(appAtomRegistry, accountId); + } + }, [accountId]); + + return { + ...readManagedRelaySnapshotState(result), + accountId, + refresh, + }; +} + +export function useManagedRelayDevices() { + const session = useAtomValue(managedRelaySessionAtom); + const accountId = session?.accountId ?? null; + const atom = accountId ? managedRelayQueryManager.devicesAtom(accountId) : EMPTY_DEVICES_ATOM; + const result = useAtomValue(atom); + const refresh = useCallback(() => { + if (accountId) { + managedRelayQueryManager.refreshDevices(appAtomRegistry, accountId); + } + }, [accountId]); + + return { + ...readManagedRelaySnapshotState(result), + accountId, + refresh, + }; +} + +export function refreshManagedRelayEnvironments(): void { + const session = appAtomRegistry.get(managedRelaySessionAtom); + if (session) { + managedRelayQueryManager.refreshEnvironments(appAtomRegistry, session.accountId); + } +} diff --git a/apps/web/src/cloud/primaryCloudLinkState.ts b/apps/web/src/cloud/primaryCloudLinkState.ts new file mode 100644 index 0000000000..ecc2297595 --- /dev/null +++ b/apps/web/src/cloud/primaryCloudLinkState.ts @@ -0,0 +1,67 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentCloudLinkStateResult, EnvironmentId } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom } from "effect/unstable/reactivity"; +import { HttpClient } from "effect/unstable/http"; +import { useCallback } from "react"; + +import { usePrimaryEnvironmentId } from "../environments/primary"; +import { webRuntime } from "../lib/runtime"; +import { appAtomRegistry } from "../rpc/atomRegistry"; +import { readPrimaryCloudLinkState } from "./linkEnvironment"; + +const primaryCloudLinkAtomRuntime = Atom.runtime( + Layer.effect( + HttpClient.HttpClient, + webRuntime.contextEffect.pipe( + Effect.map((context) => Context.get(context, HttpClient.HttpClient)), + ), + ), +); + +const primaryCloudLinkStateAtom = Atom.family((environmentId: EnvironmentId) => + primaryCloudLinkAtomRuntime + .atom(readPrimaryCloudLinkState()) + .pipe( + Atom.swr({ staleTime: 5_000, revalidateOnMount: true }), + Atom.setIdleTTL(5 * 60_000), + Atom.withLabel(`primary-cloud-link:${environmentId}`), + ), +); + +const EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM = Atom.make( + AsyncResult.success(null), +).pipe(Atom.keepAlive, Atom.withLabel("primary-cloud-link:null")); + +export function refreshPrimaryCloudLinkState(environmentId: EnvironmentId | null): void { + if (environmentId) { + appAtomRegistry.refresh(primaryCloudLinkStateAtom(environmentId)); + } +} + +export function usePrimaryCloudLinkState() { + const environmentId = usePrimaryEnvironmentId(); + const atom = environmentId + ? primaryCloudLinkStateAtom(environmentId) + : EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM; + const result = useAtomValue(atom); + const refresh = useCallback(() => { + refreshPrimaryCloudLinkState(environmentId); + }, [environmentId]); + let error: string | null = null; + if (result._tag === "Failure") { + const cause = Cause.squash(result.cause); + error = cause instanceof Error ? cause.message : "Could not read T3 Cloud link state."; + } + + return { + data: Option.getOrNull(AsyncResult.value(result)), + error, + isPending: result.waiting, + refresh, + }; +} diff --git a/apps/web/src/components/settings/CloudSettings.tsx b/apps/web/src/components/settings/CloudSettings.tsx index 3683ff275f..d44032d1e2 100644 --- a/apps/web/src/components/settings/CloudSettings.tsx +++ b/apps/web/src/components/settings/CloudSettings.tsx @@ -1,29 +1,58 @@ import { UserButton, Waitlist, useAuth, useClerk } from "@clerk/react"; import { useSignIn, useSignUp } from "@clerk/react/legacy"; import { AuthRelayWriteScope } from "@t3tools/contracts"; -import { RELAY_CLERK_TOKEN_OPTIONS } from "@t3tools/shared/relayAuth"; -import type { RelayClientDeviceRecord } from "@t3tools/contracts/relay"; -import { CloudIcon } from "lucide-react"; +import { CloudIcon, RefreshCwIcon, SmartphoneIcon } from "lucide-react"; import { useCallback, useEffect, useRef, useState } from "react"; import { type DesktopCloudAuthOAuthStrategy, resolveDesktopCloudAuthOAuthOptions, } from "../../cloud/desktopAuth"; -import { - listCloudDevices, - readPrimaryCloudLinkState, - type CloudLinkState, - updatePrimaryCloudPreferences, -} from "../../cloud/linkEnvironment"; +import { updatePrimaryCloudPreferences } from "../../cloud/linkEnvironment"; +import { useManagedRelayDevices } from "../../cloud/managedRelayState"; +import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState"; import { isElectron } from "../../env"; -import { fetchSessionState, usePrimaryEnvironmentId } from "../../environments/primary"; +import { usePrimarySessionState } from "../../environments/primary"; import { webRuntime } from "../../lib/runtime"; +import { cn } from "../../lib/utils"; import { Button } from "../ui/button"; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; +import { Skeleton } from "../ui/skeleton"; import { Switch } from "../ui/switch"; import { toastManager } from "../ui/toast"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; +const NOTIFICATION_DEVICE_SKELETON_ROWS = ["primary", "secondary"] as const; + +function NotificationDevicesSkeleton() { + return NOTIFICATION_DEVICE_SKELETON_ROWS.map((row) => ( +
+
+ + + +
+
+ )); +} + +function EmptyNotificationDevices() { + return ( + + + + + + No notification devices + + Sign in on the mobile app to register a device for account-level notifications. + + + + ); +} + function hasClerkConfig(): boolean { return Boolean(import.meta.env.VITE_CLERK_PUBLISHABLE_KEY); } @@ -99,69 +128,30 @@ function CloudWaitlistPanel() { } function CloudSettingsPanelInner() { - const { getToken } = useAuth(); - const primaryEnvironmentId = usePrimaryEnvironmentId(); - const [primaryLinkState, setPrimaryLinkState] = useState(null); - const [devices, setDevices] = useState>([]); - const [isLoadingDevices, setIsLoadingDevices] = useState(false); + const primaryLinkState = usePrimaryCloudLinkState(); + const primarySessionState = usePrimarySessionState(); + const devicesState = useManagedRelayDevices(); const [isUpdatingPreference, setIsUpdatingPreference] = useState(false); - const [canManageRelay, setCanManageRelay] = useState(false); - - const refreshPrimaryLinkState = useCallback(() => { - if (!primaryEnvironmentId) { - setPrimaryLinkState(null); - return; - } - void webRuntime - .runPromise(readPrimaryCloudLinkState()) - .then(setPrimaryLinkState, () => setPrimaryLinkState(null)); - }, [primaryEnvironmentId]); + const devices = devicesState.data ?? []; + const canManageRelay = + primarySessionState.data?.authenticated === true && + Boolean(primarySessionState.data.scopes?.includes(AuthRelayWriteScope)); useEffect(() => { - refreshPrimaryLinkState(); - }, [refreshPrimaryLinkState]); - - useEffect(() => { - void fetchSessionState() - .then((session) => - setCanManageRelay( - session.authenticated && Boolean(session.scopes?.includes(AuthRelayWriteScope)), - ), - ) - .catch(() => setCanManageRelay(false)); - }, []); - - const refreshDevices = useCallback(async () => { - setIsLoadingDevices(true); - try { - const token = await getToken(RELAY_CLERK_TOKEN_OPTIONS); - if (!token) { - setDevices([]); - return; - } - setDevices(await webRuntime.runPromise(listCloudDevices({ clerkToken: token }))); - } catch (error) { + if (devicesState.error) { toastManager.add({ type: "error", title: "Cloud devices unavailable", - description: cloudErrorMessage(error, "Could not load notification devices."), + description: devicesState.error, }); - } finally { - setIsLoadingDevices(false); } - }, [getToken]); - - useEffect(() => { - void refreshDevices(); - }, [refreshDevices]); + }, [devicesState.error]); const updatePublishAgentActivity = async (enabled: boolean) => { setIsUpdatingPreference(true); try { - const state = await webRuntime.runPromise( - updatePrimaryCloudPreferences({ publishAgentActivity: enabled }), - ); - setPrimaryLinkState(state); + await webRuntime.runPromise(updatePrimaryCloudPreferences({ publishAgentActivity: enabled })); + primaryLinkState.refresh(); toastManager.add({ type: "success", title: enabled ? "Agent activity enabled" : "Agent activity disabled", @@ -194,13 +184,13 @@ function CloudSettingsPanelInner() { title="Publish agent activity" description="Allow this environment to send agent activity to your notification devices." status={ - !primaryLinkState?.linked ? "Link this environment from Connections first." : null + !primaryLinkState.data?.linked ? "Link this environment from Connections first." : null } control={ void updatePublishAgentActivity(enabled)} /> } @@ -209,36 +199,47 @@ function CloudSettingsPanelInner() { void refreshDevices()} - > - {isLoadingDevices ? "Refreshing..." : "Refresh"} - + + + + + } + /> + Refresh notification devices + } > - {devices.map((device) => ( - - ))} - {!isLoadingDevices && devices.length === 0 ? ( - - ) : null} + {devicesState.data === null ? ( + + ) : devices.length > 0 ? ( + devices.map((device) => ( + + )) + ) : ( + + )} ); diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx index 790aadbc97..07b170f173 100644 --- a/apps/web/src/components/settings/ConnectionsSettings.tsx +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -69,11 +69,13 @@ import { } from "../ui/alert-dialog"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { QRCodeSvg } from "../ui/qr-code"; +import { Skeleton } from "../ui/skeleton"; import { Spinner } from "../ui/spinner"; import { Switch } from "../ui/switch"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { Button } from "../ui/button"; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; import { Group, GroupSeparator } from "../ui/group"; import { AnimatedHeight } from "../AnimatedHeight"; import { @@ -94,6 +96,7 @@ import { revokeServerClientSession, revokeServerPairingLink, isLoopbackHostname, + usePrimaryEnvironmentId, usePrimarySessionState, type ServerClientSessionRecord, type ServerPairingLinkRecord, @@ -117,10 +120,13 @@ import { useServerConfig } from "~/rpc/serverState"; import { connectManagedCloudEnvironment, linkPrimaryEnvironmentToCloud, - listManagedCloudEnvironments, - readPrimaryCloudLinkState, unlinkPrimaryEnvironmentFromCloud, } from "~/cloud/linkEnvironment"; +import { + refreshManagedRelayEnvironments, + useManagedRelayEnvironments, +} from "~/cloud/managedRelayState"; +import { usePrimaryCloudLinkState } from "~/cloud/primaryCloudLinkState"; import { webRuntime } from "~/lib/runtime"; const DEFAULT_TAILSCALE_SERVE_PORT = 443; @@ -1598,34 +1604,44 @@ const DesktopSshHostRow = memo(function DesktopSshHostRow({ ); }); +function CloudLinkSwitch({ + checked, + disabled, + disabledReason, + onCheckedChange, +}: { + readonly checked: boolean; + readonly disabled: boolean; + readonly disabledReason: string | null; + readonly onCheckedChange?: (enabled: boolean) => void; +}) { + const control = ( + + ); + return disabledReason ? ( + + {control}} /> + {disabledReason} + + ) : ( + control + ); +} + function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) { const { getToken, isSignedIn } = useAuth(); - const [linked, setLinked] = useState(false); - const [isLoading, setIsLoading] = useState(true); - const [error, setError] = useState(null); - - const refresh = useCallback(() => { - setIsLoading(true); - void webRuntime.runPromise(readPrimaryCloudLinkState()).then( - (state) => { - setLinked(state?.linked ?? false); - setError(null); - setIsLoading(false); - }, - (cause: unknown) => { - setError(cause instanceof Error ? cause.message : "Could not read T3 Cloud link state."); - setIsLoading(false); - }, - ); - }, []); - - useEffect(() => { - refresh(); - }, [refresh]); + const primaryCloudLinkState = usePrimaryCloudLinkState(); + const [operationError, setOperationError] = useState(null); + const [isUpdating, setIsUpdating] = useState(false); const updateLink = async (enabled: boolean) => { - setIsLoading(true); - setError(null); + setIsUpdating(true); + setOperationError(null); try { const clerkToken = await getToken(RELAY_CLERK_TOKEN_OPTIONS); if (enabled) { @@ -1638,7 +1654,8 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b unlinkPrimaryEnvironmentFromCloud({ clerkToken: clerkToken ?? null }), ); } - setLinked(enabled); + primaryCloudLinkState.refresh(); + refreshManagedRelayEnvironments(); toastManager.add({ type: "success", title: enabled ? "T3 Cloud linked" : "T3 Cloud unlinked", @@ -1648,27 +1665,32 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b }); } catch (cause) { const message = cause instanceof Error ? cause.message : "Could not update T3 Cloud access."; - setError(message); + setOperationError(message); toastManager.add({ type: "error", title: "Could not update T3 Cloud", description: message, }); } finally { - setIsLoading(false); + setIsUpdating(false); } }; + const disabledReason = !isSignedIn + ? "Sign in from T3 Cloud settings to manage this environment." + : !canManageRelay + ? "Your session does not have permission to manage T3 Cloud access." + : null; return ( void updateLink(enabled)} /> } @@ -1683,47 +1705,62 @@ function CloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) } + control={ + + } /> ); } +function EmptyRemoteEnvironments() { + return ( + + + + + + No saved remote environments + + Click “Add environment” to pair another environment, or connect one from T3 + Cloud. + + + + ); +} + +function RemoteEnvironmentRowsSkeleton() { + return ( +
+
+
+ + +
+ +
+
+ ); +} + function ConfiguredCloudRemoteEnvironmentRows({ + primaryEnvironmentId, savedEnvironmentIds, }: { + readonly primaryEnvironmentId: EnvironmentId | null; readonly savedEnvironmentIds: ReadonlyArray; }) { - const { getToken, isSignedIn } = useAuth(); - const [environments, setEnvironments] = useState>([]); + const { getToken } = useAuth(); + const environmentsState = useManagedRelayEnvironments(); const [connectingEnvironmentId, setConnectingEnvironmentId] = useState( null, ); const savedIds = useMemo(() => new Set(savedEnvironmentIds), [savedEnvironmentIds]); - useEffect(() => { - if (!isSignedIn) { - setEnvironments([]); - return; - } - let cancelled = false; - void getToken(RELAY_CLERK_TOKEN_OPTIONS) - .then((clerkToken) => - clerkToken - ? webRuntime.runPromise(listManagedCloudEnvironments({ clerkToken })) - : Promise.resolve([]), - ) - .then((next) => { - if (!cancelled) setEnvironments(next); - }) - .catch(() => { - if (!cancelled) setEnvironments([]); - }); - return () => { - cancelled = true; - }; - }, [getToken, isSignedIn]); - const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => { setConnectingEnvironmentId(environment.environmentId); try { @@ -1752,45 +1789,65 @@ function ConfiguredCloudRemoteEnvironmentRows({ } }; - return environments - .filter((environment) => !savedIds.has(environment.environmentId)) - .map((environment) => ( -
-
-
-
- -

{environment.label}

-
-

T3 Cloud

+ const connectableEnvironments = (environmentsState.data ?? []).filter( + (environment) => + environment.environmentId !== primaryEnvironmentId && + !savedIds.has(environment.environmentId), + ); + + if (savedEnvironmentIds.length === 0 && environmentsState.data === null) { + return ; + } + + if (savedEnvironmentIds.length === 0 && connectableEnvironments.length === 0) { + return ; + } + + return connectableEnvironments.map((environment) => ( +
+
+
+
+ +

{environment.label}

- +

T3 Cloud

+
- )); +
+ )); } function CloudRemoteEnvironmentRows({ + primaryEnvironmentId, savedEnvironmentIds, }: { + readonly primaryEnvironmentId: EnvironmentId | null; readonly savedEnvironmentIds: ReadonlyArray; }) { return hasCloudConfig() ? ( - + + ) : savedEnvironmentIds.length === 0 ? ( + ) : null; } export function ConnectionsSettings() { const desktopBridge = window.desktopBridge; + const primaryEnvironmentId = usePrimaryEnvironmentId(); const primarySessionState = usePrimarySessionState(); const currentSessionScopes = desktopBridge ? AuthAdministrativeScopes @@ -2815,7 +2872,7 @@ export function ConnectionsSettings() { {canManageLocalBackend ? ( <> - + {primaryVersionMismatch ? ( ) : ( - + ))} - - - {savedEnvironmentIds.length === 0 ? ( -
-

- No saved remote environments yet. Click “Add environment” to pair another - environment. -

-
- ) : null} +
); diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index c9253f4321..e8f46505ed 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -574,7 +574,9 @@ describe("GeneralSettingsPanel observability", () => { , ); - await expect.element(page.getByText("Manage local backend")).toBeInTheDocument(); + await expect + .element(page.getByRole("heading", { name: "This environment", exact: true })) + .toBeInTheDocument(); await expect.element(page.getByLabelText("Enable network access")).toBeDisabled(); await expect .element( diff --git a/apps/web/src/environments/primary/requestInit.ts b/apps/web/src/environments/primary/requestInit.ts new file mode 100644 index 0000000000..cf70237380 --- /dev/null +++ b/apps/web/src/environments/primary/requestInit.ts @@ -0,0 +1,7 @@ +import * as Effect from "effect/Effect"; +import { FetchHttpClient } from "effect/unstable/http"; + +export const primaryEnvironmentRequestInit = { credentials: "include" } as const; + +export const withPrimaryEnvironmentRequestInit = (effect: Effect.Effect) => + effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit)); diff --git a/apps/web/src/lib/runtime.ts b/apps/web/src/lib/runtime.ts index abb885e3bb..34f6d8264a 100644 --- a/apps/web/src/lib/runtime.ts +++ b/apps/web/src/lib/runtime.ts @@ -8,6 +8,7 @@ import { PrimaryEnvironmentHttpClient, primaryEnvironmentHttpClientLive, } from "../environments/primary/httpClient"; +import { primaryEnvironmentRequestInit } from "../environments/primary/requestInit"; import { browserCryptoLayer } from "../cloud/dpop"; import { webManagedRelayClientLayer } from "../cloud/managedRelayLayer"; @@ -26,7 +27,7 @@ const primaryHttpRuntime = ManagedRuntime.make( Layer.provide( Layer.mergeAll( remoteHttpClientLayer((input, init) => globalThis.fetch(input, init)), - Layer.succeed(FetchHttpClient.RequestInit, { credentials: "include" }), + Layer.succeed(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit), ), ), ), diff --git a/infra/relay/alchemy.run.ts b/infra/relay/alchemy.run.ts index 4ec6b5abaa..e9a3928758 100644 --- a/infra/relay/alchemy.run.ts +++ b/infra/relay/alchemy.run.ts @@ -6,7 +6,6 @@ import * as Drizzle from "alchemy/Drizzle"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Planetscale from "alchemy/Planetscale"; -import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient"; import { PlanetscaleDatabase, RelayHyperdrive } from "./src/db.ts"; import { ManagedEndpointZone } from "./src/zone.ts"; @@ -20,7 +19,6 @@ export default Alchemy.Stack( Cloudflare.providers(), Drizzle.providers(), Planetscale.providers(), - FetchHttpClient.layer, ), state: Cloudflare.state(), }, diff --git a/infra/relay/migrations/postgres/20260527044716_baseline/migration.sql b/infra/relay/migrations/postgres/20260527044716_baseline/migration.sql index 0871aaa263..694885f380 100644 --- a/infra/relay/migrations/postgres/20260527044716_baseline/migration.sql +++ b/infra/relay/migrations/postgres/20260527044716_baseline/migration.sql @@ -78,7 +78,6 @@ CREATE TABLE "relay_live_activities" ( CREATE TABLE "relay_mobile_devices" ( "user_id" varchar(255), "device_id" varchar(255), - "label" text DEFAULT 'iOS device' NOT NULL, "platform" varchar(16) NOT NULL, "ios_major_version" integer NOT NULL, "app_version" varchar(64), @@ -102,4 +101,4 @@ CREATE INDEX "idx_relay_live_activities_user" ON "relay_live_activities" ("user_ CREATE UNIQUE INDEX "idx_relay_live_activities_activity_push_token" ON "relay_live_activities" ("activity_push_token");--> statement-breakpoint CREATE INDEX "idx_relay_mobile_devices_user" ON "relay_mobile_devices" ("user_id");--> statement-breakpoint CREATE UNIQUE INDEX "idx_relay_mobile_devices_push_token" ON "relay_mobile_devices" ("push_token");--> statement-breakpoint -CREATE UNIQUE INDEX "idx_relay_mobile_devices_push_to_start_token" ON "relay_mobile_devices" ("push_to_start_token"); +CREATE UNIQUE INDEX "idx_relay_mobile_devices_push_to_start_token" ON "relay_mobile_devices" ("push_to_start_token"); \ No newline at end of file diff --git a/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.json b/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.json index 02f9d7d149..aa35a4f8ee 100644 --- a/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.json +++ b/infra/relay/migrations/postgres/20260527044716_baseline/snapshot.json @@ -787,19 +787,6 @@ "schema": "public", "table": "relay_mobile_devices" }, - { - "type": "text", - "typeSchema": null, - "notNull": true, - "dimensions": 0, - "default": "'iOS device'", - "generated": null, - "identity": null, - "name": "label", - "entityType": "columns", - "schema": "public", - "table": "relay_mobile_devices" - }, { "type": "varchar(16)", "typeSchema": null, diff --git a/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/migration.sql b/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/migration.sql new file mode 100644 index 0000000000..291096637a --- /dev/null +++ b/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "relay_mobile_devices" ADD COLUMN "label" text DEFAULT 'iOS device' NOT NULL; diff --git a/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/snapshot.json b/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/snapshot.json new file mode 100644 index 0000000000..d79130adb0 --- /dev/null +++ b/infra/relay/migrations/postgres/20260601225421_add_mobile_device_label/snapshot.json @@ -0,0 +1,1280 @@ +{ + "dialect": "postgres", + "id": "e189638b-4700-4656-b86e-d8baa63f5fe4", + "prevIds": ["ad620f05-3fd1-43b8-a3ca-d4c02543d892"], + "version": "8", + "ddl": [ + { + "isRlsEnabled": false, + "name": "relay_agent_activity_rows", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_delivery_attempts", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_dpop_proofs", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_credentials", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_environment_links", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_live_activities", + "entityType": "tables", + "schema": "public" + }, + { + "isRlsEnabled": false, + "name": "relay_mobile_devices", + "entityType": "tables", + "schema": "public" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "state_json", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "type": "varchar(36)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thread_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "kind", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "source_job_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "token_suffix", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_status", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_reason", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "apns_id", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "transport_error", + "entityType": "columns", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "type": "varchar(128)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "thumbprint", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "jti", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "iat", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "expires_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "credential_hash", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'T3 Environment'", + "generated": null, + "identity": null, + "name": "environment_label", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "environment_public_key", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_http_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_ws_base_url", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(32)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "endpoint_provider_kind", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "notifications_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "true", + "generated": null, + "identity": null, + "name": "live_activities_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "boolean", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "false", + "generated": null, + "identity": null, + "name": "managed_tunnels_enabled", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(191)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_by_device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "revoked_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_environment_links" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "activity_push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_start_queued_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "remote_started_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ended_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_aggregate_json", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "last_live_activity_delivery_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_live_activities" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "user_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(255)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "device_id", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": "'iOS device'", + "generated": null, + "identity": null, + "name": "label", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(16)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "platform", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "integer", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "ios_major_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "app_version", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "text", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "push_to_start_token", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "jsonb", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "preferences_json", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "created_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "type": "varchar(64)", + "typeSchema": null, + "notNull": true, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "name": "updated_at", + "entityType": "columns", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "updated_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_agent_activity_rows_updated", + "entityType": "indexes", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "thread_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "created_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "source_job_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_delivery_attempts_source_job", + "entityType": "indexes", + "schema": "public", + "table": "relay_delivery_attempts" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "expires_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_dpop_proofs_expires_at", + "entityType": "indexes", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "credential_hash", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_hash", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "environment_public_key", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_credentials_environment_key", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_credentials" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "environment_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + }, + { + "value": "revoked_at", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_environment_links_environment", + "entityType": "indexes", + "schema": "public", + "table": "relay_environment_links" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "activity_push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_live_activities_activity_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_live_activities" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "user_id", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": false, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_user", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "nameExplicit": true, + "columns": [ + { + "value": "push_to_start_token", + "isExpression": false, + "asc": true, + "nullsFirst": false, + "opclass": null + } + ], + "isUnique": true, + "where": null, + "with": "", + "method": "btree", + "concurrently": false, + "name": "idx_relay_mobile_devices_push_to_start_token", + "entityType": "indexes", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["environment_id", "environment_public_key", "thread_id"], + "nameExplicit": false, + "name": "relay_agent_activity_rows_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_agent_activity_rows" + }, + { + "columns": ["thumbprint", "jti"], + "nameExplicit": false, + "name": "relay_dpop_proofs_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_dpop_proofs" + }, + { + "columns": ["user_id", "environment_id"], + "nameExplicit": false, + "name": "relay_environment_links_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_environment_links" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_live_activities_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_live_activities" + }, + { + "columns": ["user_id", "device_id"], + "nameExplicit": false, + "name": "relay_mobile_devices_pkey", + "entityType": "pks", + "schema": "public", + "table": "relay_mobile_devices" + }, + { + "columns": ["id"], + "nameExplicit": false, + "name": "relay_delivery_attempts_pkey", + "schema": "public", + "table": "relay_delivery_attempts", + "entityType": "pks" + }, + { + "columns": ["credential_id"], + "nameExplicit": false, + "name": "relay_environment_credentials_pkey", + "schema": "public", + "table": "relay_environment_credentials", + "entityType": "pks" + } + ], + "renames": [] +} diff --git a/infra/relay/src/db.ts b/infra/relay/src/db.ts index a01ec05c0a..e4094240d9 100644 --- a/infra/relay/src/db.ts +++ b/infra/relay/src/db.ts @@ -32,7 +32,7 @@ export const PlanetscaleDatabase = Effect.gen(function* () { inheritedRoles: ["pg_read_all_data", "pg_write_all_data"], }); - return { database, runtimeRole, schema }; + return { database, runtimeRole }; }); export const RelayHyperdrive = Effect.gen(function* () { diff --git a/packages/client-runtime/src/index.ts b/packages/client-runtime/src/index.ts index 7aa36d29fb..ac32e794fe 100644 --- a/packages/client-runtime/src/index.ts +++ b/packages/client-runtime/src/index.ts @@ -27,3 +27,4 @@ export * from "./archivedThreadsState.ts"; export * from "./checkpointDiffState.ts"; export * from "./remote.ts"; export * from "./managedRelay.ts"; +export * from "./managedRelayState.ts"; diff --git a/packages/client-runtime/src/managedRelayState.test.ts b/packages/client-runtime/src/managedRelayState.test.ts new file mode 100644 index 0000000000..e6c51bb808 --- /dev/null +++ b/packages/client-runtime/src/managedRelayState.test.ts @@ -0,0 +1,144 @@ +import { EnvironmentId } from "@t3tools/contracts"; +import type { + RelayClientDeviceRecord, + RelayClientEnvironmentRecord, + RelayEnvironmentStatusResponse, +} from "@t3tools/contracts/relay"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { Atom, AtomRegistry } from "effect/unstable/reactivity"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { ManagedRelayClient, type ManagedRelayClientShape } from "./managedRelay.ts"; +import { + createManagedRelayQueryManager, + createManagedRelaySession, + readManagedRelaySnapshotState, + setManagedRelaySession, +} from "./managedRelayState.ts"; + +let registry = AtomRegistry.make(); + +const environment = { + environmentId: EnvironmentId.make("environment-1"), + label: "Main environment", + endpoint: { + httpBaseUrl: "https://environment.example.test", + wsBaseUrl: "wss://environment.example.test", + providerKind: "cloudflare_tunnel", + }, + linkedAt: "2026-06-01T00:00:00.000Z", +} satisfies RelayClientEnvironmentRecord; + +const device = { + deviceId: "device-1", + label: "Julius iPhone", + platform: "ios", + iosMajorVersion: 18, + appVersion: null, + notifications: { + enabled: true, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, + }, + liveActivities: { + enabled: true, + }, + updatedAt: "2026-06-01T00:00:00.000Z", +} satisfies RelayClientDeviceRecord; + +function resetRegistry() { + registry.dispose(); + registry = AtomRegistry.make(); +} + +function createManager(overrides?: Partial) { + const client = ManagedRelayClient.of({ + relayUrl: "https://relay.example.test", + listEnvironments: () => Effect.succeed([environment]), + listDevices: () => Effect.succeed([device]), + createEnvironmentLinkChallenge: () => Effect.die("unused"), + linkEnvironment: () => Effect.die("unused"), + unlinkEnvironment: () => Effect.die("unused"), + getEnvironmentStatus: () => + Effect.succeed({ + environmentId: environment.environmentId, + endpoint: environment.endpoint, + status: "online", + checkedAt: "2026-06-01T00:00:00.000Z", + }), + connectEnvironment: () => Effect.die("unused"), + registerDevice: () => Effect.die("unused"), + unregisterDevice: () => Effect.die("unused"), + registerLiveActivity: () => Effect.die("unused"), + resetTokenCache: Effect.void, + ...overrides, + }); + const runtime = Atom.runtime(Layer.succeed(ManagedRelayClient, client)); + return createManagedRelayQueryManager(runtime, { staleTimeMs: 60_000 }); +} + +function setSession() { + setManagedRelaySession( + registry, + createManagedRelaySession({ + accountId: "account-1", + readClerkToken: () => Promise.resolve("clerk-token"), + }), + ); +} + +describe("createManagedRelayQueryManager", () => { + afterEach(resetRegistry); + + it("keeps environment snapshots cached and refreshes them explicitly", async () => { + const listEnvironments = vi.fn(() => Effect.succeed([environment])); + const manager = createManager({ listEnvironments }); + setSession(); + const atom = manager.environmentsAtom("account-1"); + + registry.get(atom); + await vi.waitFor(() => expect(listEnvironments).toHaveBeenCalledTimes(1)); + + registry.get(manager.environmentsAtom("account-1")); + expect(listEnvironments).toHaveBeenCalledTimes(1); + + manager.refreshEnvironments(registry, "account-1"); + await vi.waitFor(() => expect(listEnvironments).toHaveBeenCalledTimes(2)); + }); + + it("loads device snapshots through the current account session", async () => { + const listDevices = vi.fn(() => Effect.succeed([device])); + const manager = createManager({ listDevices }); + setSession(); + const atom = manager.devicesAtom("account-1"); + + registry.get(atom); + await vi.waitFor(() => { + expect(readManagedRelaySnapshotState(registry.get(atom)).data).toEqual([device]); + }); + }); + + it("rejects status responses for a different environment", async () => { + const mismatchedStatus = { + environmentId: EnvironmentId.make("environment-2"), + endpoint: environment.endpoint, + status: "online", + checkedAt: "2026-06-01T00:00:00.000Z", + } satisfies RelayEnvironmentStatusResponse; + const manager = createManager({ + getEnvironmentStatus: () => Effect.succeed(mismatchedStatus), + }); + setSession(); + const atom = manager.environmentStatusAtom({ accountId: "account-1", environment }); + + registry.get(atom); + await vi.waitFor(() => { + expect(readManagedRelaySnapshotState(registry.get(atom)).error).toBe( + "Relay returned status for a different environment.", + ); + }); + }); +}); diff --git a/packages/client-runtime/src/managedRelayState.ts b/packages/client-runtime/src/managedRelayState.ts new file mode 100644 index 0000000000..2bbebd155a --- /dev/null +++ b/packages/client-runtime/src/managedRelayState.ts @@ -0,0 +1,253 @@ +import type { + RelayClientEnvironmentRecord, + RelayEnvironmentStatusResponse, +} from "@t3tools/contracts/relay"; +import { + RelayEnvironmentConnectScope, + RelayEnvironmentStatusScope, +} from "@t3tools/contracts/relay"; +import * as Cause from "effect/Cause"; +import * as Data from "effect/Data"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom, type AtomRegistry } from "effect/unstable/reactivity"; + +import { ManagedRelayClient } from "./managedRelay.ts"; + +const DEFAULT_STALE_TIME_MS = 15_000; +const DEFAULT_IDLE_TTL_MS = 5 * 60_000; + +export interface ManagedRelaySession { + readonly accountId: string; + readonly readClerkToken: () => Effect.Effect; +} + +export interface ManagedRelaySnapshotState { + readonly data: A | null; + readonly error: string | null; + readonly isPending: boolean; +} + +export class ManagedRelaySessionError extends Data.TaggedError("ManagedRelaySessionError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export class ManagedRelaySnapshotError extends Data.TaggedError("ManagedRelaySnapshotError")<{ + readonly message: string; +}> {} + +export const managedRelaySessionAtom = Atom.make(null).pipe( + Atom.keepAlive, + Atom.withLabel("managed-relay:session"), +); + +export function createManagedRelaySession(input: { + readonly accountId: string; + readonly readClerkToken: () => Promise; +}): ManagedRelaySession { + return { + accountId: input.accountId, + readClerkToken: () => + Effect.tryPromise({ + try: input.readClerkToken, + catch: (cause) => + new ManagedRelaySessionError({ + message: "Could not obtain the T3 Cloud session token.", + cause, + }), + }), + }; +} + +export function setManagedRelaySession( + registry: AtomRegistry.AtomRegistry, + session: ManagedRelaySession | null, +): void { + registry.set(managedRelaySessionAtom, session); +} + +function requireClerkToken( + get: Atom.AtomContext, + accountId: string, +): Effect.Effect { + const session = get(managedRelaySessionAtom); + if (!session || session.accountId !== accountId) { + return Effect.fail( + new ManagedRelaySessionError({ + message: "Sign in to T3 Cloud before loading relay data.", + }), + ); + } + return session.readClerkToken().pipe( + Effect.flatMap((token) => + token + ? Effect.succeed(token) + : Effect.fail( + new ManagedRelaySessionError({ + message: "The T3 Cloud session token is unavailable.", + }), + ), + ), + ); +} + +function statusKey(input: { + readonly accountId: string; + readonly environment: RelayClientEnvironmentRecord; +}): string { + return JSON.stringify(input); +} + +function parseStatusKey(key: string): { + readonly accountId: string; + readonly environment: RelayClientEnvironmentRecord; +} { + return JSON.parse(key) as { + readonly accountId: string; + readonly environment: RelayClientEnvironmentRecord; + }; +} + +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; + if (result._tag === "Failure") { + const cause = Cause.squash(result.cause); + error = cause instanceof Error ? cause.message : "Could not load T3 Cloud data."; + } + return { + data: Option.getOrNull(AsyncResult.value(result)), + error, + isPending: result.waiting, + }; +} + +export function createManagedRelayQueryManager( + runtime: Atom.AtomRuntime, + options?: { + readonly staleTimeMs?: number; + readonly idleTtlMs?: number; + }, +) { + const staleTime = options?.staleTimeMs ?? DEFAULT_STALE_TIME_MS; + const idleTtl = options?.idleTtlMs ?? DEFAULT_IDLE_TTL_MS; + + const environmentsAtom = Atom.family((accountId: string) => + runtime + .atom((get) => + Effect.gen(function* () { + const clerkToken = yield* requireClerkToken(get, accountId); + const relay = yield* ManagedRelayClient; + return yield* relay.listEnvironments({ clerkToken }); + }), + ) + .pipe( + Atom.swr({ staleTime, revalidateOnMount: true }), + Atom.setIdleTTL(idleTtl), + Atom.withLabel(`managed-relay:environments:${accountId}`), + ), + ); + + const devicesAtom = Atom.family((accountId: string) => + runtime + .atom((get) => + Effect.gen(function* () { + const clerkToken = yield* requireClerkToken(get, accountId); + const relay = yield* ManagedRelayClient; + return yield* relay.listDevices({ clerkToken }); + }), + ) + .pipe( + Atom.swr({ staleTime, revalidateOnMount: true }), + Atom.setIdleTTL(idleTtl), + Atom.withLabel(`managed-relay:devices:${accountId}`), + ), + ); + + const environmentStatusAtom = Atom.family((key: string) => { + const { accountId, environment } = parseStatusKey(key); + return runtime + .atom((get) => + Effect.gen(function* () { + const clerkToken = yield* requireClerkToken(get, accountId); + const relay = yield* ManagedRelayClient; + const status = yield* relay.getEnvironmentStatus({ + clerkToken, + scopes: [RelayEnvironmentStatusScope, RelayEnvironmentConnectScope], + environmentId: environment.environmentId, + }); + return yield* validateEnvironmentStatus(environment, status); + }), + ) + .pipe( + Atom.swr({ staleTime, revalidateOnMount: true }), + Atom.setIdleTTL(idleTtl), + Atom.withLabel(`managed-relay:environment-status:${key}`), + ); + }); + + return { + environmentsAtom, + devicesAtom, + environmentStatusAtom: (input: { + readonly accountId: string; + readonly environment: RelayClientEnvironmentRecord; + }) => environmentStatusAtom(statusKey(input)), + 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))); + }, + }; +} diff --git a/patches/alchemy@2.0.0-beta.49.patch b/patches/alchemy@2.0.0-beta.49.patch new file mode 100644 index 0000000000..8d0cebac3a --- /dev/null +++ b/patches/alchemy@2.0.0-beta.49.patch @@ -0,0 +1,356 @@ +diff --git a/bin/exec.js b/bin/exec.js +index 9cd9f8059..8317c57be 100644 +--- a/bin/exec.js ++++ b/bin/exec.js +@@ -366,6 +366,7 @@ const of = (resource) => { + const asOutput = (t) => isOutput(t) ? t : Effect.isEffect(t) ? new EffectExpr(VoidExpr, () => t) : new LiteralExpr(t); + const isOutput = (value) => value && (typeof value === "object" || typeof value === "function") && ExprSymbol in value; + const ExprSymbol = Symbol.for("alchemy/Expr"); ++const exprKind = (node) => node?.[ExprSymbol]?.kind ?? node?.kind; + const isExpr = (value) => value && (typeof value === "object" || typeof value === "function") && ExprSymbol in value; + var BaseExpr = class { + constructor() {} +@@ -389,7 +390,7 @@ var BaseExpr = class { + return this[inspect](); + } + }; +-const isResourceExpr = (node) => node?.kind === "ResourceExpr"; ++const isResourceExpr = (node) => exprKind(node) === "ResourceExpr"; + var ResourceExpr = class extends BaseExpr { + src; + stables; +@@ -404,7 +405,7 @@ var ResourceExpr = class extends BaseExpr { + return this.src.LogicalId; + } + }; +-const isPropExpr = (node) => node?.kind === "PropExpr"; ++const isPropExpr = (node) => exprKind(node) === "PropExpr"; + var PropExpr = class extends BaseExpr { + expr; + identifier; +@@ -419,7 +420,7 @@ var PropExpr = class extends BaseExpr { + return `${this.expr[inspect]()}.${this.identifier.toString()}`; + } + }; +-const isLiteralExpr = (node) => node?.kind === "LiteralExpr"; ++const isLiteralExpr = (node) => exprKind(node) === "LiteralExpr"; + var LiteralExpr = class extends BaseExpr { + value; + kind = "LiteralExpr"; +@@ -433,7 +434,7 @@ var LiteralExpr = class extends BaseExpr { + } + }; + const VoidExpr = new LiteralExpr(void 0); +-const isApplyExpr = (node) => node?.kind === "ApplyExpr"; ++const isApplyExpr = (node) => exprKind(node) === "ApplyExpr"; + var ApplyExpr = class extends BaseExpr { + expr; + f; +@@ -448,7 +449,7 @@ var ApplyExpr = class extends BaseExpr { + return `${this.expr[inspect]()}.map(${this.f.toString()})`; + } + }; +-const isFlatMapExpr = (node) => node?.kind === "FlatMapExpr"; ++const isFlatMapExpr = (node) => exprKind(node) === "FlatMapExpr"; + var FlatMapExpr = class extends BaseExpr { + expr; + f; +@@ -463,7 +464,7 @@ var FlatMapExpr = class extends BaseExpr { + return `${this.expr[inspect]()}.flatMap(${this.f.toString()})`; + } + }; +-const isEffectExpr = (node) => node?.kind === "EffectExpr"; ++const isEffectExpr = (node) => exprKind(node) === "EffectExpr"; + var EffectExpr = class extends BaseExpr { + expr; + f; +@@ -478,7 +479,7 @@ var EffectExpr = class extends BaseExpr { + return `${this.expr[inspect]()}.mapEffect(${this.f.toString()})`; + } + }; +-const isNamedExpr = (node) => node?.kind === "NamedExpr"; ++const isNamedExpr = (node) => exprKind(node) === "NamedExpr"; + /** + * Wraps another `Expr` and overrides its `toString()` / inspect output. + * +@@ -500,7 +501,7 @@ var NamedExpr = class extends BaseExpr { + return this.bindingName; + } + }; +-const isAllExpr = (node) => node?.kind === "AllExpr"; ++const isAllExpr = (node) => exprKind(node) === "AllExpr"; + var AllExpr = class extends BaseExpr { + outs; + kind = "AllExpr"; +@@ -513,7 +514,7 @@ var AllExpr = class extends BaseExpr { + return `all(${this.outs.map((out) => out[inspect]()).join(", ")})`; + } + }; +-const isRefExpr = (node) => node?.kind === "RefExpr"; ++const isRefExpr = (node) => exprKind(node) === "RefExpr"; + var RefExpr = class extends BaseExpr { + stack; + stage; +@@ -530,7 +531,7 @@ var RefExpr = class extends BaseExpr { + return `ref(${this.resourceId}, { stack: ${this.stack}, stage: ${this.stage} })`; + } + }; +-const isStackRefExpr = (node) => node?.kind === "StackRefExpr"; ++const isStackRefExpr = (node) => exprKind(node) === "StackRefExpr"; + /** + * A reference to the persisted output of a Stack at `(stack, stage)`. + * +diff --git a/lib/Drizzle/Schema.js b/lib/Drizzle/Schema.js +index 95aa38b5d..963ec8534 100644 +--- a/lib/Drizzle/Schema.js ++++ b/lib/Drizzle/Schema.js +@@ -99,11 +99,11 @@ export const SchemaProvider = () => Provider.effect(Schema, Effect.gen(function* + const dialect = props.dialect ?? "postgres"; + const kit = yield* loadKit(dialect); + const schemaModule = yield* loadSchemaModule(props); ++ const prevEntry = yield* readLatestSnapshot(out); + const cur = yield* Effect.tryPromise({ +- try: () => kit.generateDrizzleJson(schemaModule), ++ try: () => kit.generateDrizzleJson(schemaModule, prevEntry?.snapshot?.id), + catch: (cause) => new Error(`drizzle-kit generateDrizzleJson failed: ${cause}`), + }); +- const prevEntry = yield* readLatestSnapshot(out); + // For the initial migration, drizzle-kit needs an *empty* snapshot + // produced by `generateDrizzleJson({})`, not a bare `{}` — the + // snapshot has internal fields (`ddl`, etc.) that the differ reads. +@@ -181,4 +181,4 @@ export const SchemaProvider = () => Provider.effect(Schema, Effect.gen(function* + }), + }; + })); +-//# sourceMappingURL=Schema.js.map +\ No newline at end of file ++//# sourceMappingURL=Schema.js.map +diff --git a/lib/Output.js b/lib/Output.js +index ce26480d1..e3862cce7 100644 +--- a/lib/Output.js ++++ b/lib/Output.js +@@ -28,6 +28,7 @@ export const isOutput = (value) => value && + (typeof value === "object" || typeof value === "function") && + ExprSymbol in value; + export const ExprSymbol = Symbol.for("alchemy/Expr"); ++const exprKind = (node) => node?.[ExprSymbol]?.kind ?? node?.kind; + export const isExpr = (value) => value && + (typeof value === "object" || typeof value === "function") && + ExprSymbol in value; +@@ -57,7 +58,7 @@ export class BaseExpr { + return this[inspect](); + } + } +-export const isResourceExpr = (node) => node?.kind === "ResourceExpr"; ++export const isResourceExpr = (node) => exprKind(node) === "ResourceExpr"; + export class ResourceExpr extends BaseExpr { + src; + stables; +@@ -72,7 +73,7 @@ export class ResourceExpr extends BaseExpr { + return this.src.LogicalId; + } + } +-export const isPropExpr = (node) => node?.kind === "PropExpr"; ++export const isPropExpr = (node) => exprKind(node) === "PropExpr"; + export class PropExpr extends BaseExpr { + expr; + identifier; +@@ -88,7 +89,7 @@ export class PropExpr extends BaseExpr { + } + } + export const literal = (value) => new LiteralExpr(value); +-export const isLiteralExpr = (node) => node?.kind === "LiteralExpr"; ++export const isLiteralExpr = (node) => exprKind(node) === "LiteralExpr"; + export class LiteralExpr extends BaseExpr { + value; + kind = "LiteralExpr"; +@@ -106,7 +107,7 @@ export const map = ((...args) => args.length === 1 + ? (output) => new ApplyExpr(output, args[0]) + : new ApplyExpr(args[0], args[1])); + //Output.ApplyExpr +-export const isApplyExpr = (node) => node?.kind === "ApplyExpr"; ++export const isApplyExpr = (node) => exprKind(node) === "ApplyExpr"; + export class ApplyExpr extends BaseExpr { + expr; + f; +@@ -125,7 +126,7 @@ export const mapEffect = (fn) => (output) => new EffectExpr(output, fn); + export const flatMap = ((...args) => args.length === 1 + ? (output) => new FlatMapExpr(output, args[0]) + : new FlatMapExpr(args[0], args[1])); +-export const isFlatMapExpr = (node) => node?.kind === "FlatMapExpr"; ++export const isFlatMapExpr = (node) => exprKind(node) === "FlatMapExpr"; + export class FlatMapExpr extends BaseExpr { + expr; + f; +@@ -140,7 +141,7 @@ export class FlatMapExpr extends BaseExpr { + return `${this.expr[inspect]()}.flatMap(${this.f.toString()})`; + } + } +-export const isEffectExpr = (node) => node?.kind === "EffectExpr"; ++export const isEffectExpr = (node) => exprKind(node) === "EffectExpr"; + export class EffectExpr extends BaseExpr { + expr; + f; +@@ -155,7 +156,7 @@ export class EffectExpr extends BaseExpr { + return `${this.expr[inspect]()}.mapEffect(${this.f.toString()})`; + } + } +-export const isNamedExpr = (node) => node?.kind === "NamedExpr"; ++export const isNamedExpr = (node) => exprKind(node) === "NamedExpr"; + /** + * Wraps another `Expr` and overrides its `toString()` / inspect output. + * +@@ -179,7 +180,7 @@ export class NamedExpr extends BaseExpr { + } + export const named = (expr, name) => new NamedExpr(expr, name); + export const all = (...outs) => new AllExpr(outs); +-export const isAllExpr = (node) => node?.kind === "AllExpr"; ++export const isAllExpr = (node) => exprKind(node) === "AllExpr"; + export class AllExpr extends BaseExpr { + outs; + kind = "AllExpr"; +@@ -192,7 +193,7 @@ export class AllExpr extends BaseExpr { + return `all(${this.outs.map((out) => out[inspect]()).join(", ")})`; + } + } +-export const isRefExpr = (node) => node?.kind === "RefExpr"; ++export const isRefExpr = (node) => exprKind(node) === "RefExpr"; + export class RefExpr extends BaseExpr { + stack; + stage; +@@ -209,7 +210,7 @@ export class RefExpr extends BaseExpr { + return `ref(${this.resourceId}, { stack: ${this.stack}, stage: ${this.stage} })`; + } + } +-export const isStackRefExpr = (node) => node?.kind === "StackRefExpr"; ++export const isStackRefExpr = (node) => exprKind(node) === "StackRefExpr"; + /** + * A reference to the persisted output of a Stack at `(stack, stage)`. + * +diff --git a/src/Drizzle/Schema.ts b/src/Drizzle/Schema.ts +index 07adafc9f..601b06b24 100644 +--- a/src/Drizzle/Schema.ts ++++ b/src/Drizzle/Schema.ts +@@ -181,13 +181,17 @@ export const SchemaProvider = () => + const dialect = props.dialect ?? "postgres"; + const kit = yield* loadKit(dialect); + const schemaModule = yield* loadSchemaModule(props); ++ const prevEntry = yield* readLatestSnapshot(out); + const cur = yield* Effect.tryPromise({ +- try: () => kit.generateDrizzleJson(schemaModule), ++ try: () => ++ kit.generateDrizzleJson( ++ schemaModule, ++ (prevEntry?.snapshot as { id?: string } | undefined)?.id, ++ ), + catch: (cause) => + new Error(`drizzle-kit generateDrizzleJson failed: ${cause}`), + }); + +- const prevEntry = yield* readLatestSnapshot(out); + // For the initial migration, drizzle-kit needs an *empty* snapshot + // produced by `generateDrizzleJson({})`, not a bare `{}` — the + // snapshot has internal fields (`ddl`, etc.) that the differ reads. +diff --git a/src/Output.ts b/src/Output.ts +index 967d27d8f..46e4622e3 100644 +--- a/src/Output.ts ++++ b/src/Output.ts +@@ -72,6 +72,8 @@ export type ToOutput = [Extract] extends [never] + + export const ExprSymbol = Symbol.for("alchemy/Expr"); + ++const exprKind = (node: any): unknown => node?.[ExprSymbol]?.kind ?? node?.kind; ++ + export const isExpr = (value: any): value is Expr => + value && + (typeof value === "object" || typeof value === "function") && +@@ -145,7 +147,7 @@ export type ArrayExpr = Output & { + + export const isResourceExpr = ( + node: Expr | any, +-): node is ResourceExpr => node?.kind === "ResourceExpr"; ++): node is ResourceExpr => exprKind(node) === "ResourceExpr"; + + export class ResourceExpr extends BaseExpr { + readonly kind = "ResourceExpr"; +@@ -163,7 +165,7 @@ export class ResourceExpr extends BaseExpr { + + export const isPropExpr = ( + node: any, +-): node is PropExpr => node?.kind === "PropExpr"; ++): node is PropExpr => exprKind(node) === "PropExpr"; + + export class PropExpr< + A = any, +@@ -186,7 +188,7 @@ export class PropExpr< + export const literal = (value: A) => new LiteralExpr(value); + + export const isLiteralExpr = (node: any): node is LiteralExpr => +- node?.kind === "LiteralExpr"; ++ exprKind(node) === "LiteralExpr"; + + export class LiteralExpr extends BaseExpr { + readonly kind = "LiteralExpr"; +@@ -217,7 +219,7 @@ export const map: { + //Output.ApplyExpr + export const isApplyExpr = ( + node: Output, +-): node is ApplyExpr => node?.kind === "ApplyExpr"; ++): node is ApplyExpr => exprKind(node) === "ApplyExpr"; + + export class ApplyExpr extends BaseExpr { + readonly kind = "ApplyExpr"; +@@ -259,7 +261,7 @@ export const flatMap: { + + export const isFlatMapExpr = ( + node: any, +-): node is FlatMapExpr => node?.kind === "FlatMapExpr"; ++): node is FlatMapExpr => exprKind(node) === "FlatMapExpr"; + + export class FlatMapExpr extends BaseExpr< + B, +@@ -280,7 +282,7 @@ export class FlatMapExpr extends BaseExpr< + + export const isEffectExpr = ( + node: any, +-): node is EffectExpr => node?.kind === "EffectExpr"; ++): node is EffectExpr => exprKind(node) === "EffectExpr"; + + export class EffectExpr extends BaseExpr< + B, +@@ -301,7 +303,7 @@ export class EffectExpr extends BaseExpr< + + export const isNamedExpr = ( + node: any, +-): node is NamedExpr => node?.kind === "NamedExpr"; ++): node is NamedExpr => exprKind(node) === "NamedExpr"; + + /** + * Wraps another `Expr` and overrides its `toString()` / inspect output. +@@ -352,7 +354,7 @@ type Tuple< + + export const isAllExpr = ( + node: any, +-): node is AllExpr => node?.kind === "AllExpr"; ++): node is AllExpr => exprKind(node) === "AllExpr"; + + export class AllExpr extends BaseExpr { + readonly kind = "AllExpr"; +@@ -366,7 +368,7 @@ export class AllExpr extends BaseExpr { + } + + export const isRefExpr = (node: any): node is RefExpr => +- node?.kind === "RefExpr"; ++ exprKind(node) === "RefExpr"; + + export class RefExpr extends BaseExpr { + readonly kind = "RefExpr"; +@@ -384,7 +386,7 @@ export class RefExpr extends BaseExpr { + } + + export const isStackRefExpr = (node: any): node is StackRefExpr => +- node?.kind === "StackRefExpr"; ++ exprKind(node) === "StackRefExpr"; + + /** + * A reference to the persisted output of a Stack at `(stack, stage)`. diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 644bb663de..ad15dce3ae 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -67,5 +67,6 @@ packageExtensions: patchedDependencies: "@expo/metro-config@56.0.13": patches/@expo%2Fmetro-config@56.0.13.patch "@pierre/diffs@1.1.20": patches/@pierre%2Fdiffs@1.1.20.patch + alchemy@2.0.0-beta.49: patches/alchemy@2.0.0-beta.49.patch effect@4.0.0-beta.73: patches/effect@4.0.0-beta.73.patch react-native-nitro-modules@0.35.9: patches/react-native-nitro-modules@0.35.9.patch