TypeScript
fix(web): show saved service access with Local environment off (#26464)
shivamd520d5bb850d
diff --git a/apps/web/src/cloud/cloudLinkState.ts b/apps/web/src/cloud/cloudLinkState.tsnew file mode 100644index 00000000000..2bf0ae83f57--- /dev/null+++ b/apps/web/src/cloud/cloudLinkState.ts@@ -0,0 +1,71 @@+import { useAtomValue } from "@effect/atom-react";+import {+ AuthRelayReadScope,+ type EnvironmentCloudLinkStateResult,+ type EnvironmentId,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import { AsyncResult, Atom } from "effect/reactivity";++import { connectionAtomRuntime } from "../connection/runtime";+import { usePrimaryEnvironmentId } from "../state/environments";+import { appAtomRegistry } from "../rpc/atomRegistry";+import { readEnvironmentScope, useEnvironmentScope } from "../state/session";+import { readCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";+import { hasCloudPublicConfig } from "./publicConfig";++const cloudLinkStateAtom = Atom.family((environmentId: EnvironmentId) =>+ connectionAtomRuntime+ .atom(readCloudLinkState({ target: { environmentId } }))+ .pipe(+ Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),+ Atom.setIdleTTL(5 * 60_000),+ Atom.withLabel(`cloud-link:${environmentId}`),+ ),+);++const EMPTY_CLOUD_LINK_STATE_ATOM = Atom.make(+ AsyncResult.success<EnvironmentCloudLinkStateResult | null>(null),+).pipe(Atom.keepAlive, Atom.withLabel("cloud-link:null"));++function refreshCloudLinkState(target: CloudLinkTarget | null): void {+ if (target && readEnvironmentScope(target.environmentId, AuthRelayReadScope)) {+ appAtomRegistry.refresh(cloudLinkStateAtom(target.environmentId));+ }+}++export function readCachedCloudLinkState(target: CloudLinkTarget) {+ if (!readEnvironmentScope(target.environmentId, AuthRelayReadScope)) return null;+ const result = appAtomRegistry.get(cloudLinkStateAtom(target.environmentId));+ return result._tag === "Success" ? result.value : null;+}++export function useCloudLinkState(environmentId: EnvironmentId | null) {+ const canReadRelay = useEnvironmentScope(environmentId, AuthRelayReadScope);+ const target: CloudLinkTarget | null = environmentId === null ? null : { environmentId };+ const atom =+ environmentId !== null && hasCloudPublicConfig() && canReadRelay+ ? cloudLinkStateAtom(environmentId)+ : EMPTY_CLOUD_LINK_STATE_ATOM;+ const result = useAtomValue(atom);+ const refresh = () => {+ refreshCloudLinkState(target);+ };+ 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 Connect link state.";+ }++ return {+ data: result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null),+ error,+ isPending: result.waiting,+ refresh,+ target,+ };+}++export function usePrimaryCloudLinkState() {+ return useCloudLinkState(usePrimaryEnvironmentId());+}diff --git a/apps/web/src/cloud/linkEnvironment.test.ts b/apps/web/src/cloud/linkEnvironment.test.tsindex 698712914fd..7a09f928dbe 100644--- a/apps/web/src/cloud/linkEnvironment.test.ts+++ b/apps/web/src/cloud/linkEnvironment.test.ts@@ -16,6 +16,7 @@ import { afterEach, beforeEach, vi } from "vite-plus/test";import {AVAILABLE_CONNECTION_STATE,type PreparedConnection,+ BearerConnectionTarget,PrimaryConnectionTarget,EnvironmentSupervisor,} from "@t3tools/client-runtime/connection";@@ -25,15 +26,22 @@ import { ManagedRelay } from "@t3tools/client-runtime/relay";import { layerRemoteHttpClient } from "@t3tools/client-runtime/rpc";import { __resetDesktopPrimaryAuthForTests } from "../environments/primary/desktopAuth";-import { readPrimaryCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";+import { readCloudLinkState } from "./linkEnvironment";-const TARGET: CloudLinkTarget = {+const TARGET = {environmentId: "environment-1",label: "Desktop",httpBaseUrl: "http://127.0.0.1:3000",wsBaseUrl: "ws://127.0.0.1:3000",};+const SAVED_SERVICE_TARGET = {+ environmentId: "saved-service",+ label: "Service",+ httpBaseUrl: "http://127.0.0.1:3773",+ wsBaseUrl: "ws://127.0.0.1:3773",+};+const relayClientInstallDialog = vi.hoisted(() => ({requestConfirmation: vi.fn(),reportProgress: vi.fn(),@@ -88,26 +96,73 @@ function layerRegistry(options?: {inboundFrames: Effect.succeed(0),closed: Effect.never,};- const target = new PrimaryConnectionTarget({- environmentId: EnvironmentId.make(TARGET.environmentId),- label: TARGET.label,- httpBaseUrl: TARGET.httpBaseUrl,- wsBaseUrl: TARGET.wsBaseUrl,+ const makeSupervisor = Effect.fn(function* (prepared: Option.Option<PreparedConnection>) {+ return EnvironmentSupervisor.EnvironmentSupervisor.of({+ target: new PrimaryConnectionTarget({+ environmentId: EnvironmentId.make(TARGET.environmentId),+ label: TARGET.label,+ httpBaseUrl: TARGET.httpBaseUrl,+ wsBaseUrl: TARGET.wsBaseUrl,+ }),+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),+ session: yield* SubscriptionRef.make(Option.some(session)),+ prepared: yield* SubscriptionRef.make(prepared),+ connect: Effect.void,+ disconnect: Effect.void,+ retryNow: Effect.void,+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);});- const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({- target,- state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),- session: yield* SubscriptionRef.make(Option.some(session)),- prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),- connect: Effect.void,- disconnect: Effect.void,- retryNow: Effect.void,- } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);+ const supervisors = new Map([+ [+ TARGET.environmentId,+ yield* makeSupervisor(+ Option.some({+ environmentId: EnvironmentId.make(TARGET.environmentId),+ label: TARGET.label,+ httpBaseUrl: TARGET.httpBaseUrl,+ socketUrl: `${TARGET.wsBaseUrl}/ws`,+ httpAuthorization: { _tag: "Bearer", token: "desktop-bearer-token" },+ target: new PrimaryConnectionTarget({+ environmentId: EnvironmentId.make(TARGET.environmentId),+ label: TARGET.label,+ httpBaseUrl: TARGET.httpBaseUrl,+ wsBaseUrl: TARGET.wsBaseUrl,+ }),+ }),+ ),+ ],+ [+ SAVED_SERVICE_TARGET.environmentId,+ yield* makeSupervisor(+ Option.some({+ environmentId: EnvironmentId.make(SAVED_SERVICE_TARGET.environmentId),+ label: SAVED_SERVICE_TARGET.label,+ httpBaseUrl: SAVED_SERVICE_TARGET.httpBaseUrl,+ socketUrl: `${SAVED_SERVICE_TARGET.wsBaseUrl}/ws`,+ httpAuthorization: { _tag: "Bearer", token: "saved-service-token" },+ target: new BearerConnectionTarget({+ environmentId: EnvironmentId.make(SAVED_SERVICE_TARGET.environmentId),+ label: SAVED_SERVICE_TARGET.label,+ connectionId: "saved-service-connection",+ }),+ }),+ ),+ ],+ ]);+ const supervisorFor = (environmentId: EnvironmentId) => supervisors.get(environmentId)!;const registry = {- run: <A, E, R>(_environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>- Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),- runStream: <A, E, R>(_environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>- Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor),+ run: <A, E, R>(environmentId: EnvironmentId, effect: Effect.Effect<A, E, R>) =>+ Effect.provideService(+ effect,+ EnvironmentSupervisor.EnvironmentSupervisor,+ supervisorFor(environmentId),+ ),+ runStream: <A, E, R>(environmentId: EnvironmentId, stream: Stream.Stream<A, E, R>) =>+ Stream.provideService(+ stream,+ EnvironmentSupervisor.EnvironmentSupervisor,+ supervisorFor(environmentId),+ ),} as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"];return EnvironmentRegistry.EnvironmentRegistry.of(registry);}),@@ -145,9 +200,9 @@ afterEach(() => {});describe("web cloud link environment client", () => {- it.effect("uses desktop bearer auth for primary cloud link state", () =>+ it.effect("reads link state from the chosen environment with its own credentials", () =>Effect.gen(function* () {- const fetchMock = vi.fn().mockResolvedValue(+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>Response.json({linked: true,cloudUserId: "user-1",@@ -165,11 +220,23 @@ describe("web cloud link environment client", () => {} as unknown as DesktopBridge,});- yield* withServices(readPrimaryCloudLinkState({ target: TARGET }));+ for (const [target, token] of [+ [TARGET, "desktop-bearer-token"],+ [SAVED_SERVICE_TARGET, "saved-service-token"],+ ] as const) {+ fetchMock.mockClear();+ yield* withServices(+ readCloudLinkState({+ target: { environmentId: EnvironmentId.make(target.environmentId) },+ }),+ );- const request = new Request(fetchMock.mock.calls[0]?.[0], fetchMock.mock.calls[0]?.[1]);- expect(request.credentials).not.toBe("include");- expect(request.headers.get("authorization")).toBe("Bearer desktop-bearer-token");+ const [input, init] = fetchMock.mock.calls[0]!;+ const request = new Request(input, init);+ expect(new URL(request.url).origin).toBe(target.httpBaseUrl);+ expect(request.credentials).not.toBe("include");+ expect(request.headers.get("authorization")).toBe(`Bearer ${token}`);+ }}),);});diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.tsindex e6e42dc9218..70fd2de055f 100644--- a/apps/web/src/cloud/linkEnvironment.ts+++ b/apps/web/src/cloud/linkEnvironment.ts@@ -3,7 +3,8 @@ import * as Effect from "effect/Effect";import * as Option from "effect/Option";import * as Schema from "effect/Schema";import * as Stream from "effect/Stream";-import { HttpClient } from "effect/http";+import * as SubscriptionRef from "effect/SubscriptionRef";+import type { HttpClient } from "effect/http";import {EnvironmentCloudEndpointUnavailableError,type EnvironmentCloudLinkStateResult,@@ -19,12 +20,11 @@ import {type RelayEnvironmentLinkResponse,type RelayManagedEndpointProviderKind,} from "@t3tools/contracts/relay";-import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";+import { EnvironmentRegistry, EnvironmentSupervisor } from "@t3tools/client-runtime/connection";import { request, runStream } from "@t3tools/client-runtime/rpc";-import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";import { ManagedRelay, relayRequestFailureDetail } from "@t3tools/client-runtime/relay";+import { executeConnectedEnvironmentHttpRequest } from "@t3tools/client-runtime/state/environmentHttpAuth";-import * as PrimaryEnvironmentHttpLayer from "../environments/primary/httpLayer";import { resolveCloudPublicConfig } from "./publicConfig";import {finishRelayClientInstall,@@ -176,62 +176,125 @@ function ensureLinkedEnvironmentMatches(input: {}export interface CloudLinkTarget {- readonly environmentId: string;- readonly label: string;- readonly httpBaseUrl: string;- readonly wsBaseUrl: string;+ readonly environmentId: EnvironmentId;}export type CloudLinkState = EnvironmentCloudLinkStateResult;-export const readPrimaryCloudLinkState: (input: {+// Linking can install the relay client and start a managed tunnel before it answers.+const CLOUD_LINK_REQUEST_TIMEOUT_MS = 60_000;++type ConnectedEnvironmentHttpRequest<A, E, R> = Parameters<+ typeof executeConnectedEnvironmentHttpRequest<"connect", A, E, R>+>[0];++/** Runs on the target environment with this client's own credentials for it. */+const connectRequest = <A, E, R>(+ target: CloudLinkTarget,+ input: Omit<ConnectedEnvironmentHttpRequest<A, E, R>, "group" | "timeoutMs">,+ failureMessage: string,+) =>+ Effect.flatMap(EnvironmentRegistry.EnvironmentRegistry, (registry) =>+ registry.run(+ target.environmentId,+ executeConnectedEnvironmentHttpRequest({+ ...input,+ group: "connect",+ timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,+ }),+ ),+ ).pipe(Effect.mapError(environmentApiError(failureMessage)));++const preparedEndpoint = (target: CloudLinkTarget) =>+ Effect.flatMap(EnvironmentRegistry.EnvironmentRegistry, (registry) =>+ registry.run(+ target.environmentId,+ Effect.flatMap(EnvironmentSupervisor.EnvironmentSupervisor, (supervisor) =>+ SubscriptionRef.get(supervisor.prepared),+ ),+ ),+ ).pipe(+ Effect.mapError(environmentApiError("Could not reach the environment.")),+ Effect.flatMap(+ Option.match({+ onNone: () =>+ Effect.fail(+ new CloudEnvironmentLinkError({ message: "The environment is not connected." }),+ ),+ onSome: ({ httpBaseUrl, target }) =>+ Effect.succeed({+ httpBaseUrl,+ wsBaseUrl:+ target._tag === "PrimaryConnectionTarget"+ ? target.wsBaseUrl+ : httpBaseUrl.replace(/^http/, "ws"),+ }),+ }),+ ),+ );++type CloudLinkServices = EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient;++export const readCloudLinkState: (input: {readonly target: CloudLinkTarget;-}) => Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> =- Effect.fn("linkEnvironment.readPrimaryCloudLinkState")(function* (input: {+}) => Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, CloudLinkServices> =+ Effect.fn("linkEnvironment.readCloudLinkState")(function* (input: {readonly target: CloudLinkTarget;}) {- const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- return yield* client.connect- .linkState({ headers: {} })- .pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));- }, Effect.provide(PrimaryEnvironmentHttpLayer.layer));+ return yield* connectRequest(+ input.target,+ {+ method: "GET",+ url: (urls) => urls.linkState(),+ request: ({ client, headers }) => client.linkState({ headers }),+ },+ "Could not read environment cloud link state.",+ );+ });-export const updatePrimaryCloudPreferences: (input: {+export const updateCloudPreferences: (input: {readonly target: CloudLinkTarget;readonly publishAgentActivity: boolean;readonly holdWebhooksWhileOffline?: boolean;-}) => Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> = Effect.fn(- "linkEnvironment.updatePrimaryCloudPreferences",+}) => Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, CloudLinkServices> = Effect.fn(+ "linkEnvironment.updateCloudPreferences",)(function* (input: {readonly target: CloudLinkTarget;readonly publishAgentActivity: boolean;readonly holdWebhooksWhileOffline?: boolean;}) {- const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- const { target: _target, ...payload } = input;- return yield* client.connect- .preferences({- headers: {},- payload,- })- .pipe(Effect.mapError(environmentApiError("Could not update environment cloud preferences.")));-}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));+ const { target, ...payload } = input;+ return yield* connectRequest(+ target,+ {+ method: "POST",+ url: (urls) => urls.preferences(),+ request: ({ client, headers }) => client.preferences({ headers, payload }),+ },+ "Could not update environment cloud preferences.",+ );+});-export const unlinkPrimaryEnvironmentFromCloud: (input: {+export const unlinkEnvironmentFromCloud: (input: {readonly target: CloudLinkTarget;readonly clerkToken: string | null;}) => Effect.Effect<void,CloudEnvironmentLinkError,- HttpClient.HttpClient | ManagedRelay.ManagedRelayClient-> = Effect.fn("linkEnvironment.unlinkPrimaryEnvironmentFromCloud")(function* (input: {+ CloudLinkServices | ManagedRelay.ManagedRelayClient+> = Effect.fn("linkEnvironment.unlinkEnvironmentFromCloud")(function* (input: {readonly target: CloudLinkTarget;readonly clerkToken: string | null;}) {- const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);- yield* client.connect- .unlink({ headers: {} })- .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));+ yield* connectRequest(+ input.target,+ {+ method: "POST",+ url: (urls) => urls.unlink(),+ request: ({ client, headers }) => client.unlink({ headers }),+ },+ "Could not unlink the environment from cloud.",+ );const configuredRelayUrl = relayUrl();if (configuredRelayUrl && input.clerkToken) {@@ -239,7 +302,7 @@ export const unlinkPrimaryEnvironmentFromCloud: (input: {yield* relayClient.unlinkEnvironment({clerkToken: input.clerkToken,- environmentId: EnvironmentId.make(input.target.environmentId),+ environmentId: input.target.environmentId,}).pipe(Effect.catch((cause) =>@@ -249,21 +312,21 @@ export const unlinkPrimaryEnvironmentFromCloud: (input: {),);}-}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));+});export type CloudLinkMode = "managed" | "publish_only";const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;-export const linkPrimaryEnvironmentToCloud: (input: {+export const linkEnvironmentToCloud: (input: {readonly target: CloudLinkTarget;readonly clerkToken: string;readonly mode?: CloudLinkMode;}) => Effect.Effect<void,CloudEnvironmentLinkError,- EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient | ManagedRelay.ManagedRelayClient-> = Effect.fn("linkEnvironment.linkPrimaryEnvironmentToCloud")(function* (input: {+ CloudLinkServices | ManagedRelay.ManagedRelayClient+> = Effect.fn("linkEnvironment.linkEnvironmentToCloud")(function* (input: {readonly target: CloudLinkTarget;readonly clerkToken: string;readonly mode?: CloudLinkMode;@@ -279,9 +342,10 @@ export const linkPrimaryEnvironmentToCloud: (input: {? MANAGED_ENDPOINT_PROVIDER_KIND: PUBLISH_ONLY_PROVIDER_KIND;const relayClient = yield* ManagedRelay.ManagedRelayClient;- const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);+ // The environment only signs a proof for the loopback origin this request reaches it on.+ const endpoint = yield* preparedEndpoint(input.target);if (managedTunnelsEnabled) {- yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));+ yield* ensureRelayClientAvailable(input.target.environmentId);}const challenge = yield* relayClient@@ -300,21 +364,24 @@ export const linkPrimaryEnvironmentToCloud: (input: {),),);- const proof = yield* environmentClient.connect- .linkProof({- headers: {},- payload: {- challenge: challenge.challenge,- relayIssuer: configuredRelayUrl,- endpoint: {- httpBaseUrl: input.target.httpBaseUrl,- wsBaseUrl: input.target.wsBaseUrl,- providerKind,- },- origin: endpointOrigin(input.target.httpBaseUrl),- },- })- .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));+ const proof = yield* connectRequest(+ input.target,+ {+ method: "POST",+ url: (urls) => urls.linkProof(),+ request: ({ client, headers }) =>+ client.linkProof({+ headers,+ payload: {+ challenge: challenge.challenge,+ relayIssuer: configuredRelayUrl,+ endpoint: { ...endpoint, providerKind },+ origin: endpointOrigin(endpoint.httpBaseUrl),+ },+ }),+ },+ "Could not obtain environment link proof.",+ );const link = yield* relayClient.linkEnvironment({clerkToken: input.clerkToken,@@ -336,17 +403,24 @@ export const linkPrimaryEnvironmentToCloud: (input: {link,});- yield* environmentClient.connect- .relayConfig({- headers: {},- payload: {- relayUrl: configuredRelayUrl,- relayIssuer: link.relayIssuer,- cloudUserId: link.cloudUserId,- environmentCredential: link.environmentCredential,- cloudMintPublicKey: link.cloudMintPublicKey,- endpointRuntime: link.endpointRuntime,- },- })- .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));-}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));+ yield* connectRequest(+ input.target,+ {+ method: "POST",+ url: (urls) => urls.relayConfig(),+ request: ({ client, headers }) =>+ client.relayConfig({+ headers,+ payload: {+ relayUrl: configuredRelayUrl,+ relayIssuer: link.relayIssuer,+ cloudUserId: link.cloudUserId,+ environmentCredential: link.environmentCredential,+ cloudMintPublicKey: link.cloudMintPublicKey,+ endpointRuntime: link.endpointRuntime,+ },+ }),+ },+ "Could not configure environment relay access.",+ );+});diff --git a/apps/web/src/cloud/linkEnvironmentAtoms.ts b/apps/web/src/cloud/linkEnvironmentAtoms.tsindex 4a3541cd3a1..66b7f884e9a 100644--- a/apps/web/src/cloud/linkEnvironmentAtoms.ts+++ b/apps/web/src/cloud/linkEnvironmentAtoms.ts@@ -5,11 +5,11 @@ import {import { connectionAtomRuntime } from "../connection/runtime";import {- linkPrimaryEnvironmentToCloud,+ linkEnvironmentToCloud,type CloudLinkMode,type CloudLinkTarget,- unlinkPrimaryEnvironmentFromCloud,- updatePrimaryCloudPreferences,+ unlinkEnvironmentFromCloud,+ updateCloudPreferences,} from "./linkEnvironment";const cloudLinkScheduler = createAtomCommandScheduler();@@ -18,32 +18,32 @@ const cloudLinkConcurrency = {key: (input: { readonly target: CloudLinkTarget }) => input.target.environmentId,};-export const linkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime, {- label: "web:cloud:link-primary-environment",+export const linkEnvironment = createRuntimeCommand(connectionAtomRuntime, {+ label: "web:cloud:link-environment",scheduler: cloudLinkScheduler,concurrency: cloudLinkConcurrency,execute: (input: {readonly target: CloudLinkTarget;readonly clerkToken: string;readonly mode?: CloudLinkMode;- }) => linkPrimaryEnvironmentToCloud(input),+ }) => linkEnvironmentToCloud(input),});-export const unlinkPrimaryEnvironment = createRuntimeCommand(connectionAtomRuntime, {- label: "web:cloud:unlink-primary-environment",+export const unlinkEnvironment = createRuntimeCommand(connectionAtomRuntime, {+ label: "web:cloud:unlink-environment",scheduler: cloudLinkScheduler,concurrency: cloudLinkConcurrency,execute: (input: { readonly target: CloudLinkTarget; readonly clerkToken: string | null }) =>- unlinkPrimaryEnvironmentFromCloud(input),+ unlinkEnvironmentFromCloud(input),});-export const updatePrimaryEnvironmentPreferences = createRuntimeCommand(connectionAtomRuntime, {- label: "web:cloud:update-primary-environment-preferences",+export const updateEnvironmentPreferences = createRuntimeCommand(connectionAtomRuntime, {+ label: "web:cloud:update-environment-preferences",scheduler: cloudLinkScheduler,concurrency: cloudLinkConcurrency,execute: (input: {readonly target: CloudLinkTarget;readonly publishAgentActivity: boolean;readonly holdWebhooksWhileOffline?: boolean;- }) => updatePrimaryCloudPreferences(input),+ }) => updateCloudPreferences(input),});diff --git a/apps/web/src/cloud/primaryCloudLinkState.ts b/apps/web/src/cloud/primaryCloudLinkState.tsdeleted file mode 100644index 867008fbc3b..00000000000--- a/apps/web/src/cloud/primaryCloudLinkState.ts+++ /dev/null@@ -1,98 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import {- AuthRelayReadScope,- EnvironmentId,- type EnvironmentCloudLinkStateResult,-} 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 { AsyncResult, Atom } from "effect/reactivity";-import { HttpClient } from "effect/http";--import { usePrimaryEnvironment } from "../state/environments";-import { runtime } from "../lib/runtime";-import { appAtomRegistry } from "../rpc/atomRegistry";-import { readEnvironmentScope, useEnvironmentScope } from "../state/session";-import { readPrimaryCloudLinkState, type CloudLinkTarget } from "./linkEnvironment";-import { hasCloudPublicConfig } from "./publicConfig";--const primaryCloudLinkAtomRuntime = Atom.runtime(- Layer.effect(- HttpClient.HttpClient,- runtime.contextEffect.pipe(- Effect.map((context) => Context.get(context, HttpClient.HttpClient)),- ),- ),-);--const primaryCloudLinkStateAtom = Atom.family((key: string) => {- const target = JSON.parse(key) as CloudLinkTarget;- return primaryCloudLinkAtomRuntime- .atom(readPrimaryCloudLinkState({ target }))- .pipe(- Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),- Atom.setIdleTTL(5 * 60_000),- Atom.withLabel(`primary-cloud-link:${target.environmentId}`),- );-});--const EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM = Atom.make(- AsyncResult.success<EnvironmentCloudLinkStateResult | null>(null),-).pipe(Atom.keepAlive, Atom.withLabel("primary-cloud-link:null"));--function targetKey(target: CloudLinkTarget): string {- return JSON.stringify(target);-}--function refreshPrimaryCloudLinkState(target: CloudLinkTarget | null): void {- if (- target &&- readEnvironmentScope(EnvironmentId.make(target.environmentId), AuthRelayReadScope)- ) {- appAtomRegistry.refresh(primaryCloudLinkStateAtom(targetKey(target)));- }-}--export function readCachedPrimaryCloudLinkState(target: CloudLinkTarget) {- if (!readEnvironmentScope(EnvironmentId.make(target.environmentId), AuthRelayReadScope))- return null;- const result = appAtomRegistry.get(primaryCloudLinkStateAtom(targetKey(target)));- return result._tag === "Success" ? result.value : null;-}--export function usePrimaryCloudLinkState() {- const primary = usePrimaryEnvironment();- const canReadRelay = useEnvironmentScope(primary?.environmentId ?? null, AuthRelayReadScope);- const target =- primary?.entry.target._tag === "PrimaryConnectionTarget"- ? {- environmentId: primary.environmentId,- label: primary.label,- httpBaseUrl: primary.entry.target.httpBaseUrl,- wsBaseUrl: primary.entry.target.wsBaseUrl,- }- : null;- const atom =- target && hasCloudPublicConfig() && canReadRelay- ? primaryCloudLinkStateAtom(targetKey(target))- : EMPTY_PRIMARY_CLOUD_LINK_STATE_ATOM;- const result = useAtomValue(atom);- const refresh = () => {- refreshPrimaryCloudLinkState(target);- };- 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 Connect link state.";- }-- return {- data: result._tag === "Failure" ? null : AsyncResult.getOrElse(result, () => null),- error,- isPending: result.waiting,- refresh,- target,- };-}diff --git a/apps/web/src/cloud/useCloudLinkController.browser.test.tsx b/apps/web/src/cloud/useCloudLinkController.browser.test.tsxindex 5884ee5c19d..20e1fc71d29 100644--- a/apps/web/src/cloud/useCloudLinkController.browser.test.tsx+++ b/apps/web/src/cloud/useCloudLinkController.browser.test.tsx@@ -38,7 +38,7 @@ vi.mock(import("@effect/atom-react"), async (original) => ({? []: [[- "primary",+ "service",{ environment: { endpoint: { providerKind: testState.relayProviderKind } } },],],@@ -73,15 +73,15 @@ vi.mock(import("../state/use-atom-command"), async (original) => ({}));vi.mock(import("./linkEnvironmentAtoms"), async (original) => ({...(await original()),- linkPrimaryEnvironment: testState.link as never,- unlinkPrimaryEnvironment: testState.unlink as never,- updatePrimaryEnvironmentPreferences: testState.preferences as never,+ linkEnvironment: testState.link as never,+ unlinkEnvironment: testState.unlink as never,+ updateEnvironmentPreferences: testState.preferences as never,}));-vi.mock(import("./primaryCloudLinkState"), async (original) => ({+vi.mock(import("./cloudLinkState"), async (original) => ({...(await original()),- readCachedPrimaryCloudLinkState: () => testState.snapshot,- usePrimaryCloudLinkState: (() => ({- target,+ readCachedCloudLinkState: () => testState.snapshot,+ useCloudLinkState: ((environmentId: EnvironmentId | null) => ({+ target: environmentId === null ? null : { environmentId },data: testState.renderedSnapshot,error: null,isPending: false,@@ -96,12 +96,7 @@ vi.mock(import("./publicConfig"), async (original) => ({import { CloudEnvironmentLinkError } from "./linkEnvironment";import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";-const target = {- environmentId: EnvironmentId.make("primary"),- label: "Primary",- httpBaseUrl: "http://localhost:3773",- wsBaseUrl: "ws://localhost:3773/ws",-};+const target = { environmentId: EnvironmentId.make("service") };const linkedState: EnvironmentCloudLinkStateResult = {linked: true,cloudUserId: "account-1",@@ -114,7 +109,7 @@ const linkedState: EnvironmentCloudLinkStateResult = {type Controller = ReturnType<typeof useCloudLinkController>;function ControllerProbe({ onRender }: { onRender: (controller: Controller) => void }) {- const value = useCloudLinkController();+ const value = useCloudLinkController(target.environmentId);useLayoutEffect(() => {onRender(value);});diff --git a/apps/web/src/cloud/useCloudLinkController.ts b/apps/web/src/cloud/useCloudLinkController.tsindex 1ae60b8c383..9936bf888d9 100644--- a/apps/web/src/cloud/useCloudLinkController.ts+++ b/apps/web/src/cloud/useCloudLinkController.ts@@ -2,10 +2,10 @@ import { useAtomValue } from "@effect/atom-react";import { useAuth } from "@clerk/react";import { findErrorTraceId } from "@t3tools/client-runtime/errors";import {- EnvironmentId,AuthRelayReadScope,AuthRelayWriteScope,type EnvironmentCloudLinkStateResult,+ type EnvironmentId,} from "@t3tools/contracts";import { ManagedRelay } from "@t3tools/client-runtime/relay";import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";@@ -24,11 +24,11 @@ import { useAtomCommand } from "../state/use-atom-command";import { CloudEnvironmentLinkError } from "./linkEnvironment";import { refreshManagedTunnelUsage } from "./managedRelayState";import {- linkPrimaryEnvironment as linkPrimaryEnvironmentAtom,- unlinkPrimaryEnvironment as unlinkPrimaryEnvironmentAtom,- updatePrimaryEnvironmentPreferences as updatePrimaryEnvironmentPreferencesAtom,+ linkEnvironment as linkEnvironmentAtom,+ unlinkEnvironment as unlinkEnvironmentAtom,+ updateEnvironmentPreferences as updateEnvironmentPreferencesAtom,} from "./linkEnvironmentAtoms";-import { readCachedPrimaryCloudLinkState, usePrimaryCloudLinkState } from "./primaryCloudLinkState";+import { readCachedCloudLinkState, useCloudLinkState } from "./cloudLinkState";import { resolveRelayClerkTokenOptions } from "./publicConfig";export interface CloudLinkDesiredState {@@ -62,26 +62,24 @@ function tunnelLimitFromLinkFailure(cause: unknown): number | null {: null;}-export function useCloudLinkController() {+export function useCloudLinkController(environmentId: EnvironmentId | null) {const { getToken, isSignedIn } = useAuth();const refreshRelayEnvironments = useAtomCommand(relayEnvironmentDiscovery.refresh, {reportFailure: false,});- const linkPrimaryEnvironment = useAtomCommand(linkPrimaryEnvironmentAtom, {+ const linkEnvironment = useAtomCommand(linkEnvironmentAtom, {reportFailure: false,});- const unlinkPrimaryEnvironment = useAtomCommand(unlinkPrimaryEnvironmentAtom, {+ const unlinkEnvironment = useAtomCommand(unlinkEnvironmentAtom, {reportFailure: false,});- const updatePrimaryEnvironmentPreferences = useAtomCommand(- updatePrimaryEnvironmentPreferencesAtom,- { reportFailure: false },- );- const primaryCloudLinkState = usePrimaryCloudLinkState();+ const updateEnvironmentPreferences = useAtomCommand(updateEnvironmentPreferencesAtom, {+ reportFailure: false,+ });+ const cloudLinkState = useCloudLinkState(environmentId);const relayEnvironments = useAtomValue(relayEnvironmentDiscovery.stateValueAtom).environments;- const primaryEnvironmentId = primaryCloudLinkState.target?.environmentId;- const relayProviderKind = primaryEnvironmentId- ? relayEnvironments.get(primaryEnvironmentId)?.environment.endpoint.providerKind+ const relayProviderKind = environmentId+ ? relayEnvironments.get(environmentId)?.environment.endpoint.providerKind: undefined;const [operationError, setOperationError] = useState<string | null>(null);const [tunnelLimit, setTunnelLimit] = useState<number | null>(null);@@ -106,24 +104,24 @@ export function useCloudLinkController() {});};- const linkData = primaryCloudLinkState.data;+ const linkData = cloudLinkState.data;const linkRevoked = linkData?.linkRevoked ?? false;const managedTunnelActive = linkData ? isManagedTunnelActive(linkData, relayProviderKind) : false;const managedTunnelOutOfSync =linkData !== null && !managedTunnelActive && isManagedTunnelActive(linkData, undefined);- const publishAgentActivity = primaryCloudLinkState.data?.publishAgentActivity ?? false;- const holdWebhooksWhileOffline = primaryCloudLinkState.data?.holdWebhooksWhileOffline ?? false;- const linked = !linkRevoked && (primaryCloudLinkState.data?.linked ?? false);+ const publishAgentActivity = cloudLinkState.data?.publishAgentActivity ?? false;+ const holdWebhooksWhileOffline = cloudLinkState.data?.holdWebhooksWhileOffline ?? false;+ const linked = !linkRevoked && (cloudLinkState.data?.linked ?? false);const reconcileCloudState = async (desired: CloudLinkDesiredState): Promise<boolean> => {setOperationError(null);setTunnelLimit(null);- const target = primaryCloudLinkState.target;+ const target = cloudLinkState.target;if (!target) {- reportUpdateFailure(new Error("Local environment is not ready yet."));+ reportUpdateFailure(new Error("Choose an environment first."));return false;}- const environmentId = EnvironmentId.make(target.environmentId);+ const environmentId = target.environmentId;const canManageLink = () => {if (!readEnvironmentScope(environmentId, AuthRelayReadScope) ||@@ -137,7 +135,7 @@ export function useCloudLinkController() {return true;};const readLinkState = () => {- const state = readCachedPrimaryCloudLinkState(target);+ const state = readCachedCloudLinkState(target);if (state === null) {reportUpdateFailure(new Error("Wait until the current T3 Connect settings can be read."));}@@ -152,7 +150,7 @@ export function useCloudLinkController() {// A failed mutation may have partially applied, so refresh server state on every exit.if (!wantsLink) {// Unlink needs no relay token; failed token reads must still allow it.- const unlinkResult = await unlinkPrimaryEnvironment({+ const unlinkResult = await unlinkEnvironment({target,clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,});@@ -161,7 +159,7 @@ export function useCloudLinkController() {if (!isAtomCommandInterrupted(unlinkResult)) {reportUpdateFailure(squashAtomCommandFailure(unlinkResult));}- primaryCloudLinkState.refresh();+ cloudLinkState.refresh();return false;}} else {@@ -182,7 +180,7 @@ export function useCloudLinkController() {currentLinkState.linkRevoked === true ||currentManagedTunnel !== desired.managedTunnel) {- const linkResult = await linkPrimaryEnvironment({+ const linkResult = await linkEnvironment({target,clerkToken,mode: desired.managedTunnel ? "managed" : "publish_only",@@ -197,15 +195,15 @@ export function useCloudLinkController() {if (limit === null) reportUpdateFailure(cause);else setTunnelLimit(limit);}- primaryCloudLinkState.refresh();+ cloudLinkState.refresh();return false;}}if (!canManageLink() || readLinkState() === null) {- primaryCloudLinkState.refresh();+ cloudLinkState.refresh();return false;}- const prefResult = await updatePrimaryEnvironmentPreferences({+ const prefResult = await updateEnvironmentPreferences({target,publishAgentActivity: desired.publish,...(desired.holdWebhooksWhileOffline === undefined@@ -216,12 +214,12 @@ export function useCloudLinkController() {if (!isAtomCommandInterrupted(prefResult)) {reportUpdateFailure(squashAtomCommandFailure(prefResult));}- primaryCloudLinkState.refresh();+ cloudLinkState.refresh();return false;}}- primaryCloudLinkState.refresh();+ cloudLinkState.refresh();const refreshResult = await refreshRelayEnvironments();if (refreshResult._tag === "Failure" && !isAtomCommandInterrupted(refreshResult)) {reportUpdateFailure(squashAtomCommandFailure(refreshResult));@@ -232,7 +230,7 @@ export function useCloudLinkController() {return {isSignedIn,- linkState: primaryCloudLinkState,+ linkState: cloudLinkState,linked,linkRevoked,managedTunnelActive,diff --git a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsxindex 70c4f6e8579..faf903c76bd 100644--- a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx+++ b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx@@ -77,7 +77,7 @@ function ConfiguredConnectOnboardingDialog() {const sessionScopesKnown =primaryEnvironmentId === null ? environmentsReady : primarySessionState._tag !== "Initial";- const controller = useCloudLinkController();+ const controller = useCloudLinkController(primaryEnvironmentId);const accountPage = useT3ConnectAccountPage();const showPublishStep = canManageRelay && controller.linkState.target !== null;const steps: ReadonlyArray<OnboardingStep> = showPublishStepdiff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.browser.test.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.browser.test.tsxnew file mode 100644index 00000000000..14204df0267--- /dev/null+++ b/apps/web/src/components/settings/AuthorizedClientsSettings.browser.test.tsx@@ -0,0 +1,80 @@+import {+ EnvironmentId,+ managedCapabilityDenial,+ type ManagedPolicySummary,+} from "@t3tools/contracts";+import { describe, expect, it, vi } from "vite-plus/test";++import "~/index.css";+import { render } from "../../../test/render";+import { AuthorizedClientsHeaderAction } from "./AuthorizedClientsSettings";++const localId = EnvironmentId.make("local");+const serviceId = EnvironmentId.make("service");++const state = vi.hoisted(() => ({+ primaryEnvironmentId: null as string | null,+ policies: new Map<string, unknown>(),+}));++vi.mock(import("../../state/environments"), async (original) => ({+ ...(await original()),+ usePrimaryEnvironmentId: (() => state.primaryEnvironmentId) as never,+}));+vi.mock(import("../../state/entities"), async (original) => ({+ ...(await original()),+ useServerConfigs: (() =>+ new Map(+ [...state.policies].map(([environmentId, managedPolicy]) => [+ environmentId,+ { managedPolicy },+ ]),+ )) as never,+}));+vi.mock(import("../../state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: (() => vi.fn()) as never,+}));++const remoteClientsOff: ManagedPolicySummary = {+ organization: "Example Corp",+ lockedSettings: [],+ limits: { clients: ["desktop"] },+};++function setup(policies: ReadonlyArray<readonly [EnvironmentId, ManagedPolicySummary]>) {+ state.primaryEnvironmentId = localId;+ state.policies = new Map(policies);+}++const renderHeader = (environmentId: EnvironmentId) =>+ render(+ <AuthorizedClientsHeaderAction+ environmentId={environmentId}+ onPairingLinkCreated={() => {}}+ clientSessions={null}+ isRevokingOtherClients={false}+ onRevokeOtherClients={() => {}}+ delegatableScopes={[]}+ />,+ );++describe("AuthorizedClientsHeaderAction", () => {+ const denial = managedCapabilityDenial(remoteClientsOff, "remoteClients")!;++ it("follows the selected service's policy, not the primary's", async () => {+ setup([[serviceId, remoteClientsOff]]);+ await using screen = await renderHeader(serviceId);++ await expect.element(screen.getByRole("group", { name: denial })).toBeVisible();+ await expect.element(screen.getByRole("button", { name: "Create link" })).toBeDisabled();+ });++ it("leaves pairing open on an unmanaged service when the primary is managed", async () => {+ setup([[localId, remoteClientsOff]]);+ await using screen = await renderHeader(serviceId);++ await expect.element(screen.getByRole("button", { name: "Create link" })).toBeEnabled();+ expect(screen.getByRole("group", { name: denial }).query()).toBeNull();+ });+});diff --git a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx b/apps/web/src/components/settings/AuthorizedClientsSettings.tsxindex 171bdeab60f..75e3c972ee7 100644--- a/apps/web/src/components/settings/AuthorizedClientsSettings.tsx+++ b/apps/web/src/components/settings/AuthorizedClientsSettings.tsx@@ -13,9 +13,12 @@ import {type AuthGrantScope,type AuthPairingCredentialResult,type AdvertisedEndpoint,+ type EnvironmentId,} from "@t3tools/contracts";-import { settlePromise } from "@t3tools/client-runtime/state/runtime";-import * as Cause from "effect/Cause";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";import { cn } from "../../lib/utils";@@ -47,14 +50,14 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { Button } from "../ui/button";import { Textarea } from "../ui/textarea";import {- createServerPairingCredential,isLoopbackHostname,type ServerClientSessionRecord,type ServerPairingLinkRecord,} from "~/environments/primary";+import { authEnvironment } from "~/state/auth";import { readEnvironmentScope } from "~/state/session";-import { usePrimaryEnvironmentId } from "~/state/environments";-import { usePrimaryManagedPolicy } from "~/state/managedPolicy";+import { useManagedPolicy, usePrimaryManagedPolicy } from "~/state/managedPolicy";+import { useAtomCommand } from "~/state/use-atom-command";import { ManagedControl } from "../ManagedPolicy";import { ConnectionStatusDot } from "../ConnectionStatusDot";import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";@@ -124,6 +127,8 @@ type PairingLinkListRowProps = {pairingLink: ServerPairingLinkRecord;credential: string | undefined;defaultShareOpen: boolean;+ /** Whether this page is served by the environment the link pairs with. */+ servedByEnvironment: boolean;endpointUrl: string | null | undefined;endpoints: ReadonlyArray<AdvertisedEndpoint>;defaultEndpointKey: string | null;@@ -136,6 +141,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({pairingLink,credential,defaultShareOpen,+ servedByEnvironment,endpointUrl,endpoints,defaultEndpointKey,@@ -191,7 +197,7 @@ const PairingLinkListRow = memo(function PairingLinkListRow({endpointPairingUrl ??(credential && endpointUrl != null && endpointUrl !== ""? (hostedPairingUrl ?? resolveDesktopPairingUrl(endpointUrl, credential))- : isLoopbackHostname(window.location.hostname)+ : !servedByEnvironment || isLoopbackHostname(window.location.hostname)? null: currentOriginPairingUrl);const [failedCopyValue, setFailedCopyValue] = useState<string | null>(null);@@ -567,6 +573,7 @@ const ConnectedClientListRow = memo(function ConnectedClientListRow({});type AuthorizedClientsHeaderActionProps = {+ environmentId: EnvironmentId;onPairingLinkCreated: (result: AuthPairingCredentialResult) => void;clientSessions: ReadonlyArray<ServerClientSessionRecord> | null;isRevokingOtherClients: boolean;@@ -575,14 +582,17 @@ type AuthorizedClientsHeaderActionProps = {};export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeaderAction({+ environmentId,onPairingLinkCreated,clientSessions,isRevokingOtherClients,onRevokeOtherClients,delegatableScopes,}: AuthorizedClientsHeaderActionProps) {- const primaryEnvironmentId = usePrimaryEnvironmentId();- const pairingDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "remoteClients");+ const pairingDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "remoteClients");+ const createPairingCredential = useAtomCommand(authEnvironment.createPairingCredential, {+ reportFailure: false,+ });const [dialogOpen, setDialogOpen] = useState(false);const [pairingLabel, setPairingLabel] = useState("");const [pairingScopes, setPairingScopes] = useState<ReadonlyArray<AuthGrantScope>>([@@ -593,27 +603,26 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHeadconst handleCreatePairingLink = async () => {if (- primaryEnvironmentId === null ||selectedScopes.length === 0 ||- !readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope) ||- !selectedScopes.every((scope) => readEnvironmentScope(primaryEnvironmentId, scope))+ !readEnvironmentScope(environmentId, AuthAccessWriteScope) ||+ !selectedScopes.every((scope) => readEnvironmentScope(environmentId, scope)))return;setIsCreatingPairingLink(true);- const settled = await settlePromise(async () => {- const created = await createServerPairingCredential({- label: pairingLabel,- scopes: selectedScopes,- });- onPairingLinkCreated(created);+ const trimmedLabel = pairingLabel.trim();+ const result = await createPairingCredential({+ environmentId,+ input: { ...(trimmedLabel ? { label: trimmedLabel } : {}), scopes: selectedScopes },+ });+ if (result._tag === "Success") {+ onPairingLinkCreated(result.value);setPairingLabel("");setPairingScopes(AuthStandardClientScopes.filter((scope) => delegatableScopes.includes(scope)),);setDialogOpen(false);- });- if (settled._tag === "Failure") {- const error = Cause.squash(settled.cause);+ } else if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);const message = error instanceof Error ? error.message : "Failed to create pairing URL.";toastManager.add(stackedThreadToast({@@ -787,6 +796,7 @@ export const AuthorizedClientsHeaderAction = memo(function AuthorizedClientsHead});type PairingClientsListProps = {+ servedByEnvironment: boolean;endpointUrl: string | null | undefined;endpoints: ReadonlyArray<AdvertisedEndpoint>;defaultEndpointKey: string | null;@@ -803,6 +813,7 @@ type PairingClientsListProps = {};export const PairingClientsList = memo(function PairingClientsList({+ servedByEnvironment,endpointUrl,endpoints,defaultEndpointKey,@@ -825,6 +836,7 @@ export const PairingClientsList = memo(function PairingClientsList({pairingLink={pairingLink}credential={createdPairingCredentials.get(pairingLink.id)}defaultShareOpen={pairingLink.id === sharedPairingLinkId}+ servedByEnvironment={servedByEnvironment}endpointUrl={endpointUrl}endpoints={endpoints}defaultEndpointKey={defaultEndpointKey}diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.test.tsindex 0f76d89b4d3..ffd59c5439b 100644--- a/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts+++ b/apps/web/src/components/settings/ConnectionsSettings.logic.test.ts@@ -1,7 +1,8 @@-import type { DesktopWslState } from "@t3tools/contracts";+import { type DesktopWslState, EnvironmentId } from "@t3tools/contracts";import { describe, expect, it, vi } from "vite-plus/test";import {applyWslEnableSelection,+ resolveAccessEnvironmentId,resolveTailscaleServeBaseUrl,selectQrEndpointOption,togglePairingScopeSelection,@@ -144,3 +145,59 @@ describe("selectQrEndpointOption", () => {);});});++describe("resolveAccessEnvironmentId", () => {+ const primary = EnvironmentId.make("primary");+ const service = EnvironmentId.make("service");+ const laptop = EnvironmentId.make("laptop");+ it.each([+ {+ label: "defaults to the primary environment",+ primaryEnvironmentId: primary,+ environments: [+ { environmentId: primary, connected: true },+ { environmentId: service, connected: true },+ ],+ selected: null,+ expected: primary,+ },+ {+ label: "falls back to a connected saved environment without a primary",+ primaryEnvironmentId: null,+ environments: [+ { environmentId: laptop, connected: false },+ { environmentId: service, connected: true },+ ],+ selected: null,+ expected: service,+ },+ {+ label: "keeps an explicit choice",+ primaryEnvironmentId: primary,+ environments: [+ { environmentId: primary, connected: true },+ { environmentId: laptop, connected: false },+ ],+ selected: laptop,+ expected: laptop,+ },+ {+ label: "drops a choice that is no longer listed",+ primaryEnvironmentId: null,+ environments: [{ environmentId: service, connected: true }],+ selected: laptop,+ expected: service,+ },+ {+ label: "has nothing to show without environments",+ primaryEnvironmentId: null,+ environments: [],+ selected: null,+ expected: null,+ },+ ])("$label", ({ primaryEnvironmentId, environments, selected, expected }) => {+ expect(resolveAccessEnvironmentId({ primaryEnvironmentId, environments, selected })).toBe(+ expected,+ );+ });+});diff --git a/apps/web/src/components/settings/ConnectionsSettings.logic.ts b/apps/web/src/components/settings/ConnectionsSettings.logic.tsindex 23c20ad54da..e219694351b 100644--- a/apps/web/src/components/settings/ConnectionsSettings.logic.ts+++ b/apps/web/src/components/settings/ConnectionsSettings.logic.ts@@ -19,6 +19,7 @@ import {type DesktopSshEnvironmentTarget,type DesktopUpdateState,type DesktopWslState,+ type EnvironmentId,} from "@t3tools/contracts";import {getDesktopUpdateDownloadedVersion,@@ -436,3 +437,22 @@ export function endpointShareHint(endpoint: AdvertisedEndpoint, url: string): streturn "Clients on this machine";}}++/** An explicit choice while it is listed, else the primary, else a connected environment. */+export function resolveAccessEnvironmentId(input: {+ readonly primaryEnvironmentId: EnvironmentId | null;+ readonly environments: ReadonlyArray<{+ readonly environmentId: EnvironmentId;+ readonly connected: boolean;+ }>;+ readonly selected: EnvironmentId | null;+}): EnvironmentId | null {+ const isListed = (environmentId: EnvironmentId | null) =>+ input.environments.some((environment) => environment.environmentId === environmentId);+ if (isListed(input.selected)) return input.selected;+ if (isListed(input.primaryEnvironmentId)) return input.primaryEnvironmentId;+ return (+ (input.environments.find((environment) => environment.connected) ?? input.environments[0])+ ?.environmentId ?? null+ );+}diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsxindex 5409f6ec530..087f73589f3 100644--- a/apps/web/src/components/settings/ConnectionsSettings.tsx+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx@@ -1,7 +1,7 @@import { SessionPermissions } from "./SessionPermissions";import { ChevronRightIcon, EllipsisIcon } from "lucide-react";import { useAtomValue } from "@effect/atom-react";-import { useState } from "react";+import { type ReactNode, useState } from "react";import {AuthAccessReadScope,AuthAccessWriteScope,@@ -30,9 +30,11 @@ import {applyWslEnableSelection,isWslSettingsRowVisible,missingTailscaleEndpointDescription,+ resolveAccessEnvironmentId,resolveLocalVersionStatusLabel,resolveTailscaleServeBaseUrl,} from "./ConnectionsSettings.logic";+import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis";import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";import { ManagedByOrganization } from "../ManagedPolicy";import { LocalEnvironmentSetting } from "./LocalEnvironmentSetting";@@ -72,13 +74,7 @@ import { stackedThreadToast, toastManager } from "../ui/toast";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { Button } from "../ui/button";import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon";-import {- revokeOtherServerClientSessions,- revokeServerClientSession,- revokeServerPairingLink,- usePrimarySessionState,- type ServerClientSessionRecord,-} from "~/environments/primary";+import { type ServerClientSessionRecord } from "~/environments/primary";import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";import { useUiStateStore } from "~/uiStateStore";import {@@ -90,7 +86,11 @@ import { hasCloudPublicConfig } from "~/cloud/publicConfig";import { RemoveT3ConnectEnvironmentDialog } from "../clerk/RemoveT3ConnectEnvironmentDialog";import { authEnvironment } from "~/state/auth";import { environmentCatalog } from "~/connection/catalog";-import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";+import {+ readEnvironmentScope,+ useEnvironmentScope,+ useEnvironmentSessionState,+} from "~/state/session";import { useEnvironmentQuery } from "~/state/query";import {desktopNetworkAccessStateAtom,@@ -100,8 +100,10 @@ import { desktopWslStateAtom, refreshDesktopWslState } from "~/state/desktopWslSimport { useDesktopUpdateState } from "~/state/desktopUpdate";import {type EnvironmentPresentation,+ useEnvironment,useEnvironments,usePrimaryEnvironment,+ usePrimaryEnvironmentId,} from "~/state/environments";import { requestConfirmDialog } from "~/confirmDialog";import { useAtomCommand } from "../../state/use-atom-command";@@ -154,8 +156,98 @@ function LocalVersionStatusLabel() {);}-/** Environments lists the machines this app connects to; access covers who may reach this one. */+/** Environments lists the machines this app connects to; access covers who may reach one of them. */export function ConnectionsSettings({ view }: { readonly view: "environments" | "access" }) {+ return view === "access" ? (+ <AccessSettings />+ ) : (+ <ConnectionsSettingsContent view="environments" accessEnvironmentId={null} />+ );+}++function AccessSettings() {+ const { environments } = useEnvironments();+ const primaryEnvironmentId = usePrimaryEnvironmentId();+ const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);+ const candidates = environments.filter(+ (environment) =>+ environment.environmentId === primaryEnvironmentId ||+ (environment.entry.enabled && !isDesktopLocalConnectionTarget(environment.entry.target)),+ );+ const accessEnvironmentId = resolveAccessEnvironmentId({+ primaryEnvironmentId,+ environments: candidates.map((environment) => ({+ environmentId: environment.environmentId,+ connected: environment.connection.phase === "connected",+ })),+ selected: selectedEnvironmentId,+ });+ const picker =+ candidates.length > 1 && accessEnvironmentId !== null ? (+ <div className="flex min-w-0 items-center gap-1.5 px-3 text-sm text-muted-foreground sm:px-4">+ <span className="shrink-0">Showing access for</span>+ <Select+ value={accessEnvironmentId}+ onValueChange={(next) => {+ if (next !== null) setSelectedEnvironmentId(next);+ }}+ >+ <SelectTrigger size="sm" className="w-auto max-w-72" aria-label="Environment">+ <SelectValue>+ {(value: EnvironmentId) => {+ const environment = candidates.find(+ (candidate) => candidate.environmentId === value,+ );+ return environment ? settingsScopeEnvironmentLabel(environment, candidates) : null;+ }}+ </SelectValue>+ </SelectTrigger>+ <SelectPopup alignItemWithTrigger={false}>+ {candidates.map((environment) => (+ <SelectItem+ hideIndicator+ key={environment.environmentId}+ value={environment.environmentId}+ >+ <span className="flex min-w-0 items-center gap-2">+ <EnvironmentMachineIcon+ aria-hidden+ kind={resolveEnvironmentMachineKind(environment.serverConfig)}+ className="size-3.5 shrink-0"+ />+ <span className="min-w-0 truncate">+ {settingsScopeEnvironmentLabel(environment, candidates)}+ </span>+ {environment.connection.phase !== "connected" ? (+ <span className="shrink-0 text-xs text-muted-foreground">Offline</span>+ ) : null}+ </span>+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ </div>+ ) : null;+ // Keyed so pairing credentials and pending work never carry over to another environment.+ return (+ <ConnectionsSettingsContent+ key={accessEnvironmentId ?? "none"}+ view="access"+ accessEnvironmentId={accessEnvironmentId}+ accessEnvironmentPicker={picker}+ />+ );+}++function ConnectionsSettingsContent({+ view,+ accessEnvironmentId,+ accessEnvironmentPicker = null,+}: {+ readonly view: "environments" | "access";+ readonly accessEnvironmentId: EnvironmentId | null;+ readonly accessEnvironmentPicker?: ReactNode;+}) {const desktopBridge = window.desktopBridge;const { environments } = useEnvironments();const primaryEnvironment = usePrimaryEnvironment();@@ -165,11 +257,15 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |reportFailure: false,});const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;- const primarySessionState = usePrimarySessionState();- const currentSessionScopes = primarySessionState.data?.authenticated- ? (primarySessionState.data.permissions ?? primarySessionState.data.scopes ?? null)+ const accessEnvironment = useEnvironment(accessEnvironmentId);+ // Desktop network, Tailscale, and WSL controls change the backend this app spawned.+ const isPrimaryAccess =+ accessEnvironmentId !== null && accessEnvironmentId === primaryEnvironmentId;+ const accessSessionState = useEnvironmentSessionState(accessEnvironmentId);+ const currentSessionScopes = accessSessionState.data?.authenticated+ ? (accessSessionState.data.permissions ?? accessSessionState.data.scopes ?? null): null;- const currentAuthPolicy = desktopBridge ? null : (primarySessionState.data?.auth.policy ?? null);+ const currentAuthPolicy = desktopBridge ? null : (accessSessionState.data?.auth.policy ?? null);const savedEnvironments = environments.filter((environment) => environment.entry.target._tag !== "PrimaryConnectionTarget",);@@ -272,9 +368,11 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |DesktopServerExposureState["mode"] | null>(null);const primaryServerConfig = primaryEnvironment?.serverConfig ?? null;- const primaryManagedPolicy = primaryServerConfig?.managedPolicy;// Turning remote access off stays possible; only the way in is managed.- const remoteClientsDenial = managedCapabilityDenial(primaryManagedPolicy, "remoteClients");+ const remoteClientsDenial = managedCapabilityDenial(+ primaryServerConfig?.managedPolicy,+ "remoteClients",+ );const primaryVersionMismatch = resolveServerConfigVersionMismatch(primaryServerConfig);const primaryServerUpdateState = useAtomValue(serverEnvironment.updateStateAtom(primaryEnvironmentId),@@ -286,21 +384,28 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |const setDefaultAdvertisedEndpointKey = useUiStateStore((state) => state.setDefaultAdvertisedEndpointKey,);- const canReadAccess = useEnvironmentScope(primaryEnvironmentId, AuthAccessReadScope);- const canWriteAccess = useEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope);- const canReadRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayReadScope);- const canMaintain = useEnvironmentScope(primaryEnvironmentId, AuthEnvironmentMaintainScope);- const canManageRelay = useEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope);- const canManageLocalBackend = !isLocalEnvironmentDisabled() && canMaintain;+ const canReadAccess = useEnvironmentScope(accessEnvironmentId, AuthAccessReadScope);+ const canWriteAccess = useEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope);+ const canReadRelay = useEnvironmentScope(accessEnvironmentId, AuthRelayReadScope);+ const canMaintain = useEnvironmentScope(accessEnvironmentId, AuthEnvironmentMaintainScope);+ const canManageRelay = useEnvironmentScope(accessEnvironmentId, AuthRelayWriteScope);+ const canManageLocalBackend = isPrimaryAccess && !isLocalEnvironmentDisabled() && canMaintain;const showsAccess = view === "access";const authAccessChanges = useEnvironmentQuery(- showsAccess && canReadAccess && primaryEnvironmentId !== null+ showsAccess && canReadAccess && accessEnvironmentId !== null? authEnvironment.accessChanges({- environmentId: primaryEnvironmentId,+ environmentId: accessEnvironmentId,input: null,}): null,);+ const revokePairingLink = useAtomCommand(authEnvironment.revokePairingLink, {+ reportFailure: false,+ });+ const revokeClient = useAtomCommand(authEnvironment.revokeClient, { reportFailure: false });+ const revokeOtherClients = useAtomCommand(authEnvironment.revokeOtherClients, {+ reportFailure: false,+ });const desktopNetworkAccess = useEnvironmentQuery(showsAccess && canManageLocalBackend && desktopBridge ? desktopNetworkAccessStateAtom : null,);@@ -468,17 +573,15 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |const handleRevokeDesktopPairingLink = async (id: string) => {if (- primaryEnvironmentId === null ||- !readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope)+ accessEnvironmentId === null ||+ !readEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope))return;setRevokingDesktopPairingLinkId(id);setDesktopAccessManagementMutationError(null);- const settled = await settlePromise(async () => {- await revokeServerPairingLink(id);- });- if (settled._tag === "Failure") {- const error = Cause.squash(settled.cause);+ const result = await revokePairingLink({ environmentId: accessEnvironmentId, input: { id } });+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);const message = error instanceof Error ? error.message : "Failed to revoke pairing link.";setDesktopAccessManagementMutationError(message);toastManager.add(@@ -496,17 +599,15 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |sessionId: ServerClientSessionRecord["sessionId"],) => {if (- primaryEnvironmentId === null ||- !readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope)+ accessEnvironmentId === null ||+ !readEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope))return;setRevokingDesktopClientSessionId(sessionId);setDesktopAccessManagementMutationError(null);- const settled = await settlePromise(async () => {- await revokeServerClientSession(sessionId);- });- if (settled._tag === "Failure") {- const error = Cause.squash(settled.cause);+ const result = await revokeClient({ environmentId: accessEnvironmentId, input: { sessionId } });+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);const message = error instanceof Error ? error.message : "Failed to revoke client access.";setDesktopAccessManagementMutationError(message);toastManager.add(@@ -522,22 +623,21 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |const handleRevokeOtherDesktopClients = async () => {if (- primaryEnvironmentId === null ||- !readEnvironmentScope(primaryEnvironmentId, AuthAccessWriteScope)+ accessEnvironmentId === null ||+ !readEnvironmentScope(accessEnvironmentId, AuthAccessWriteScope))return;setIsRevokingOtherDesktopClients(true);setDesktopAccessManagementMutationError(null);- const settled = await settlePromise(async () => {- const revokedCount = await revokeOtherServerClientSessions();+ const result = await revokeOtherClients({ environmentId: accessEnvironmentId, input: null });+ if (result._tag === "Success") {toastManager.add({type: "success",- title: revokedCount === 1 ? "Revoked 1 other client" : `Revoked ${revokedCount} clients`,+ title: result.value === 1 ? "Revoked 1 other client" : `Revoked ${result.value} clients`,description: "Other paired clients will need a new pairing link before reconnecting.",});- });- if (settled._tag === "Failure") {- const error = Cause.squash(settled.cause);+ } else if (!isAtomCommandInterrupted(result)) {+ const error = squashAtomCommandFailure(result);const message = error instanceof Error ? error.message : "Failed to revoke other clients.";setDesktopAccessManagementMutationError(message);toastManager.add(@@ -938,6 +1038,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |clientSessions: typeof desktopClientSessions,) => (<PairingClientsList+ servedByEnvironment={isPrimaryAccess}endpointUrl={desktopServerExposureState?.endpointUrl}endpoints={visibleDesktopAdvertisedEndpoints}defaultEndpointKey={defaultDesktopAdvertisedEndpointKey}@@ -1033,28 +1134,28 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |/>);+ const accessServerConfig = accessEnvironment?.serverConfig ?? null;const primarySettings = (<>- {primaryEnvironmentId !== null ? (+ {accessEnvironmentPicker}+ {accessEnvironmentId !== null ? (<><SettingsSection{...searchableSetting("connections-environment")}title={- primaryEnvironment?.label ?? (desktopBridge ? "This machine" : "Primary environment")+ accessEnvironment?.label ?? (desktopBridge ? "This machine" : "Primary environment")}icon={<EnvironmentMachineIconaria-hiddenkind={- primaryServerConfig- ? resolveEnvironmentMachineKind(primaryServerConfig)- : "desktop"+ accessServerConfig ? resolveEnvironmentMachineKind(accessServerConfig) : "desktop"}className="size-4"/>}headerAction={- primaryEnvironmentId !== null ? (+ accessEnvironmentId !== null ? (<Menu><MenuTriggerrender={@@ -1070,17 +1171,17 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |</MenuTrigger><MenuPopup align="end"><EnvironmentIconMenu- environmentId={primaryEnvironmentId}- serverConfig={primaryServerConfig}+ environmentId={accessEnvironmentId}+ serverConfig={accessServerConfig}/></MenuPopup></Menu>) : null}>- {primaryManagedPolicy ? (+ {accessServerConfig?.managedPolicy ? (<div className="px-3 py-2 sm:px-4">- <ManagedByOrganization policy={primaryManagedPolicy} />+ <ManagedByOrganization policy={accessServerConfig.managedPolicy} /></div>) : null}{canManageLocalBackend ? (@@ -1132,19 +1233,18 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |{renderEndpointRows()}{renderTailscaleRow()}{renderWslRow()}- {canReadRelay || canManageRelay ? (- <CloudLinkRow canReadRelay={canReadRelay} canManageRelay={canManageRelay} />- ) : null}</>) : canManageLocalBackend ? (- <>- {renderDisabledNetworkAccessRow()}- {canReadRelay || canManageRelay ? (- <CloudLinkRow canReadRelay={canReadRelay} canManageRelay={canManageRelay} />- ) : null}- </>+ renderDisabledNetworkAccessRow()) : null}- {primaryEnvironment ? (+ {canReadRelay || canManageRelay ? (+ <CloudLinkRow+ environmentId={accessEnvironmentId}+ canReadRelay={canReadRelay}+ canManageRelay={canManageRelay}+ />+ ) : null}+ {accessEnvironment ? (<details className="group px-3 sm:px-4"><summary className="flex min-h-11 cursor-pointer list-none items-center gap-2 rounded-md text-sm font-medium outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring [&::-webkit-details-marker]:hidden">Permissions@@ -1154,8 +1254,8 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |/></summary><SessionPermissions- environmentId={primaryEnvironment.environmentId}- connected={primaryEnvironment.connection.phase === "connected"}+ environmentId={accessEnvironment.environmentId}+ connected={accessEnvironment.connection.phase === "connected"}/></details>) : null}@@ -1177,6 +1277,7 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |control={canWriteAccess ? (<AuthorizedClientsHeaderAction+ environmentId={accessEnvironmentId}delegatableScopes={currentSessionScopes ?? []}onPairingLinkCreated={handlePairingLinkCreated}clientSessions={@@ -1481,9 +1582,6 @@ export function ConnectionsSettings({ view }: { readonly view: "environments" |title="No environment selected"description="Connect an environment to view its settings and access."/>- {canReadRelay || canManageRelay ? (- <CloudLinkRow canReadRelay={canReadRelay} canManageRelay={canManageRelay} />- ) : null}</SettingsSection>)}</>diff --git a/apps/web/src/components/settings/SavedEnvironmentRows.tsx b/apps/web/src/components/settings/SavedEnvironmentRows.tsxindex ec888267c78..53b745412d9 100644--- a/apps/web/src/components/settings/SavedEnvironmentRows.tsx+++ b/apps/web/src/components/settings/SavedEnvironmentRows.tsx@@ -55,13 +55,9 @@ import { useT3ConnectAccountPage } from "../clerk/T3ConnectAccountPages";import { TunnelLimitAlert, TunnelUsageMeter } from "../cloud/TunnelUsage";import { environmentCatalog } from "~/connection/catalog";import { readEnvironmentScope } from "~/state/session";-import {- type EnvironmentPresentation,- useRelayEnvironmentDiscovery,- usePrimaryEnvironmentId,-} from "~/state/environments";+import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";import { APP_VERSION } from "~/branding";-import { usePrimaryManagedPolicy } from "~/state/managedPolicy";+import { useManagedPolicy } from "~/state/managedPolicy";import { useAtomCommand } from "../../state/use-atom-command";import { serverEnvironment } from "~/state/server";import {@@ -518,11 +514,16 @@ function T3ConnectTunnelUsage({ tunnelLimit }: { readonly tunnelLimit: number |);}-function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boolean }) {- const primaryEnvironmentId = usePrimaryEnvironmentId();+function ConfiguredCloudLinkRow({+ environmentId,+ canManageRelay,+}: {+ readonly environmentId: EnvironmentId;+ readonly canManageRelay: boolean;+}) {const {isSignedIn,- linkState: primaryCloudLinkState,+ linkState: cloudLinkState,linkRevoked,managedTunnelActive,managedTunnelOutOfSync,@@ -531,10 +532,10 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: boperationError,tunnelLimit,reconcileCloudState,- } = useCloudLinkController();+ } = useCloudLinkController(environmentId);const { openAuthPrompt } = useT3ConnectAuthPrompt();// The server unlinks and refuses relay changes under such a policy; unlinking stays possible.- const connectDenial = managedCapabilityDenial(usePrimaryManagedPolicy(), "connect");+ const connectDenial = managedCapabilityDenial(useManagedPolicy(environmentId), "connect");const [isUpdating, setIsUpdating] = useState(false);const [isUpdatingPreference, setIsUpdatingPreference] = useState(false);@@ -545,8 +546,8 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: bconst switchDisabled =!canManageRelay ||!isSignedIn ||- primaryCloudLinkState.data === null ||- primaryCloudLinkState.isPending ||+ cloudLinkState.data === null ||+ cloudLinkState.isPending ||isBusy;// `isSignedIn` is undefined until Clerk loads. Signed out, one row shows a// sign-in button instead of its switch; the onboarding dialog that opens after@@ -557,7 +558,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: bSign in</Button>);- const refreshLinkState = useEffectEvent(primaryCloudLinkState.refresh);+ const refreshLinkState = useEffectEvent(cloudLinkState.refresh);// The server rechecks reachability when the tunnel's 30 s readiness poll changes.// Poll while mounted, so a failed read does not stop later ones.// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- 30 s interval that refreshes the cloud link reachability while mounted@@ -565,7 +566,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: bconst interval = window.setInterval(() => refreshLinkState(), 30_000);return () => window.clearInterval(interval);}, []);- const reachability = managedTunnelActive ? primaryCloudLinkState.data?.reachability : undefined;+ const reachability = managedTunnelActive ? cloudLinkState.data?.reachability : undefined;const reachabilityStatus =reachability?.status === "reachable" ? (formatConnectReachable(reachability)@@ -586,11 +587,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b) : null;const updateManagedTunnel = async (enabled: boolean) => {- if (- primaryEnvironmentId === null ||- !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)- )- return;+ if (!readEnvironmentScope(environmentId, AuthRelayWriteScope)) return;setIsUpdating(true);const ok = await reconcileCloudState({ managedTunnel: enabled, publish: publishAgentActivity });if (ok) {@@ -612,11 +609,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b};const updatePublishAgentActivity = async (enabled: boolean) => {- if (- primaryEnvironmentId === null ||- !readEnvironmentScope(primaryEnvironmentId, AuthRelayWriteScope)- )- return;+ if (!readEnvironmentScope(environmentId, AuthRelayWriteScope)) return;setIsUpdatingPreference(true);const ok = await reconcileCloudState({ managedTunnel: managedTunnelActive, publish: enabled });if (ok) {@@ -672,7 +665,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b? "T3 Connect is out of sync. This environment is linked only to publish agent activity, so other devices cannot connect. Turn T3 Connect on to repair it.": "Make this environment available to your other devices through T3 Connect."}- status={operationError ?? primaryCloudLinkState.error ?? reachabilityStatus}+ status={operationError ?? cloudLinkState.error ?? reachabilityStatus}managed={managedTunnelActive ? undefined : connectDenial}control={signedOut ? (@@ -742,9 +735,11 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b}export function CloudLinkRow({+ environmentId,canReadRelay,canManageRelay,}: {+ readonly environmentId: EnvironmentId;readonly canReadRelay: boolean;readonly canManageRelay: boolean;}) {@@ -757,7 +752,7 @@ export function CloudLinkRow({/>);}- return <ConfiguredCloudLinkRow canManageRelay={canManageRelay} />;+ return <ConfiguredCloudLinkRow environmentId={environmentId} canManageRelay={canManageRelay} />;}function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnabled?: boolean }) {diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsxindex 2b8b37d4790..1c65371cfbd 100644--- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx+++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx@@ -48,7 +48,7 @@ import { formatRelativeTime } from "../../timestampFormat";import { useEnvironmentSettings } from "../../hooks/useSettings";import { getCustomModelOptionsByInstance } from "../../modelSelection";import { providerInstanceEntriesFor } from "../../providerInstances";-import { usePrimaryCloudLinkState } from "../../cloud/primaryCloudLinkState";+import { usePrimaryCloudLinkState } from "../../cloud/cloudLinkState";import { requestConfirmDialog } from "../../confirmDialog";import { webhookAddress } from "@t3tools/client-runtime/webhook-address";import { Link, useNavigate } from "@tanstack/react-router";diff --git a/apps/web/src/components/settings/SettingsScopeSentence.tsx b/apps/web/src/components/settings/SettingsScopeSentence.tsxindex bb6a896d458..907cbc0b4bd 100644--- a/apps/web/src/components/settings/SettingsScopeSentence.tsx+++ b/apps/web/src/components/settings/SettingsScopeSentence.tsx@@ -49,7 +49,7 @@ export const SETTINGS_DEVICE_ONLY_PATHS: ReadonlySet<string> = new Set(["/settings/diffs","/settings/snap-shot","/settings/connections",- // Network access and authorized clients belong to the environment serving this app.+ // Access picks its environment on the page itself."/settings/access","/settings/about",]);diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.tsindex 712c4d87d70..254673b0026 100644--- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts+++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts@@ -1,6 +1,6 @@import { AuthEnvironmentMaintainScope } from "@t3tools/contracts";-import { usePrimaryCloudLinkState } from "~/cloud/primaryCloudLinkState";+import { usePrimaryCloudLinkState } from "~/cloud/cloudLinkState";import { hasCloudPublicConfig } from "~/cloud/publicConfig";import { isElectron } from "~/env";import { isLocalEnvironmentDisabled } from "~/localEnvironment";diff --git a/apps/web/src/environments/primary/auth.ts b/apps/web/src/environments/primary/auth.tsindex daa0894abcb..e9affcfbdd7 100644--- a/apps/web/src/environments/primary/auth.ts+++ b/apps/web/src/environments/primary/auth.ts@@ -2,8 +2,6 @@ import type {AuthBrowserSessionResult,AuthClientMetadata,AuthEnvironmentScope,- AuthGrantScope,- AuthPairingCredentialResult,ServerAuthSessionMethod,AuthSessionId,AuthSessionState,@@ -347,83 +345,6 @@ export async function submitServerAuthCredential(credential: string): Promise<vostripPairingTokenFromUrl();}-export async function createServerPairingCredential(input?: {- readonly label?: string;- readonly scopes?: ReadonlyArray<AuthGrantScope>;-}): Promise<AuthPairingCredentialResult> {- const trimmedLabel = input?.label?.trim();- try {- return await runPrimaryHttp(- PrimaryEnvironmentHttpClient.pipe(- Effect.flatMap((client) =>- client.auth.pairingCredential({- headers: {},- payload: {- ...(trimmedLabel ? { label: trimmedLabel } : {}),- ...(input?.scopes ? { scopes: input.scopes } : {}),- },- }),- ),- ),- );- } catch (error) {- throw PrimaryEnvironmentRequestError.fromCause({- operation: "create-pairing-credential",- cause: error,- });- }-}--export async function revokeServerPairingLink(id: string): Promise<void> {- try {- await runPrimaryHttp(- PrimaryEnvironmentHttpClient.pipe(- Effect.flatMap((client) => client.auth.revokePairingLink({ headers: {}, payload: { id } })),- ),- );- } catch (error) {- throw PrimaryEnvironmentRequestError.fromCause({- operation: "revoke-pairing-link",- pairingLinkId: id,- cause: error,- });- }-}--export async function revokeServerClientSession(sessionId: AuthSessionId): Promise<void> {- try {- await runPrimaryHttp(- PrimaryEnvironmentHttpClient.pipe(- Effect.flatMap((client) =>- client.auth.revokeClient({ headers: {}, payload: { sessionId } }),- ),- ),- );- } catch (error) {- throw PrimaryEnvironmentRequestError.fromCause({- operation: "revoke-client-session",- sessionId,- cause: error,- });- }-}--export async function revokeOtherServerClientSessions(): Promise<number> {- try {- const result = await runPrimaryHttp(- PrimaryEnvironmentHttpClient.pipe(- Effect.flatMap((client) => client.auth.revokeOtherClients({ headers: {} })),- ),- );- return result.revokedCount;- } catch (error) {- throw PrimaryEnvironmentRequestError.fromCause({- operation: "revoke-other-client-sessions",- cause: error,- });- }-}-export async function resolveInitialServerAuthGateState(): Promise<ServerAuthGateState> {// Preserve explicit grant replacement across the auth-gate reload triggered by token removal.if (window.location.pathname.replace(/\/+$/, "") !== "/pair") {diff --git a/apps/web/src/environments/primary/index.ts b/apps/web/src/environments/primary/index.tsindex 78068f7642c..a35a6699cc5 100644--- a/apps/web/src/environments/primary/index.ts+++ b/apps/web/src/environments/primary/index.ts@@ -1,12 +1,8 @@export {- createServerPairingCredential,peekPairingTokenFromUrl,PrimaryEnvironmentPairingCredentialRejectedError,PrimaryEnvironmentRequestError,resolveInitialServerAuthGateState,- revokeOtherServerClientSessions,- revokeServerClientSession,- revokeServerPairingLink,stripPairingTokenFromUrl,submitServerAuthCredential,takePairingTokenFromUrl,@@ -15,8 +11,6 @@ export {__resetServerAuthBootstrapForTests,} from "./auth";-export { usePrimarySessionState } from "./sessionState";-export {DesktopEnvironmentBootstrapIncompleteError,PrimaryEnvironmentProtocolUnsupportedError,diff --git a/apps/web/src/environments/primary/sessionState.ts b/apps/web/src/environments/primary/sessionState.tsdeleted file mode 100644index 766421a17af..00000000000--- a/apps/web/src/environments/primary/sessionState.ts+++ /dev/null@@ -1,37 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import * as Cause from "effect/Cause";-import * as Effect from "effect/Effect";-import { AsyncResult, Atom } from "effect/reactivity";--import { isLocalEnvironmentDisabled } from "../../localEnvironment";-import { appAtomRegistry } from "../../rpc/atomRegistry";-import { fetchSessionState } from "./auth";--const primarySessionStateAtom = Atom.make(- Effect.suspend(() =>- isLocalEnvironmentDisabled() ? Effect.succeed(null) : Effect.promise(fetchSessionState),- ),-).pipe(- Atom.swr({ staleTime: 5_000, revalidateOnMount: true }),- Atom.setIdleTTL(5 * 60_000),- Atom.withLabel("primary-environment:session"),-);--function refreshPrimarySessionState(): void {- appAtomRegistry.refresh(primarySessionStateAtom);-}--export function usePrimarySessionState() {- const result = useAtomValue(primarySessionStateAtom);- let error: string | null = null;- if (result._tag === "Failure") {- const cause = Cause.squash(result.cause);- error = cause instanceof Error ? cause.message : "Could not read environment session.";- }- return {- data: AsyncResult.getOrElse(result, () => null),- error,- isPending: result.waiting,- refresh: refreshPrimarySessionState,- };-}diff --git a/apps/web/src/state/session.ts b/apps/web/src/state/session.tsindex 00c38aec3df..2c2de0a107d 100644--- a/apps/web/src/state/session.ts+++ b/apps/web/src/state/session.ts@@ -92,8 +92,12 @@ export function readPreparedConnection(environmentId: EnvironmentId) {}/** data survives SWR revalidation; isPending applies only before first resolve. */-export function useEnvironmentSessionState(environmentId: EnvironmentId) {- const result = useAtomValue(environmentSession.sessionStateAtom(environmentId));+export function useEnvironmentSessionState(environmentId: EnvironmentId | null) {+ const result = useAtomValue(+ environmentId === null+ ? EMPTY_SESSION_STATE_ATOM+ : environmentSession.sessionStateAtom(environmentId),+ );return {data: AsyncResult.getOrElse(result, () => null),hasError: result._tag === "Failure",diff --git a/docs/user/remote-access.md b/docs/user/remote-access.mdindex 259f58c00e5..649dfbca637 100644--- a/docs/user/remote-access.md+++ b/docs/user/remote-access.md@@ -369,6 +369,10 @@ pairing links and revoke client sessions. Revoking an unused link prevents newpairings; revoke a device's session to remove its existing access. Command-linemanagement is available through `t3 auth --help`.+When the app connects to more than one environment, choose one at the top of the+page. A desktop app with **Local environment** off can manage a background+service on the same machine this way, including its T3 Connect link.+A session with an open connection stays listed after its access credentialexpires.diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex 270640bc4ae..15d9bc66962 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -231,6 +231,10 @@"types": "./src/state/peerLinks.ts","default": "./src/state/peerLinks.ts"},+ "./state/environmentHttpAuth": {+ "types": "./src/state/environmentHttpAuth.ts",+ "default": "./src/state/environmentHttpAuth.ts"+ },"./state/peerPairingCode": {"types": "./src/state/peerPairingCode.ts","default": "./src/state/peerPairingCode.ts"diff --git a/packages/client-runtime/src/state/auth.ts b/packages/client-runtime/src/state/auth.tsindex 3f249e3b417..9c9a4fd308d 100644--- a/packages/client-runtime/src/state/auth.ts+++ b/packages/client-runtime/src/state/auth.ts@@ -2,14 +2,22 @@ import type {AuthAccessSnapshot,AuthAccessStreamEvent,AuthAccessStreamSnapshotEvent,+ AuthCreatePairingCredentialInput,+ AuthRevokeClientSessionInput,+ AuthRevokePairingLinkInput,} from "@t3tools/contracts";import { WS_METHODS } from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import type { HttpClient } from "effect/http";import * as Stream from "effect/Stream";import { Atom } from "effect/reactivity";import type { EnvironmentRegistry } from "../connection/registry.ts";import { subscribe } from "../rpc/client.ts";-import { createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";+import { executeConnectedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";+import { createEnvironmentCommand, createEnvironmentSubscriptionAtomFamily } from "./runtime.ts";++const ACCESS_REQUEST_TIMEOUT_MS = 8_000;export const EMPTY_AUTH_ACCESS_SNAPSHOT: AuthAccessSnapshot = {pairingLinks: [],@@ -75,10 +83,55 @@ function projectAuthAccessSnapshot(return [snapshot, [projected]];}+/** Access management runs on the chosen environment with this client's own session there. */export function createAuthEnvironmentAtoms<R, E>(- runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,+ runtime: Atom.AtomRuntime<EnvironmentRegistry | HttpClient.HttpClient | R, E>,) {return {+ createPairingCredential: createEnvironmentCommand(runtime, {+ label: "environment-data:server:auth-create-pairing-credential",+ execute: (input: AuthCreatePairingCredentialInput) =>+ executeConnectedEnvironmentHttpRequest({+ group: "auth",+ method: "POST",+ url: (urls) => urls.pairingCredential(),+ timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,+ request: ({ client, headers }) => client.pairingCredential({ headers, payload: input }),+ }),+ }),+ revokePairingLink: createEnvironmentCommand(runtime, {+ label: "environment-data:server:auth-revoke-pairing-link",+ execute: (input: AuthRevokePairingLinkInput) =>+ executeConnectedEnvironmentHttpRequest({+ group: "auth",+ method: "POST",+ url: (urls) => urls.revokePairingLink(),+ timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,+ request: ({ client, headers }) => client.revokePairingLink({ headers, payload: input }),+ }),+ }),+ revokeClient: createEnvironmentCommand(runtime, {+ label: "environment-data:server:auth-revoke-client",+ execute: (input: AuthRevokeClientSessionInput) =>+ executeConnectedEnvironmentHttpRequest({+ group: "auth",+ method: "POST",+ url: (urls) => urls.revokeClient(),+ timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,+ request: ({ client, headers }) => client.revokeClient({ headers, payload: input }),+ }),+ }),+ revokeOtherClients: createEnvironmentCommand(runtime, {+ label: "environment-data:server:auth-revoke-other-clients",+ execute: (_input: null) =>+ executeConnectedEnvironmentHttpRequest({+ group: "auth",+ method: "POST",+ url: (urls) => urls.revokeOtherClients(),+ timeoutMs: ACCESS_REQUEST_TIMEOUT_MS,+ request: ({ client, headers }) => client.revokeOtherClients({ headers }),+ }).pipe(Effect.map((result) => result.revokedCount)),+ }),accessChanges: createEnvironmentSubscriptionAtomFamily(runtime, {label: "environment-data:server:auth-access-changes",subscribe: (_input: null) =>diff --git a/packages/client-runtime/src/state/environmentHttpAuth.ts b/packages/client-runtime/src/state/environmentHttpAuth.tsindex e3fcbb5ffad..57ec7409540 100644--- a/packages/client-runtime/src/state/environmentHttpAuth.ts+++ b/packages/client-runtime/src/state/environmentHttpAuth.ts@@ -5,12 +5,14 @@ import {ORCHESTRATION_PROTOCOL_VERSION_TEXT,} from "@t3tools/contracts";import * as Result from "effect/Result";+import * as SubscriptionRef from "effect/SubscriptionRef";import { withRelayClientTracing } from "@t3tools/shared/relayTracing";import { FetchHttpClient, type HttpMethod } from "effect/http";-import type { RemoteEnvironmentAuthorization } from "../authorization/service.ts";+import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";import type { PreparedConnection, PreparedHttpAuthorization } from "../connection/model.ts";-import type { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";+import * as EnvironmentSupervisor from "../connection/supervisor.ts";+import * as ManagedRelay from "../relay/managedRelay.ts";import {executeEnvironmentHttpRequest,makeEnvironmentHttpApiGroupClient,@@ -53,7 +55,7 @@ const buildEnvironmentAuthHeaders = Effect.fn("environmentHttpAuth.buildEnvironmauthorization: PreparedHttpAuthorization | null,method: HttpMethod.HttpMethod,url: string,- signer: Option.Option<ManagedRelayDpopSigner["Service"]>,+ signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>,): Effect.fn.Return<EnvironmentHttpAuthHeaders, RemoteEnvironmentAuthFetchError> {if (authorization === null) {return {};@@ -102,6 +104,33 @@ export const executeAuthenticatedEnvironmentHttpRequest = <): executeEnvironmentRequest(input).pipe(Effect.withSpan(ENVIRONMENT_REQUEST_SPAN));+/** Sends the request with this client's own credentials on the supervised environment. */+export const executeConnectedEnvironmentHttpRequest = Effect.fn(+ "clientRuntime.state.executeConnectedEnvironmentHttpRequest",+)(function* <Group extends Parameters<typeof makeEnvironmentHttpApiGroupClient>[1], A, E, R>(+ input: Omit<+ Parameters<typeof executeEnvironmentRequest<Group, A, E, R>>[0],+ "prepared" | "signer" | "remoteAuthorization"+ >,+) {+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;+ const prepared = yield* SubscriptionRef.get(supervisor.prepared);+ if (Option.isNone(prepared)) {+ return yield* new RemoteEnvironmentAuthFetchError({+ message: "The environment is not connected.",+ cause: supervisor.target._tag,+ });+ }+ return yield* executeAuthenticatedEnvironmentHttpRequest({+ ...input,+ prepared: prepared.value,+ signer: yield* Effect.serviceOption(ManagedRelay.ManagedRelayDpopSigner),+ remoteAuthorization: yield* Effect.serviceOption(+ RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,+ ),+ });+});+const ENVIRONMENT_REQUEST_SPAN = "clientRuntime.state.executeAuthenticatedEnvironmentHttpRequest";const executeEnvironmentRequest = Effect.fnUntraced(function* <@@ -111,8 +140,10 @@ const executeEnvironmentRequest = Effect.fnUntraced(function* <R,>(input: {readonly prepared: PreparedConnection;- readonly signer: Option.Option<ManagedRelayDpopSigner["Service"]>;- readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;+ readonly signer: Option.Option<ManagedRelay.ManagedRelayDpopSigner["Service"]>;+ readonly remoteAuthorization?: Option.Option<+ RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]+ >;readonly method: HttpMethod.HttpMethod;/*** The URL to sign, from the group's contract URL builder. It encodes path