refactor(cloud): retain relay queries with atoms

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-03 23:48:05 -07:00
1 parent 15b21b6e35
commit 4453bd0fd9
33 files changed
+2734 -355

No files matched your search

+31 -80
View File
@@ -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<EnvironmentId | null>(null);
const [cloudEnvironments, setCloudEnvironments] = useState<
ReadonlyArray<CloudEnvironmentRecordWithStatus>
>([]);
const [cloudStatus, setCloudStatus] = useState<"idle" | "loading" | "error">("idle");
const [cloudError, setCloudError] = useState<string | null>(null);
const cloudEnvironmentsState = useManagedRelayEnvironments();
const [connectingCloudEnvironmentId, setConnectingCloudEnvironmentId] = useState<string | null>(
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() {
</Text>
<Pressable
accessibilityRole="button"
disabled={cloudStatus === "loading"}
onPress={refreshCloudEnvironments}
disabled={cloudEnvironmentsState.isPending}
onPress={cloudEnvironmentsState.refresh}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{cloudStatus === "loading" ? (
{cloudEnvironmentsState.isPending ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
@@ -233,17 +183,17 @@ export default function SettingsEnvironmentsRouteScreen() {
{availableCloudEnvironments.length > 0 ? (
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
{availableCloudEnvironments.map((record, index) => (
{availableCloudEnvironments.map((environment, index) => (
<CloudEnvironmentRow
key={record.environment.environmentId}
record={record}
key={environment.environmentId}
environment={environment}
borderTop={index !== 0}
isConnecting={connectingCloudEnvironmentId === record.environment.environmentId}
onConnect={() => handleConnectCloudEnvironment(record)}
isConnecting={connectingCloudEnvironmentId === environment.environmentId}
onConnect={() => handleConnectCloudEnvironment(environment)}
/>
))}
</View>
) : cloudStatus === "loading" ? (
) : cloudEnvironmentsState.data === null ? (
<View
collapsable={false}
className="items-center gap-3 rounded-[24px] bg-card px-6 py-6"
@@ -253,13 +203,13 @@ export default function SettingsEnvironmentsRouteScreen() {
Loading linked cloud environments.
</Text>
</View>
) : cloudStatus === "error" ? (
) : cloudEnvironmentsState.error ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card px-5 py-5">
<Text className="text-[15px] font-t3-bold text-foreground">
Could not load T3 Cloud environments
</Text>
<Text className="text-[13px] leading-[18px] text-foreground-muted">
{cloudError}
{cloudEnvironmentsState.error}
</Text>
</View>
) : (
@@ -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: {
</View>
<View className="min-w-0 flex-1 gap-0.5">
<Text className="text-[16px] font-t3-bold leading-[21px] text-foreground" numberOfLines={1}>
{environment.label}
{props.environment.label}
</Text>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{environment.endpoint.httpBaseUrl}
{props.environment.endpoint.httpBaseUrl}
</Text>
<Text className="text-[12px] leading-[16px] text-foreground-muted" numberOfLines={1}>
{statusText}
+3
View File
@@ -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.
}
@@ -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]);
@@ -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",
@@ -547,6 +547,7 @@ export function connectCloudEnvironment(input: {
bearerToken: null,
authenticationMethod: "dpop",
dpopAccessToken: bootstrap.access_token,
relayManaged: true,
};
});
}
@@ -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<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environments:null"));
const EMPTY_ENVIRONMENT_STATUS_ATOM = Atom.make(
AsyncResult.initial<RelayEnvironmentStatusResponse, never>(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);
}
}
@@ -113,56 +113,66 @@ export function ConnectionEnvironmentRow(props: {
exiting={FadeOut.duration(150)}
className="gap-3 px-4 pb-4"
>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Label
{props.environment.isRelayManaged ? (
<Text className="text-[13px] leading-[18px] text-foreground-muted">
Managed by T3 Cloud. Tunnel details update automatically.
</Text>
<TextInput
autoCapitalize="words"
autoCorrect={false}
placeholder="My MacBook"
placeholderTextColor={placeholderColor}
value={label}
onChangeText={setLabel}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
) : (
<>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
Label
</Text>
<TextInput
autoCapitalize="words"
autoCorrect={false}
placeholder="My MacBook"
placeholderTextColor={placeholderColor}
value={label}
onChangeText={setLabel}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
URL
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={url}
onChangeText={setUrl}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
<View className="gap-1.5">
<Text
className="text-[11px] font-t3-bold uppercase text-foreground-muted"
style={{ letterSpacing: 0.8 }}
>
URL
</Text>
<TextInput
autoCapitalize="none"
autoCorrect={false}
keyboardType="url"
placeholder="192.168.1.100:8080"
placeholderTextColor={placeholderColor}
value={url}
onChangeText={setUrl}
className="rounded-[14px] border border-input-border bg-input px-4 py-3 text-[15px] text-foreground"
/>
</View>
</>
)}
<View className="flex-row gap-2">
<Pressable
className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5 active:opacity-70"
onPress={handleSave}
>
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
<Text
className="text-[12px] font-t3-bold uppercase text-primary-foreground"
style={{ letterSpacing: 0.8 }}
<View className="flex-row justify-end gap-2">
{props.environment.isRelayManaged ? null : (
<Pressable
className="min-h-[42px] flex-1 flex-row items-center justify-center gap-1.5 rounded-[14px] bg-primary px-3.5 py-2.5 active:opacity-70"
onPress={handleSave}
>
Save
</Text>
</Pressable>
<SymbolView name="checkmark" size={13} tintColor={primaryFg} type="monochrome" />
<Text
className="text-[12px] font-t3-bold uppercase text-primary-foreground"
style={{ letterSpacing: 0.8 }}
>
Save
</Text>
</Pressable>
)}
<Pressable
className="h-[42px] w-[42px] items-center justify-center rounded-[14px] border border-input-border bg-input active:opacity-70"
+14 -1
View File
@@ -1,6 +1,10 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { mobileAuthClientMetadata, redactPairingCredential } from "./connection";
import {
isRelayManagedConnection,
mobileAuthClientMetadata,
redactPairingCredential,
} from "./connection";
vi.mock("./runtime", () => ({
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);
});
});
+7
View File
@@ -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<SavedRemoteConnection, "authenticationMethod" | "relayManaged">,
): boolean {
return connection.relayManaged === true || connection.authenticationMethod === "dpop";
}
export async function bootstrapRemoteConnection(
input: RemoteConnectionInput,
): Promise<SavedRemoteConnection> {
@@ -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;
}
@@ -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;
}
+13 -5
View File
@@ -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 = `<svg xmlns="http://www.w3.org/2000/svg" vi
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
export const browserApiCorsLayer = HttpRouter.cors({
allowedMethods: browserApiCorsAllowedMethods,
allowedHeaders: browserApiCorsAllowedHeaders,
maxAge: 600,
});
export const browserApiCorsLayer = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig;
const devOrigin = config.devUrl?.origin;
return HttpRouter.cors({
...(devOrigin ? { allowedOrigins: [devOrigin], credentials: true } : {}),
allowedMethods: browserApiCorsAllowedMethods,
allowedHeaders: browserApiCorsAllowedHeaders,
maxAge: 600,
});
}),
);
export function isLoopbackHostname(hostname: string): boolean {
const normalizedHostname = hostname
+38 -2
View File
@@ -1142,14 +1142,26 @@ const splitHeaderTokens = (value: string | null | undefined) =>
const assertBrowserApiCorsResponseHeaders = (
headers: Readonly<Record<string, string | undefined>>,
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<Record<string, string | undefined>>,
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();
+7 -9
View File
@@ -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 = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
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.")),
);
});
+15 -2
View File
@@ -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<string | null>) | null = null;
export async function readManagedRelayClerkToken(): Promise<string | null> {
@@ -9,14 +12,24 @@ export async function readManagedRelayClerkToken(): Promise<string | null> {
}
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;
}
+83
View File
@@ -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<ReadonlyArray<RelayClientEnvironmentRecord>>([]),
).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:web:environments:null"));
const EMPTY_DEVICES_ATOM = Atom.make(
AsyncResult.success<ReadonlyArray<RelayClientDeviceRecord>>([]),
).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);
}
}
@@ -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<EnvironmentCloudLinkStateResult | null>(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,
};
}
@@ -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) => (
<div key={row} className="border-t border-border/60 px-4 py-3.5 first:border-t-0 sm:px-5">
<div className="space-y-2">
<Skeleton className="h-4 w-32 rounded-full" />
<Skeleton className="h-3 w-44 rounded-full" />
<Skeleton className="h-3 w-56 rounded-full" />
</div>
</div>
));
}
function EmptyNotificationDevices() {
return (
<Empty className="min-h-52">
<EmptyMedia variant="icon">
<SmartphoneIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>No notification devices</EmptyTitle>
<EmptyDescription>
Sign in on the mobile app to register a device for account-level notifications.
</EmptyDescription>
</EmptyHeader>
</Empty>
);
}
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<CloudLinkState | null>(null);
const [devices, setDevices] = useState<ReadonlyArray<RelayClientDeviceRecord>>([]);
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={
<Switch
aria-label="Publish agent activity"
checked={primaryLinkState?.publishAgentActivity ?? false}
disabled={!primaryLinkState?.linked || !canManageRelay || isUpdatingPreference}
checked={primaryLinkState.data?.publishAgentActivity ?? false}
disabled={!primaryLinkState.data?.linked || !canManageRelay || isUpdatingPreference}
onCheckedChange={(enabled) => void updatePublishAgentActivity(enabled)}
/>
}
@@ -209,36 +199,47 @@ function CloudSettingsPanelInner() {
<SettingsSection
title="Notification devices"
headerAction={
<Button
size="xs"
variant="ghost"
disabled={isLoadingDevices}
onClick={() => void refreshDevices()}
>
{isLoadingDevices ? "Refreshing..." : "Refresh"}
</Button>
<Tooltip>
<TooltipTrigger
render={
<Button
size="icon-xs"
variant="ghost"
className="size-5 rounded-sm p-0 text-muted-foreground hover:text-foreground"
disabled={devicesState.isPending}
onClick={devicesState.refresh}
aria-label="Refresh notification devices"
>
<RefreshCwIcon
className={cn("size-3", devicesState.isPending && "animate-spin")}
/>
</Button>
}
/>
<TooltipPopup side="top">Refresh notification devices</TooltipPopup>
</Tooltip>
}
>
{devices.map((device) => (
<SettingsRow
key={device.deviceId}
title={device.label}
description={`iOS ${device.iosMajorVersion}${device.appVersion ? ` · T3 Code ${device.appVersion}` : ""}`}
status={
device.notifications.enabled
? device.liveActivities.enabled
? "Notifications and Live Activities enabled"
: "Notifications enabled · Live Activities disabled"
: "Notifications disabled on device"
}
/>
))}
{!isLoadingDevices && devices.length === 0 ? (
<SettingsRow
title="No notification devices"
description="Sign in on the mobile app to register a device for account-level notifications."
/>
) : null}
{devicesState.data === null ? (
<NotificationDevicesSkeleton />
) : devices.length > 0 ? (
devices.map((device) => (
<SettingsRow
key={device.deviceId}
title={device.label}
description={`iOS ${device.iosMajorVersion}${device.appVersion ? ` · T3 Code ${device.appVersion}` : ""}`}
status={
device.notifications.enabled
? device.liveActivities.enabled
? "Notifications and Live Activities enabled"
: "Notifications enabled · Live Activities disabled"
: "Notifications disabled on device"
}
/>
))
) : (
<EmptyNotificationDevices />
)}
</SettingsSection>
</SettingsPageContainer>
);
@@ -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 = (
<Switch
aria-label="Enable T3 Cloud"
checked={checked}
disabled={disabled}
{...(onCheckedChange ? { onCheckedChange } : {})}
/>
);
return disabledReason ? (
<Tooltip>
<TooltipTrigger render={<span className="inline-flex">{control}</span>} />
<TooltipPopup side="top">{disabledReason}</TooltipPopup>
</Tooltip>
) : (
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<string | null>(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<string | null>(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 (
<SettingsRow
title="T3 Cloud"
description="Make this environment available through your T3 Cloud account."
status={error ?? (linked ? "Linked" : "Not linked")}
status={operationError ?? primaryCloudLinkState.error}
control={
<Switch
aria-label="Enable T3 Cloud"
checked={linked}
disabled={!canManageRelay || !isSignedIn || isLoading}
<CloudLinkSwitch
checked={primaryCloudLinkState.data?.linked ?? false}
disabled={!canManageRelay || !isSignedIn || primaryCloudLinkState.isPending || isUpdating}
disabledReason={disabledReason}
onCheckedChange={(enabled) => void updateLink(enabled)}
/>
}
@@ -1683,47 +1705,62 @@ function CloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean })
<SettingsRow
title="T3 Cloud"
description="Make this environment available through your T3 Cloud account."
status="Cloud is not configured in this build."
control={<Switch aria-label="Enable T3 Cloud" checked={false} disabled />}
control={
<CloudLinkSwitch
checked={false}
disabled
disabledReason="T3 Cloud is not configured in this build."
/>
}
/>
);
}
function EmptyRemoteEnvironments() {
return (
<Empty className="min-h-52">
<EmptyMedia variant="icon">
<ChevronsLeftRightEllipsisIcon />
</EmptyMedia>
<EmptyHeader>
<EmptyTitle>No saved remote environments</EmptyTitle>
<EmptyDescription>
Click &ldquo;Add environment&rdquo; to pair another environment, or connect one from T3
Cloud.
</EmptyDescription>
</EmptyHeader>
</Empty>
);
}
function RemoteEnvironmentRowsSkeleton() {
return (
<div className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0 flex-1 space-y-2">
<Skeleton className="h-4 w-32 rounded-full" />
<Skeleton className="h-3 w-20 rounded-full" />
</div>
<Skeleton className="h-7 w-16 rounded-md" />
</div>
</div>
);
}
function ConfiguredCloudRemoteEnvironmentRows({
primaryEnvironmentId,
savedEnvironmentIds,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
}) {
const { getToken, isSignedIn } = useAuth();
const [environments, setEnvironments] = useState<ReadonlyArray<RelayClientEnvironmentRecord>>([]);
const { getToken } = useAuth();
const environmentsState = useManagedRelayEnvironments();
const [connectingEnvironmentId, setConnectingEnvironmentId] = useState<EnvironmentId | null>(
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) => (
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0">
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName="bg-muted-foreground/35"
tooltipText="Available through T3 Cloud"
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
</div>
<p className="mt-1 truncate text-xs text-muted-foreground">T3 Cloud</p>
const connectableEnvironments = (environmentsState.data ?? []).filter(
(environment) =>
environment.environmentId !== primaryEnvironmentId &&
!savedIds.has(environment.environmentId),
);
if (savedEnvironmentIds.length === 0 && environmentsState.data === null) {
return <RemoteEnvironmentRowsSkeleton />;
}
if (savedEnvironmentIds.length === 0 && connectableEnvironments.length === 0) {
return <EmptyRemoteEnvironments />;
}
return connectableEnvironments.map((environment) => (
<div key={environment.environmentId} className={ITEM_ROW_CLASSNAME}>
<div className={ITEM_ROW_INNER_CLASSNAME}>
<div className="min-w-0">
<div className="flex items-center gap-2">
<ConnectionStatusDot
dotClassName="bg-muted-foreground/35"
tooltipText="Available through T3 Cloud"
/>
<p className="truncate text-sm font-medium">{environment.label}</p>
</div>
<Button
size="sm"
disabled={connectingEnvironmentId !== null}
onClick={() => void connectEnvironment(environment)}
>
{connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}
</Button>
<p className="mt-1 truncate text-xs text-muted-foreground">T3 Cloud</p>
</div>
<Button
size="sm"
disabled={connectingEnvironmentId !== null}
onClick={() => void connectEnvironment(environment)}
>
{connectingEnvironmentId === environment.environmentId ? "Connecting…" : "Connect"}
</Button>
</div>
));
</div>
));
}
function CloudRemoteEnvironmentRows({
primaryEnvironmentId,
savedEnvironmentIds,
}: {
readonly primaryEnvironmentId: EnvironmentId | null;
readonly savedEnvironmentIds: ReadonlyArray<EnvironmentId>;
}) {
return hasCloudConfig() ? (
<ConfiguredCloudRemoteEnvironmentRows savedEnvironmentIds={savedEnvironmentIds} />
<ConfiguredCloudRemoteEnvironmentRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironmentIds={savedEnvironmentIds}
/>
) : savedEnvironmentIds.length === 0 ? (
<EmptyRemoteEnvironments />
) : 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() {
<SettingsPageContainer>
{canManageLocalBackend ? (
<>
<SettingsSection title="Manage local backend">
<SettingsSection title="This environment">
{primaryVersionMismatch ? (
<SettingsRow
title="Version drift"
@@ -3017,7 +3074,7 @@ export function ConnectionsSettings() {
</Dialog>
</>
) : (
<SettingsSection title="Local backend access">
<SettingsSection title="This environment">
<SettingsRow
title="Administrative access"
description="Pairing links and client-session management require the access:write scope for this backend."
@@ -3102,16 +3159,10 @@ export function ConnectionsSettings() {
onRemove={handleRemoveSavedBackend}
/>
))}
<CloudRemoteEnvironmentRows savedEnvironmentIds={savedEnvironmentIds} />
{savedEnvironmentIds.length === 0 ? (
<div className={ITEM_ROW_CLASSNAME}>
<p className="text-xs text-muted-foreground">
No saved remote environments yet. Click &ldquo;Add environment&rdquo; to pair another
environment.
</p>
</div>
) : null}
<CloudRemoteEnvironmentRows
primaryEnvironmentId={primaryEnvironmentId}
savedEnvironmentIds={savedEnvironmentIds}
/>
</SettingsSection>
</SettingsPageContainer>
);
@@ -574,7 +574,9 @@ describe("GeneralSettingsPanel observability", () => {
</AppAtomRegistryProvider>,
);
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(
@@ -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 = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(Effect.provideService(FetchHttpClient.RequestInit, primaryEnvironmentRequestInit));
+2 -1
View File
@@ -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),
),
),
),
-2
View File
@@ -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(),
},
@@ -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");
@@ -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,
@@ -0,0 +1 @@
ALTER TABLE "relay_mobile_devices" ADD COLUMN "label" text DEFAULT 'iOS device' NOT NULL;
+1 -1
View File
@@ -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* () {
+1
View File
@@ -27,3 +27,4 @@ export * from "./archivedThreadsState.ts";
export * from "./checkpointDiffState.ts";
export * from "./remote.ts";
export * from "./managedRelay.ts";
export * from "./managedRelayState.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<ManagedRelayClientShape>) {
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.",
);
});
});
});
@@ -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<string | null, ManagedRelaySessionError>;
}
export interface ManagedRelaySnapshotState<A> {
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<ManagedRelaySession | null>(null).pipe(
Atom.keepAlive,
Atom.withLabel("managed-relay:session"),
);
export function createManagedRelaySession(input: {
readonly accountId: string;
readonly readClerkToken: () => Promise<string | null>;
}): 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<string, ManagedRelaySessionError> {
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<RelayEnvironmentStatusResponse, ManagedRelaySnapshotError> {
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<A>(
result: AsyncResult.AsyncResult<A, unknown>,
): ManagedRelaySnapshotState<A> {
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<ManagedRelayClient>,
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)));
},
};
}
+356
View File
@@ -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<any, any, ResourceLike, any>
-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<A, Req = never> = [Extract<A, object>] 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<any> =>
value &&
(typeof value === "object" || typeof value === "function") &&
@@ -145,7 +147,7 @@ export type ArrayExpr<A extends any[], Req = any> = Output<A, Req> & {
export const isResourceExpr = <Value = any, Req = any>(
node: Expr<Value, Req> | any,
-): node is ResourceExpr<Value, Req> => node?.kind === "ResourceExpr";
+): node is ResourceExpr<Value, Req> => exprKind(node) === "ResourceExpr";
export class ResourceExpr<Value, Req = never> extends BaseExpr<Value, Req> {
readonly kind = "ResourceExpr";
@@ -163,7 +165,7 @@ export class ResourceExpr<Value, Req = never> extends BaseExpr<Value, Req> {
export const isPropExpr = <A = any, Prop extends keyof A = keyof A, Req = any>(
node: any,
-): node is PropExpr<A, Prop, Req> => node?.kind === "PropExpr";
+): node is PropExpr<A, Prop, Req> => exprKind(node) === "PropExpr";
export class PropExpr<
A = any,
@@ -186,7 +188,7 @@ export class PropExpr<
export const literal = <A>(value: A) => new LiteralExpr(value);
export const isLiteralExpr = <A = any>(node: any): node is LiteralExpr<A> =>
- node?.kind === "LiteralExpr";
+ exprKind(node) === "LiteralExpr";
export class LiteralExpr<A> extends BaseExpr<A, never> {
readonly kind = "LiteralExpr";
@@ -217,7 +219,7 @@ export const map: {
//Output.ApplyExpr<any, any, ResourceLike, any>
export const isApplyExpr = <In = any, Out = any, Req = any>(
node: Output<Out, Req>,
-): node is ApplyExpr<In, Out, Req> => node?.kind === "ApplyExpr";
+): node is ApplyExpr<In, Out, Req> => exprKind(node) === "ApplyExpr";
export class ApplyExpr<A, B, Req = never> extends BaseExpr<B, Req> {
readonly kind = "ApplyExpr";
@@ -259,7 +261,7 @@ export const flatMap: {
export const isFlatMapExpr = <In = any, Out = any, Req = any, Req2 = any>(
node: any,
-): node is FlatMapExpr<In, Out, Req, Req2> => node?.kind === "FlatMapExpr";
+): node is FlatMapExpr<In, Out, Req, Req2> => exprKind(node) === "FlatMapExpr";
export class FlatMapExpr<A, B, Req = never, Req2 = never> extends BaseExpr<
B,
@@ -280,7 +282,7 @@ export class FlatMapExpr<A, B, Req = never, Req2 = never> extends BaseExpr<
export const isEffectExpr = <In = any, Out = any, Req = any, Req2 = any>(
node: any,
-): node is EffectExpr<In, Out, Req, Req2> => node?.kind === "EffectExpr";
+): node is EffectExpr<In, Out, Req, Req2> => exprKind(node) === "EffectExpr";
export class EffectExpr<A, B, Req = never, Req2 = never> extends BaseExpr<
B,
@@ -301,7 +303,7 @@ export class EffectExpr<A, B, Req = never, Req2 = never> extends BaseExpr<
export const isNamedExpr = <A = any, Req = any>(
node: any,
-): node is NamedExpr<A, Req> => node?.kind === "NamedExpr";
+): node is NamedExpr<A, Req> => exprKind(node) === "NamedExpr";
/**
* Wraps another `Expr` and overrides its `toString()` / inspect output.
@@ -352,7 +354,7 @@ type Tuple<
export const isAllExpr = <Outs extends Expr[] = Expr[]>(
node: any,
-): node is AllExpr<Outs> => node?.kind === "AllExpr";
+): node is AllExpr<Outs> => exprKind(node) === "AllExpr";
export class AllExpr<Outs extends Expr[]> extends BaseExpr<Outs> {
readonly kind = "AllExpr";
@@ -366,7 +368,7 @@ export class AllExpr<Outs extends Expr[]> extends BaseExpr<Outs> {
}
export const isRefExpr = <A = any>(node: any): node is RefExpr<A> =>
- node?.kind === "RefExpr";
+ exprKind(node) === "RefExpr";
export class RefExpr<A> extends BaseExpr<A, never> {
readonly kind = "RefExpr";
@@ -384,7 +386,7 @@ export class RefExpr<A> extends BaseExpr<A, never> {
}
export const isStackRefExpr = <A = any>(node: any): node is StackRefExpr<A> =>
- node?.kind === "StackRefExpr";
+ exprKind(node) === "StackRefExpr";
/**
* A reference to the persisted output of a Stack at `(stack, stage)`.
+1
View File
@@ -67,5 +67,6 @@ packageExtensions:
patchedDependencies:
"@expo/[email protected]": patches/@expo%[email protected]
"@pierre/[email protected]": patches/@pierre%[email protected]
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]
[email protected]: patches/[email protected]