fix(clients): disable incompatible environments during discovery (#11990)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-15 17:29:26 -07:00
1 parent 7a368fe7c4
commit 935c55b377
17 files changed
+636 -33

No files matched your search

@@ -1,4 +1,4 @@
import { EnvironmentId } from "@t3tools/contracts";
import { EnvironmentId, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import { describe, expect, it } from "vite-plus/test";
@@ -24,6 +24,32 @@ function relayStatus(
}
describe("available cloud environment presentation", () => {
it("shows an incompatible discovered server before any connection attempt", () => {
const onlineStatus = relayStatus("online");
const status = {
...onlineStatus,
descriptor: {
environmentId: onlineStatus.environmentId,
label: "Preview server",
platform: { os: "darwin", arch: "arm64" },
serverVersion: "2.0.0",
orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1,
capabilities: { repositoryIdentity: true },
},
} satisfies RelayEnvironmentStatusResponse;
expect(
availableCloudEnvironmentPresentation({
isStatusPending: false,
status,
statusError: null,
statusErrorTraceId: null,
}),
).toMatchObject({
connectionState: "unsupported",
statusText: "Client not supported",
});
});
it("presents an online unsaved environment as available, not connected", () => {
expect(
availableCloudEnvironmentPresentation({
@@ -1,5 +1,8 @@
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import {
orchestrationProtocolCompatibilityError,
type EnvironmentConnectionPhase,
} from "@t3tools/client-runtime/connection";
export interface AvailableCloudEnvironmentPresentation {
readonly connectionError: string | null;
@@ -14,6 +17,18 @@ export function availableCloudEnvironmentPresentation(input: {
readonly statusError: string | null;
readonly statusErrorTraceId: string | null;
}): AvailableCloudEnvironmentPresentation {
const compatibilityError =
input.status?.descriptor === undefined
? null
: orchestrationProtocolCompatibilityError(input.status.descriptor);
if (compatibilityError !== null) {
return {
connectionError: compatibilityError.message,
connectionErrorTraceId: null,
connectionState: "unsupported",
statusText: "Client not supported",
};
}
if (input.status?.status === "online") {
return {
connectionError: null,
@@ -219,7 +219,8 @@ function ConnectedCloudEnvironmentRow(props: {
const serverConfig = useAtomValue(
serverEnvironment.configValueAtom(props.environment.environmentId),
);
const enabled = props.environment.isEnabled;
const unsupported = props.environment.connectionState === "unsupported";
const enabled = props.environment.isEnabled && !unsupported;
return (
<Pressable
accessibilityHint="Long press to remove from this device"
@@ -227,15 +228,16 @@ function ConnectedCloudEnvironmentRow(props: {
>
<CloudEnvironmentRowShell
borderTop={props.borderTop}
connectionError={enabled ? props.environment.connectionError : null}
connectionError={enabled || unsupported ? props.environment.connectionError : null}
connectionErrorTraceId={enabled ? props.environment.connectionErrorTraceId : null}
connectionState={enabled ? props.environment.connectionState : "available"}
connectionState={enabled || unsupported ? props.environment.connectionState : "available"}
errorExpanded={props.errorExpanded}
label={props.environment.environmentLabel}
machine={resolveEnvironmentMachineKind(serverConfig)}
onValueChange={props.onSetEnabled}
onToggleError={props.onToggleError}
{...(enabled ? {} : { statusText: "Off" })}
disabled={unsupported}
{...(enabled || unsupported ? {} : { statusText: "Off" })}
value={enabled}
/>
</Pressable>
@@ -270,6 +272,7 @@ function CloudEnvironmentRow(props: {
}
}}
onToggleError={props.onToggleError}
disabled={presentation.connectionState === "unsupported"}
statusText={presentation.statusText}
value={false}
/>
@@ -19,7 +19,7 @@ import { serverEnvironment } from "../../state/server";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
function connectionStatusLabel(environment: ConnectedEnvironmentSummary): string | null {
if (!environment.isEnabled) {
if (!environment.isEnabled && environment.connectionState !== "unsupported") {
return "Off";
}
return connectionStatusText({
@@ -46,10 +46,12 @@ export function ConnectionEnvironmentRow(props: {
const serverConfig = useAtomValue(
serverEnvironment.configValueAtom(props.environment.environmentId),
);
const enabled = props.environment.isEnabled;
const unsupported = props.environment.connectionState === "unsupported";
const enabled = props.environment.isEnabled && !unsupported;
const statusLabel = connectionStatusLabel(props.environment);
const statusTraceId = enabled ? props.environment.connectionErrorTraceId : null;
const hasConnectionFailure = enabled && props.environment.connectionError !== null;
const hasConnectionFailure =
(enabled || unsupported) && props.environment.connectionError !== null;
const isRetrying =
enabled &&
(props.environment.connectionState === "connecting" ||
@@ -77,7 +79,7 @@ export function ConnectionEnvironmentRow(props: {
onPress={props.onToggle}
>
<ConnectionStatusDot
state={enabled ? props.environment.connectionState : "available"}
state={enabled || unsupported ? props.environment.connectionState : "available"}
pulse={isRetrying}
size={8}
/>
@@ -133,6 +135,7 @@ export function ConnectionEnvironmentRow(props: {
</View>
<ThemedSwitch
disabled={unsupported}
onValueChange={(next) => props.onSetEnabled(props.environment.environmentId, next)}
value={enabled}
/>
@@ -128,7 +128,16 @@ export function useRemoteConnections() {
const error = Cause.squash(result.cause);
const message =
error instanceof Error ? error.message : "Failed to pair with the environment.";
setPendingConnectionError(message);
if (
error !== null &&
typeof error === "object" &&
"reason" in error &&
error.reason === "unsupported"
) {
Alert.alert("Client not supported", message);
} else {
setPendingConnectionError(message);
}
} else {
appAtomRegistry.set(connectionPairingUrlAtom, "");
}
@@ -1,6 +1,6 @@
import type { Discovery } from "@t3tools/client-runtime/relay";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { EnvironmentId } from "@t3tools/contracts";
import { EnvironmentId, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult } from "effect/unstable/reactivity";
import { act, useState, type ButtonHTMLAttributes, type ReactNode } from "react";
@@ -178,6 +178,84 @@ describe("cloud onboarding discovery", () => {
expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
});
it("keeps incompatible discoveries unselected until the user enables a compatible server", async () => {
const base = linkedMachines.get(newMachineId)!;
const entry = (protocolVersion: number) => ({
...base,
status: Option.some({
environmentId: newMachineId,
endpoint: base.environment.endpoint,
status: "online" as const,
checkedAt: "2026-09-15T00:00:00Z",
descriptor: {
environmentId: newMachineId,
label: base.environment.label,
platform: { os: "linux" as const, arch: "x64" as const },
serverVersion: "1.0.0",
orchestrationProtocolVersion: protocolVersion,
capabilities: { repositoryIdentity: true },
},
}),
});
discovery.listEnvironments.mockResolvedValue(
new Map([[newMachineId, entry(ORCHESTRATION_PROTOCOL_VERSION + 1)]]),
);
const onSelectionChange = vi.fn();
const autoSelectedComputers = new Set<EnvironmentId>();
function Setup() {
const [selectedIds, setSelectedIds] = useState<ReadonlySet<EnvironmentId>>(
new Set([newMachineId]),
);
return (
<CloudEnvironmentConnectRows
primaryEnvironmentId={null}
savedEnvironments={[]}
showSavedEnvironments
selection={{
autoSelectedComputers,
selectedIds,
onChange: (id, checked) => {
onSelectionChange(id, checked);
setSelectedIds((current) => {
const next = new Set(current);
if (checked) next.add(id);
else next.delete(id);
return next;
});
},
}}
/>
);
}
await act(async () => {
renderer = create(<Setup />);
});
expect(discovery.register).not.toHaveBeenCalled();
expect(onSelectionChange).toHaveBeenCalledWith(newMachineId, false);
expect(renderer!.root.findByType("input").props.checked).toBe(false);
expect(renderer!.root.findByType("input").props.disabled).toBe(true);
expect(renderer!.root.findAllByType("span").flatMap((span) => span.children)).toContain(
"Client not supported",
);
await act(async () => {
await renderer!.root.findByType("input").props.onChange({ target: { checked: true } });
});
expect(discovery.register).not.toHaveBeenCalled();
await act(async () =>
publish({
...discovery.state!,
environments: new Map([[newMachineId, entry(ORCHESTRATION_PROTOCOL_VERSION)]]),
}),
);
expect(discovery.register).not.toHaveBeenCalled();
expect(renderer!.root.findByType("input").props.checked).toBe(false);
expect(renderer!.root.findByType("input").props.disabled).toBe(false);
await act(async () => {
await renderer!.root.findByType("input").props.onChange({ target: { checked: true } });
});
expect(discovery.register).toHaveBeenCalledTimes(1);
});
it("connects and selects discovered computers by default without overwriting deselection", async () => {
discovery.listEnvironments.mockResolvedValue(linkedMachines);
const autoSelectedComputers = new Set<EnvironmentId>();
@@ -3,13 +3,17 @@ import {
type EnvironmentConnectionPresentation,
RelayConnectionRegistration,
RelayConnectionTarget,
orchestrationProtocolCompatibilityError,
} from "@t3tools/client-runtime/connection";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import * as Option from "effect/Option";
import { type ReactNode, useCallback, useEffect, useEffectEvent, useState } from "react";
@@ -29,6 +33,13 @@ import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnec
const EMPTY_DISCOVERY_REFRESH_INTERVAL_MS = 5_000;
function discoveredCompatibilityError(
status: Option.Option<RelayEnvironmentStatusResponse> | undefined,
) {
const descriptor = status === undefined ? undefined : Option.getOrNull(status)?.descriptor;
return descriptor === undefined ? null : orchestrationProtocolCompatibilityError(descriptor);
}
export interface SavedCloudEnvironmentConnection {
readonly environmentId: EnvironmentId;
readonly connection: EnvironmentConnectionPresentation;
@@ -119,6 +130,12 @@ export function CloudEnvironmentConnectRows({
}, [refreshRelayEnvironments, refreshWhileEmpty, onDiscoveryReady]);
const connectEnvironment = async (environment: RelayClientEnvironmentRecord) => {
if (
discoveredCompatibilityError(
environmentsState.environments.get(environment.environmentId)?.status,
) !== null
)
return false;
setConnectingEnvironmentIds((current) => new Set([...current, environment.environmentId]));
const result = await connectRelayEnvironment(environment);
setConnectingEnvironmentIds((current) => {
@@ -166,8 +183,17 @@ export function CloudEnvironmentConnectRows({
const selectNewComputers = useEffectEvent(() => {
const seen = selection?.autoSelectedComputers;
if (!selection || !seen) return;
for (const { environment } of visibleEnvironments) {
for (const { environment, status, availability } of visibleEnvironments) {
const id = environment.environmentId;
if (availability === "checking") continue;
if (
discoveredCompatibilityError(status) !== null ||
savedById.get(id)?.connection.phase === "unsupported"
) {
seen.add(id);
if (selection.selectedIds.has(id)) selection.onChange(id, false);
continue;
}
if (seen.has(id)) continue;
seen.add(id);
selection.onChange(id, true);
@@ -265,11 +291,20 @@ export function CloudEnvironmentConnectRows({
return empty;
}
return visibleEnvironments.map(({ environment, availability, error }) => {
return visibleEnvironments.map(({ environment, availability, error, status }) => {
const savedEnvironment = savedById.get(environment.environmentId);
const savedConnection = savedEnvironment
? presentSavedCloudEnvironmentConnection(savedEnvironment.connection)
: null;
const compatibilityError = discoveredCompatibilityError(status);
const unsupported =
compatibilityError !== null || savedEnvironment?.connection.phase === "unsupported";
const savedConnection = unsupported
? presentSavedCloudEnvironmentConnection({
phase: "unsupported",
error: compatibilityError?.message ?? savedEnvironment?.connection.error ?? null,
traceId: null,
})
: savedEnvironment
? presentSavedCloudEnvironmentConnection(savedEnvironment.connection)
: null;
const dotClassName = savedConnection
? savedConnection.tone === "connected"
? "bg-success"
@@ -302,9 +337,10 @@ export function CloudEnvironmentConnectRows({
className="flex cursor-pointer items-center gap-3 rounded-lg border border-border bg-background px-3 py-2.5 has-disabled:cursor-default"
>
<Checkbox
checked={selection.selectedIds.has(environment.environmentId)}
disabled={connectingEnvironmentIds.has(environment.environmentId)}
checked={!unsupported && selection.selectedIds.has(environment.environmentId)}
disabled={unsupported || connectingEnvironmentIds.has(environment.environmentId)}
onCheckedChange={async (checked) => {
if (unsupported) return;
selection.onChange(environment.environmentId, checked);
if (checked && !savedEnvironment) {
const connected = await connectEnvironment(environment);
@@ -1444,7 +1444,8 @@ function savedBackendStatus(environment: EnvironmentPresentation): {
readonly text: string;
readonly tone: "muted" | "error";
} {
if (!environment.entry.enabled) return { text: "Off", tone: "muted" };
if (!environment.entry.enabled && environment.connection.phase !== "unsupported")
return { text: "Off", tone: "muted" };
const { connection } = environment;
switch (connection.phase) {
case "connected":
@@ -1482,7 +1483,8 @@ function SavedBackendListRow({
onRemove,
}: SavedBackendListRowProps) {
const environmentId = environment.environmentId;
const enabled = environment.entry.enabled;
const unsupported = environment.connection.phase === "unsupported";
const enabled = environment.entry.enabled && !unsupported;
const isConnected = environment.connection.phase === "connected";
const isRemoving = removingEnvironmentId === environmentId;
const errorTraceId = environment.connection.traceId;
@@ -1545,7 +1547,10 @@ function SavedBackendListRow({
<span
className={cn(
"block truncate",
enabled && status.tone === "error" && !resumingServerUpdate && "text-destructive",
(enabled || unsupported) &&
status.tone === "error" &&
!resumingServerUpdate &&
"text-destructive",
)}
/>
}
@@ -1553,7 +1558,7 @@ function SavedBackendListRow({
{subtitleText}
</TooltipTrigger>
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
{enabled ? connectionStatusText(environment.connection) : "Switched off"}
{enabled || unsupported ? connectionStatusText(environment.connection) : "Switched off"}
{versionMismatch
? `\nUpdate available: ${versionMismatch.serverVersion} → ${versionMismatch.clientVersion}`
: ""}
@@ -1586,13 +1591,15 @@ function SavedBackendListRow({
<Switch
size="sm"
checked={enabled}
disabled={isRemoving}
disabled={isRemoving || unsupported}
aria-label={`${enabled ? "Switch off" : "Switch on"} ${environment.label}`}
onCheckedChange={(checked) => onSetEnabled(environmentId, checked)}
/>
}
/>
<TooltipPopup side="top">{enabled ? "Switch off" : "Switch on"}</TooltipPopup>
<TooltipPopup side="top">
{unsupported ? "Client not supported" : enabled ? "Switch off" : "Switch on"}
</TooltipPopup>
</Tooltip>
<Menu>
<MenuTrigger
@@ -41,6 +41,8 @@ export interface ConnectionCatalogEntry {
readonly profile: Option.Option<ConnectionProfile>;
/** False when the user switched the environment off: saved, but never connects. */
readonly enabled: boolean;
/** Discovery rejection stays visible while the saved connection is switched off. */
readonly unsupportedReason?: string;
}
export class BearerConnectionCredential extends Schema.TaggedClass<BearerConnectionCredential>()(
@@ -21,3 +21,5 @@ export {
} from "./registry.ts";
export { EnvironmentSupervisor, type EnvironmentSupervisorOptions } from "./supervisor.ts";
export * as Wakeups from "./wakeups.ts";
export { orchestrationProtocolCompatibilityError } from "./compatibility.ts";
@@ -1,6 +1,10 @@
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import * as Option from "effect/Option";
import * as SubscriptionRef from "effect/SubscriptionRef";
import { orchestrationProtocolCompatibilityError } from "./compatibility.ts";
import * as ConnectionResolver from "./resolver.ts";
import * as ConnectionDriver from "./driver.ts";
@@ -11,6 +15,49 @@ import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
import * as RpcSession from "../rpc/session.ts";
export const watchDiscoveredCompatibility = Effect.fn("connection.watchDiscoveredCompatibility")(
function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
const discovery = yield* RelayEnvironmentDiscovery.RelayEnvironmentDiscovery;
const seenChecks = new Map<string, RelayEnvironmentStatusResponse>();
yield* Stream.merge(
SubscriptionRef.changes(discovery.state),
SubscriptionRef.changes(registry.entries),
).pipe(
Stream.runForEach(() =>
Effect.gen(function* () {
const current = yield* SubscriptionRef.get(discovery.state);
if (!current.refreshing) {
for (const environmentId of seenChecks.keys()) {
if (!current.environments.has(environmentId)) seenChecks.delete(environmentId);
}
}
for (const entry of current.environments.values()) {
const status = Option.getOrNull(entry.status);
const descriptor = status?.descriptor;
if (status === null || descriptor === undefined) continue;
const environmentId = entry.environment.environmentId;
const previous = seenChecks.get(environmentId);
const fresh =
previous?.checkedAt !== status.checkedAt ||
(previous.descriptor?.orchestrationProtocolVersion ?? 1) !==
(descriptor.orchestrationProtocolVersion ?? 1) ||
previous.descriptor?.serverVersion !== descriptor.serverVersion;
const error = orchestrationProtocolCompatibilityError(descriptor);
// A replayed health result must not clear a newer socket rejection.
if (error !== null || fresh) yield* registry.setCompatibility(environmentId, error);
seenChecks.set(environmentId, status);
}
}).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not apply discovered environment compatibility.", { error }),
),
),
),
);
},
);
export function layerWithOptions(options: RpcSession.RpcSessionOptions) {
const driverLayer = ConnectionDriver.layer.pipe(
Layer.provide(Layer.mergeAll(ConnectionResolver.layer, RpcSession.layerWithOptions(options))),
@@ -26,6 +73,7 @@ export function layerWithOptions(options: RpcSession.RpcSessionOptions) {
Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
const platformSource = yield* PlatformConnectionSource.PlatformConnectionSource;
yield* watchDiscoveredCompatibility().pipe(Effect.forkScoped);
yield* registry.start;
yield* platformSource.registrations.pipe(
Stream.runForEach(registry.reconcilePlatform),
@@ -1,4 +1,8 @@
import { AuthStandardClientScopes, EnvironmentId } from "@t3tools/contracts";
import {
AuthStandardClientScopes,
EnvironmentId,
ORCHESTRATION_PROTOCOL_VERSION,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -28,7 +32,7 @@ const CLIENT_PRESENTATION_LAYER = Layer.succeed(
function pairingHttpLayer(
calls: Array<{ readonly url: string; readonly init: RequestInit }>,
options?: { readonly failDescriptor?: boolean },
options?: { readonly failDescriptor?: boolean; readonly protocolVersion?: number },
) {
const fetchFn = ((input, init = {}) => {
const url = String(input);
@@ -49,6 +53,7 @@ function pairingHttpLayer(
arch: "x64",
},
serverVersion: "0.0.0-test",
orchestrationProtocolVersion: options?.protocolVersion ?? ORCHESTRATION_PROTOCOL_VERSION,
capabilities: {
repositoryIdentity: true,
},
@@ -118,6 +123,28 @@ describe("connection onboarding", () => {
}),
);
it.effect("rejects an incompatible server without consuming the pairing credential", () =>
Effect.gen(function* () {
const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
const error = yield* preparePairingRegistration({
host: "remote.example.test",
pairingCode: "pairing-token",
}).pipe(
Effect.provide(
Layer.mergeAll(
CLIENT_PRESENTATION_LAYER,
pairingHttpLayer(calls, { protocolVersion: ORCHESTRATION_PROTOCOL_VERSION + 1 }),
),
),
Effect.flip,
);
expect(error).toMatchObject({ reason: "unsupported" });
expect(calls.map((call) => call.url)).toEqual([
"https://remote.example.test/.well-known/t3/environment",
]);
}),
);
it.effect("does not consume a pairing credential when descriptor discovery fails", () =>
Effect.gen(function* () {
const calls: Array<{ readonly url: string; readonly init: RequestInit }> = [];
@@ -31,6 +31,7 @@ import {
} from "./model.ts";
import * as Persistence from "../platform/persistence.ts";
import * as EnvironmentRegistry from "./registry.ts";
import { orchestrationProtocolCompatibilityError } from "./compatibility.ts";
export interface PairingConnectionInput {
readonly pairingUrl?: string;
@@ -91,6 +92,8 @@ export const preparePairingRegistration = Effect.fn(
const descriptor = yield* fetchRemoteEnvironmentDescriptor({
httpBaseUrl: target.httpBaseUrl,
}).pipe(Effect.mapError(mapRemoteEnvironmentError));
const compatibilityError = orchestrationProtocolCompatibilityError(descriptor);
if (compatibilityError !== null) return yield* compatibilityError;
const access = yield* bootstrapRemoteBearerSession({
httpBaseUrl: target.httpBaseUrl,
credential: target.credential,
@@ -1,6 +1,8 @@
import {
type DesktopSshEnvironmentTarget,
EnvironmentId,
ORCHESTRATION_PROTOCOL_VERSION,
type ExecutionEnvironmentDescriptor,
type OrchestrationShellSnapshot,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
@@ -36,6 +38,7 @@ import * as ConnectionCredentialStore from "./credentialStore.ts";
import * as ConnectionDriver from "./driver.ts";
import {
ConnectionTransientError,
ConnectionBlockedError,
BearerConnectionTarget,
PrimaryConnectionTarget,
RelayConnectionTarget,
@@ -54,6 +57,9 @@ import {
import * as RpcSession from "../rpc/session.ts";
import * as EnvironmentSupervisor from "./supervisor.ts";
import * as ConnectionWakeups from "./wakeups.ts";
import { watchDiscoveredCompatibility } from "./layer.ts";
import * as RelayEnvironmentDiscovery from "../relay/discovery.ts";
import type { RelayEnvironmentStatusResponse } from "@t3tools/contracts/relay";
import { runDesktopCommitWithReconnectObserver } from "../state/server.ts";
const TARGET = new PrimaryConnectionTarget({
@@ -137,6 +143,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
initialProfiles: ReadonlyArray<ConnectionProfile> = [],
initialCredentials: ReadonlyArray<readonly [string, ConnectionCredential]> = [],
options?: {
readonly prepareError?: ConnectionBlockedError;
readonly beforeSessionConnect?: (environmentId: EnvironmentId) => Effect.Effect<void>;
readonly beforeRegistrationRegister?: (
registration: ConnectionRegistration,
@@ -368,6 +375,7 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
target,
};
yield* reportProgress({ stage: "preparing" });
if (options?.prepareError) return yield* options.prepareError;
yield* reportProgress({ stage: "opening", prepared });
yield* options?.beforeSessionConnect?.(target.environmentId) ?? Effect.void;
const closed = yield* Deferred.make<never, ConnectionTransientError>();
@@ -673,6 +681,212 @@ describe("EnvironmentRegistry", () => {
}),
);
it.effect("only a fresh health check for the rejected environment unlocks it", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([RELAY_TARGET], [], [], {
initialDisabled: [RELAY_TARGET.environmentId],
});
const descriptor = (environmentId: EnvironmentId): ExecutionEnvironmentDescriptor => ({
environmentId,
label: "Server",
platform: { os: "linux", arch: "x64" },
serverVersion: "1.0.0",
orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION,
capabilities: { repositoryIdentity: true },
});
const discovered = (
value: ExecutionEnvironmentDescriptor,
checkedAt = "2026-09-15T00:00:00Z",
) => {
const environment = {
environmentId: value.environmentId,
label: value.label,
endpoint: {
httpBaseUrl: "https://relay.example.test",
wsBaseUrl: "wss://relay.example.test",
providerKind: "manual" as const,
},
linkedAt: "2026-09-15T00:00:00Z",
};
const status: RelayEnvironmentStatusResponse = {
environmentId: value.environmentId,
endpoint: environment.endpoint,
status: "online",
checkedAt,
descriptor: value,
};
return {
environment,
availability: "online" as const,
status: Option.some(status),
error: Option.none(),
};
};
const original = discovered(descriptor(RELAY_TARGET.environmentId));
const discoveryState =
yield* SubscriptionRef.make<RelayEnvironmentDiscovery.RelayEnvironmentDiscoveryState>({
...RelayEnvironmentDiscovery.EMPTY_RELAY_ENVIRONMENT_DISCOVERY_STATE,
environments: new Map([[RELAY_TARGET.environmentId, original]]),
});
const initial = yield* Deferred.make<void>();
const unrelated = yield* Deferred.make<void>();
const replayed = yield* Deferred.make<void>();
const refreshed = yield* Deferred.make<void>();
let firstEnvironmentCalls = 0;
let secondEnvironmentCalls = 0;
yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
yield* watchDiscoveredCompatibility().pipe(
Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, {
...registry,
setCompatibility: (environmentId, error) =>
registry.setCompatibility(environmentId, error).pipe(
Effect.andThen(
Effect.gen(function* () {
if (environmentId === RELAY_TARGET.environmentId) {
firstEnvironmentCalls += 1;
yield* Deferred.succeed(
firstEnvironmentCalls === 1 ? initial : refreshed,
undefined,
);
} else {
secondEnvironmentCalls += 1;
yield* Deferred.succeed(
secondEnvironmentCalls === 1 ? unrelated : replayed,
undefined,
);
}
}),
),
),
}),
Effect.provideService(
RelayEnvironmentDiscovery.RelayEnvironmentDiscovery,
RelayEnvironmentDiscovery.RelayEnvironmentDiscovery.of({
state: discoveryState,
refresh: Effect.void,
}),
),
Effect.forkScoped,
);
yield* Deferred.await(initial);
const error = new ConnectionBlockedError({
reason: "unsupported",
detail: "Socket discovered a newer protocol.",
});
yield* registry.setCompatibility(RELAY_TARGET.environmentId, error);
yield* SubscriptionRef.update(discoveryState, (state) => ({
...state,
environments: new Map(state.environments).set(
SECOND_TARGET.environmentId,
discovered(descriptor(SECOND_TARGET.environmentId)),
),
}));
yield* Deferred.await(unrelated);
expect(
(yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId)
?.unsupportedReason,
).toBe(error.message);
yield* SubscriptionRef.update(discoveryState, (state) => ({
...state,
refreshing: true,
environments: new Map(),
}));
yield* SubscriptionRef.update(discoveryState, (state) => ({
...state,
refreshing: false,
environments: new Map([
[RELAY_TARGET.environmentId, discovered(descriptor(RELAY_TARGET.environmentId))],
[
SECOND_TARGET.environmentId,
discovered(descriptor(SECOND_TARGET.environmentId), "2026-09-15T00:01:00Z"),
],
]),
}));
yield* Deferred.await(replayed);
expect(
(yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId)
?.unsupportedReason,
).toBe(error.message);
yield* SubscriptionRef.update(discoveryState, (state) => ({
...state,
environments: new Map(state.environments).set(
RELAY_TARGET.environmentId,
discovered(descriptor(RELAY_TARGET.environmentId), "2026-09-15T00:02:00Z"),
),
}));
yield* Deferred.await(refreshed);
expect(
(yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId),
).toMatchObject({ enabled: false });
expect(
(yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId)
?.unsupportedReason,
).toBeUndefined();
}).pipe(Effect.provide(harness.layer), Effect.scoped);
}),
);
it.effect("discovery keeps unsupported environments off until compatibility changes", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([RELAY_TARGET], [], [], {
initialDisabled: [RELAY_TARGET.environmentId],
});
yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
yield* registry.start;
const error = new ConnectionBlockedError({
reason: "unsupported",
detail: "Use a compatible client.",
});
yield* registry.setCompatibility(RELAY_TARGET.environmentId, error);
const entry = (yield* SubscriptionRef.get(registry.entries)).get(
RELAY_TARGET.environmentId,
);
expect(entry).toMatchObject({ enabled: false, unsupportedReason: error.message });
expect(
yield* Effect.flip(registry.setEnabled(RELAY_TARGET.environmentId, true)),
).toMatchObject({ reason: "unsupported" });
expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
yield* registry.setCompatibility(RELAY_TARGET.environmentId, null);
expect(
(yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId)?.enabled,
).toBe(false);
yield* registry.setEnabled(RELAY_TARGET.environmentId, true);
yield* awaitConnectionState(
registry,
RELAY_TARGET.environmentId,
(state) => state.phase === "connected",
);
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("a socket preflight rejection persists the connection as switched off", () =>
Effect.gen(function* () {
const error = new ConnectionBlockedError({
reason: "unsupported",
detail: "Use a compatible client.",
});
const harness = yield* makeHarness([RELAY_TARGET], [], [], { prepareError: error });
yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
yield* registry.start;
yield* SubscriptionRef.changes(registry.entries).pipe(
Stream.filter((entries) => entries.get(RELAY_TARGET.environmentId)?.enabled === false),
Stream.take(1),
Stream.runDrain,
);
expect((yield* Ref.get(harness.storedDisabled)).has(RELAY_TARGET.environmentId)).toBe(true);
expect(
(yield* SubscriptionRef.get(registry.entries)).get(RELAY_TARGET.environmentId)
?.unsupportedReason,
).toBe(error.message);
expect(yield* Ref.get(harness.sessions)).toHaveLength(0);
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("switching an environment off disconnects it and persists the flag", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([RELAY_TARGET]);
@@ -1095,6 +1309,55 @@ describe("EnvironmentRegistry", () => {
}),
);
it.effect("platform refreshes preserve unsupported state for the same endpoint", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([]);
yield* Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
const registration = new PrimaryConnectionRegistration({ target: TARGET });
yield* registry.registerPlatform(registration);
yield* awaitConnectionState(
registry,
TARGET.environmentId,
(state) => state.phase === "connected",
);
const error = new ConnectionBlockedError({
reason: "unsupported",
detail: "Use a compatible client.",
});
yield* registry.setCompatibility(TARGET.environmentId, error);
yield* awaitConnectionState(
registry,
TARGET.environmentId,
(state) => state.phase === "available",
);
yield* registry.registerPlatform(registration);
yield* registry.reconcilePlatform([registration]);
expect(
(yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId),
).toMatchObject({ enabled: false, unsupportedReason: error.message });
expect(yield* Ref.get(harness.sessions)).toHaveLength(1);
yield* registry.registerPlatform(
new PrimaryConnectionRegistration({
target: new PrimaryConnectionTarget({
...TARGET,
httpBaseUrl: "https://changed.example.test",
}),
}),
);
yield* awaitConnectionState(
registry,
TARGET.environmentId,
(state) => state.phase === "connected",
);
expect(
(yield* SubscriptionRef.get(registry.entries)).get(TARGET.environmentId)
?.unsupportedReason,
).toBeUndefined();
}).pipe(Effect.provide(harness.layer));
}),
);
it.effect("retains a healthy runtime when the platform repeats an identical registration", () =>
Effect.gen(function* () {
const harness = yield* makeHarness([]);
@@ -30,6 +30,7 @@ import type {
NetworkStatus,
SupervisorConnectionState,
} from "./model.ts";
import { ConnectionBlockedError } from "./model.ts";
import * as Persistence from "../platform/persistence.ts";
import * as EnvironmentSupervisor from "./supervisor.ts";
import * as ConnectionDriver from "./driver.ts";
@@ -104,8 +105,14 @@ export class EnvironmentRegistry extends Context.Service<
enabled: boolean,
) => Effect.Effect<
void,
EnvironmentNotRegisteredError | Persistence.ConnectionPersistenceError
| EnvironmentNotRegisteredError
| Persistence.ConnectionPersistenceError
| ConnectionBlockedError
>;
readonly setCompatibility: (
environmentId: EnvironmentId,
error: ConnectionBlockedError | null,
) => Effect.Effect<void, Persistence.ConnectionPersistenceError>;
readonly state: (
environmentId: EnvironmentId,
) => Effect.Effect<SupervisorConnectionState, EnvironmentNotRegisteredError>;
@@ -291,6 +298,21 @@ export const make = Effect.gen(function* () {
next.set(environmentId, { entry, supervisor, scope });
return next;
});
yield* SubscriptionRef.changes(supervisor.state).pipe(
Stream.runForEach((state) =>
state.phase === "blocked" && state.lastFailure?.reason === "unsupported"
? setCompatibility(environmentId, state.lastFailure).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not disable an unsupported environment.", {
environmentId,
error,
}),
),
)
: Effect.void,
),
Effect.forkIn(scope),
);
return supervisor;
}),
),
@@ -426,7 +448,16 @@ export const make = Effect.gen(function* () {
// Editing a saved environment must preserve its disabled state.
const previous = (yield* SubscriptionRef.get(entries)).get(environmentId);
const entry: ConnectionCatalogEntry =
previous === undefined ? registered : { ...registered, enabled: previous.enabled };
previous === undefined
? registered
: {
...registered,
enabled: previous.enabled,
...(previous.unsupportedReason !== undefined &&
gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(registered)
? { unsupportedReason: previous.unsupportedReason }
: {}),
};
if (
previous !== undefined &&
gitHubRoutingConnectionKey(previous) !== gitHubRoutingConnectionKey(entry)
@@ -454,12 +485,17 @@ export const make = Effect.gen(function* () {
const installPlatformRegistration = Effect.fn("EnvironmentRegistry.installPlatformRegistration")(
function* (registration: PlatformConnectionRegistration) {
const entry = connectionRegistrationCatalogEntry(registration);
const target = entry.target;
const registered = connectionRegistrationCatalogEntry(registration);
const target = registered.target;
yield* withLeaseLock(
target.environmentId,
Effect.gen(function* () {
const previous = (yield* SubscriptionRef.get(entries)).get(target.environmentId);
const entry: ConnectionCatalogEntry =
previous?.unsupportedReason !== undefined &&
gitHubRoutingConnectionKey(previous) === gitHubRoutingConnectionKey(registered)
? { ...registered, enabled: false, unsupportedReason: previous.unsupportedReason }
: registered;
const persistedTarget = (yield* Ref.get(persistedTargetsByEnvironment)).get(
target.environmentId,
);
@@ -714,6 +750,12 @@ export const make = Effect.gen(function* () {
environmentId,
Effect.gen(function* () {
const entry = yield* getEntry(environmentId);
if (enabled && entry.unsupportedReason !== undefined) {
return yield* new ConnectionBlockedError({
reason: "unsupported",
detail: entry.unsupportedReason,
});
}
if (entry.enabled === enabled) {
return;
}
@@ -794,6 +836,40 @@ export const make = Effect.gen(function* () {
Effect.forkScoped,
);
const setCompatibility = Effect.fn("EnvironmentRegistry.setCompatibility")(function* (
environmentId: EnvironmentId,
error: ConnectionBlockedError | null,
) {
yield* withLeaseLock(
environmentId,
Effect.gen(function* () {
const entry = (yield* SubscriptionRef.get(entries)).get(environmentId);
if (entry === undefined || entry.unsupportedReason === (error?.message ?? undefined))
return;
const { unsupportedReason: _previousReason, ...rest } = entry;
const next: ConnectionCatalogEntry =
error === null ? rest : { ...rest, enabled: false, unsupportedReason: error.message };
if (
error !== null &&
entry.enabled &&
!(yield* Ref.get(platformEnvironmentIds)).has(environmentId)
) {
yield* registrations.setEnabled(environmentId, false);
}
const lease = (yield* SubscriptionRef.get(serviceScopes)).get(environmentId);
if (lease !== undefined) {
yield* SubscriptionRef.update(serviceScopes, (current) =>
new Map(current).set(environmentId, { ...lease, entry: next }),
);
if (error !== null) yield* lease.supervisor.disconnect;
}
yield* SubscriptionRef.update(entries, (current) =>
new Map(current).set(environmentId, next),
);
}),
);
});
return EnvironmentRegistry.of({
entries,
networkStatus,
@@ -805,6 +881,7 @@ export const make = Effect.gen(function* () {
removeRelayEnvironments,
retryNow,
setEnabled,
setCompatibility,
state,
stateChanges,
run,
@@ -41,7 +41,10 @@ export function createEnvironmentPresentationAtoms<E>(input: {
);
return {
entry,
connection: presentEnvironmentConnection(state),
connection:
entry.unsupportedReason === undefined
? presentEnvironmentConnection(state)
: { phase: "unsupported", error: entry.unsupportedReason, traceId: null },
serverConfig: get(input.serverConfigValueAtom(environmentId)),
} satisfies EnvironmentPresentation;
}).pipe(Atom.withLabel(`environment-presentation:${environmentId}`)),
@@ -182,6 +182,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?
removeRelayEnvironments: () => Effect.die("Unexpected environment removal"),
retryNow: () => Effect.void,
setEnabled: () => Effect.die("Unexpected environment toggle"),
setCompatibility: () => Effect.die("Unexpected compatibility update"),
state: () => SubscriptionRef.get(supervisor.state),
stateChanges: () => SubscriptionRef.changes(supervisor.state),
run: (_environmentId, effect) =>