perf(client-runtime): halve server config bootstrap traffic (#8367)

Reuse one server config subscription for session bootstrap and live updates.

Preserve environment theme opt-in, replay, deletion, slow subscriber recovery, and config stream failure handling.

Co-authored-by: Adamulek123 <[email protected]>
This commit is contained in:
Adamulek123 authored and GitHub committed 2026-09-01 04:23:50 -07:00
1 parent e86604d337
commit b883fc066e
20 files changed
+1053 -151

No files matched your search

@@ -91,6 +91,7 @@ function registryLayer(options?: {
const session: RpcSession = {
client,
initialConfig: Effect.never,
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
+4 -1
View File
@@ -30,7 +30,10 @@ type ConnectionLayerSource =
| typeof backgroundActivityObserverLayer
| typeof backgroundActivityReporterLayer;
const providedClientConnectionLayer = Layer.merge(Connection.layer, snapshotLoaderLayer).pipe(
const providedClientConnectionLayer = Layer.merge(
Connection.layerWithOptions({ environmentThemes: true }),
snapshotLoaderLayer,
).pipe(
Layer.provideMerge(
Layer.mergeAll(
runtimeContextLayer,
+25 -26
View File
@@ -15,30 +15,29 @@ const resolverLayer = ConnectionResolver.layer.pipe(
Layer.provide(RemoteEnvironmentAuthorization.layer),
);
const driverLayer = ConnectionDriver.layer.pipe(
Layer.provide(Layer.mergeAll(resolverLayer, RpcSession.layer)),
);
export function layerWithOptions(options: RpcSession.RpcSessionOptions) {
const driverLayer = ConnectionDriver.layer.pipe(
Layer.provide(Layer.mergeAll(resolverLayer, RpcSession.layerWithOptions(options))),
);
const registryLayer = EnvironmentRegistry.layer.pipe(Layer.provide(driverLayer));
const onboardingLayer = ConnectionOnboarding.layer.pipe(Layer.provide(registryLayer));
const connectionServicesLayer = Layer.mergeAll(
registryLayer,
RelayEnvironmentDiscovery.layer,
onboardingLayer,
);
const connectionStartupLayer = Layer.effectDiscard(
Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
const platformSource = yield* PlatformConnectionSource.PlatformConnectionSource;
yield* registry.start;
yield* platformSource.registrations.pipe(
Stream.runForEach(registry.reconcilePlatform),
Effect.forkScoped,
);
}).pipe(Effect.withSpan("clientRuntime.connection.application.start")),
);
return connectionStartupLayer.pipe(Layer.provideMerge(connectionServicesLayer));
}
const registryLayer = EnvironmentRegistry.layer.pipe(Layer.provide(driverLayer));
const onboardingLayer = ConnectionOnboarding.layer.pipe(Layer.provide(registryLayer));
const connectionServicesLayer = Layer.mergeAll(
registryLayer,
RelayEnvironmentDiscovery.layer,
onboardingLayer,
);
const connectionStartupLayer = Layer.effectDiscard(
Effect.gen(function* () {
const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
const platformSource = yield* PlatformConnectionSource.PlatformConnectionSource;
yield* registry.start;
yield* platformSource.registrations.pipe(
Stream.runForEach(registry.reconcilePlatform),
Effect.forkScoped,
);
}).pipe(Effect.withSpan("clientRuntime.connection.application.start")),
);
export const layer = connectionStartupLayer.pipe(Layer.provideMerge(connectionServicesLayer));
export const layer = layerWithOptions({});
@@ -356,6 +356,8 @@ const makeHarness = Effect.fn("TestEnvironmentRegistry.makeHarness")(function* (
Effect.succeed({
client: {} as RpcSession.RpcSession["client"],
initialConfig: Effect.die(new Error("Config is not used by registry tests.")),
subscribeServerConfig: () =>
Stream.die(new Error("Config is not used by registry tests.")),
ready: Effect.void,
probe: Effect.void,
closed: Deferred.await(closed),
@@ -163,6 +163,7 @@ const makeHarness = Effect.fn("TestConnectionHarness.make")(function* (options?:
Effect.succeed({
client: TEST_RPC_CLIENT,
initialConfig: Effect.die(new Error("Initial config is not used by supervisor tests.")),
subscribeServerConfig: (input) => TEST_RPC_CLIENT.subscribeServerConfig(input),
ready: options?.ready?.(attempt) ?? Effect.void,
probe: options?.probe?.(attempt) ?? Effect.void,
closed: Deferred.await(closed),
@@ -57,6 +57,7 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
const session: RpcSession.RpcSession = {
client,
initialConfig: Effect.never,
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
@@ -1,6 +1,8 @@
import {
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
type RelayClientInstallProgressEvent,
type ServerConfigStreamEvent,
WS_METHODS,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
@@ -47,6 +49,7 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
return {
client,
initialConfig: Effect.never,
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
@@ -77,6 +80,39 @@ const makeHarness = Effect.fn("TestEnvironmentRpc.makeHarness")(function* () {
});
describe("environment RPC", () => {
it.effect("reuses the session config stream instead of opening a duplicate subscription", () =>
Effect.gen(function* () {
const event: ServerConfigStreamEvent = {
version: 1,
type: "settingsUpdated",
payload: { settings: DEFAULT_SERVER_SETTINGS },
};
let duplicateSubscriptions = 0;
const client = {
[WS_METHODS.subscribeServerConfig]: () => {
duplicateSubscriptions += 1;
return Stream.never;
},
} as unknown as WsRpcProtocolClient;
const { activeSession, supervisor } = yield* makeHarness();
yield* SubscriptionRef.set(
activeSession,
Option.some({
...session(client),
subscribeServerConfig: () => Stream.succeed(event),
}),
);
const received = yield* subscribe(WS_METHODS.subscribeServerConfig, {}).pipe(
Stream.runHead,
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
);
expect(received).toEqual(Option.some(event));
expect(duplicateSubscriptions).toBe(0);
}),
);
it.effect("observes unary requests until they complete", () =>
Effect.gen(function* () {
const observations: string[] = [];
+5 -1
View File
@@ -203,7 +203,11 @@ export function subscribeDynamic<TTag extends EnvironmentSubscriptionRpcTag>(
Option.match({
onNone: () => Stream.empty,
onSome: (session) => {
const method = session.client[tag] as (
const method = (
tag === WS_METHODS.subscribeServerConfig
? session.subscribeServerConfig
: session.client[tag]
) as (
input: EnvironmentRpcInput<TTag>,
) => Stream.Stream<
EnvironmentRpcStreamValue<TTag>,
+675 -23
View File
@@ -1,24 +1,41 @@
import {
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
ProviderDriverKind,
ProviderInstanceId,
ServerConfig,
type ServerConfig as ServerConfigType,
ServerConfigStreamEvent,
type ServerConfigStreamEvent as ServerConfigStreamEventType,
WS_METHODS,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as TestClock from "effect/testing/TestClock";
import * as Socket from "effect/unstable/socket/Socket";
import {
AVAILABLE_CONNECTION_STATE,
ConnectionBlockedError,
ConnectionTransientError,
PrimaryConnectionTarget,
type PreparedConnection,
} from "../connection/model.ts";
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
import * as Persistence from "../platform/persistence.ts";
import * as RpcSession from "./session.ts";
import { makeEnvironmentServerConfigState } from "../state/server.ts";
import { applyServerConfigProjection } from "../state/serverConfigProjection.ts";
type SocketEventType = "open" | "message" | "close" | "error";
type SocketEvent = {
@@ -139,10 +156,24 @@ const RpcRequest = Schema.TaggedStruct("Request", {
tag: Schema.String,
});
const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
const decodeRpcRequest = Schema.decodeUnknownSync(RpcRequest);
const isRpcRequest = Schema.is(RpcRequest);
const isPing = Schema.is(Schema.Struct({ _tag: Schema.Literal("Ping") }));
const encodeJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
const encodeServerConfig = Schema.encodeSync(ServerConfig);
const encodeServerConfigStreamEvent = Schema.encodeSync(ServerConfigStreamEvent);
const encodeDefect = Schema.encodeSync(Schema.Defect());
const ENCODED_SERVER_CONFIG = encodeServerConfig(SERVER_CONFIG);
const THEME_SERVER_CONFIG: ServerConfigType = {
...SERVER_CONFIG,
environment: {
...SERVER_CONFIG.environment,
capabilities: {
...SERVER_CONFIG.environment.capabilities,
environmentThemes: true,
},
},
};
const ENCODED_THEME_SERVER_CONFIG = encodeServerConfig(THEME_SERVER_CONFIG);
const LEGACY_SERVER_CONFIG = {
...ENCODED_SERVER_CONFIG,
environment: {
@@ -153,23 +184,26 @@ const LEGACY_SERVER_CONFIG = {
},
};
const makeFactory = Effect.fn("TestRpcSessionFactory.make")(function* () {
const makeFactory = Effect.fn("TestRpcSessionFactory.make")(function* (
options: RpcSession.RpcSessionOptions = {},
) {
const sockets: TestWebSocket[] = [];
const constructorLayer = Layer.succeed(Socket.WebSocketConstructor, (url) => {
const socket = new TestWebSocket(url);
sockets.push(socket);
return socket as unknown as globalThis.WebSocket;
});
const layer = RpcSession.layer.pipe(Layer.provide(constructorLayer));
const layer = RpcSession.layerWithOptions(options).pipe(Layer.provide(constructorLayer));
const factory = yield* RpcSession.RpcSessionFactory.pipe(Effect.provide(layer));
return { factory, sockets };
});
const awaitSocket = Effect.fn("TestRpcSessionFactory.awaitSocket")(function* (
sockets: ReadonlyArray<TestWebSocket>,
index = 0,
) {
for (let attempt = 0; attempt < 100; attempt += 1) {
const socket = sockets[0];
const socket = sockets[index];
if (socket) {
return socket;
}
@@ -183,9 +217,9 @@ const awaitRequest = Effect.fn("TestRpcSessionFactory.awaitRequest")(function* (
index = 0,
) {
for (let attempt = 0; attempt < 100; attempt += 1) {
const request = socket.sent[index];
const request = socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)[index];
if (request) {
return decodeRpcRequest(decodeJson(request));
return request;
}
yield* Effect.yieldNow;
}
@@ -195,21 +229,33 @@ const awaitRequest = Effect.fn("TestRpcSessionFactory.awaitRequest")(function* (
const completeInitialConfig = Effect.fn("TestRpcSessionFactory.completeInitialConfig")(function* (
socket: TestWebSocket,
config: unknown = ENCODED_SERVER_CONFIG,
payload: unknown = {},
) {
const request = yield* awaitRequest(socket);
expect(request).toMatchObject({
_tag: "Request",
tag: WS_METHODS.serverGetConfig,
payload: {},
tag: WS_METHODS.subscribeServerConfig,
payload,
});
socket.serverMessage(
encodeJson({
_tag: "Exit",
_tag: "Chunk",
requestId: request.id,
exit: {
_tag: "Success",
value: config,
},
values: [{ version: 1, type: "snapshot", config }],
}),
);
});
const publishConfigEvents = Effect.fn("TestRpcSessionFactory.publishConfigEvents")(function* (
socket: TestWebSocket,
events: ReadonlyArray<ServerConfigStreamEventType>,
) {
const request = yield* awaitRequest(socket);
socket.serverMessage(
encodeJson({
_tag: "Chunk",
requestId: request.id,
values: events.map((event) => encodeServerConfigStreamEvent(event)),
}),
);
});
@@ -229,7 +275,9 @@ describe("RpcSessionFactory", () => {
const config = yield* session.initialConfig;
expect(config).toEqual(SERVER_CONFIG);
expect(socket.sent).toHaveLength(1);
expect(socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)).toHaveLength(
1,
);
const probeFiber = yield* Effect.forkChild(session.probe);
const probeRequest = yield* awaitRequest(socket, 1);
@@ -250,19 +298,25 @@ describe("RpcSessionFactory", () => {
);
yield* Fiber.join(probeFiber);
expect(socket.sent.map((request) => decodeRpcRequest(decodeJson(request)).tag)).toEqual([
WS_METHODS.serverGetConfig,
WS_METHODS.serverProbe,
]);
expect(
socket.sent
.map((message) => decodeJson(message))
.filter(isRpcRequest)
.map((request) => request.tag),
).toEqual([WS_METHODS.subscribeServerConfig, WS_METHODS.serverProbe]);
socket.close(1012, "service restart");
const error = yield* Effect.flip(session.closed);
const configStreamError = yield* session
.subscribeServerConfig({})
.pipe(Stream.runDrain, Effect.flip);
expect(error).toBeInstanceOf(ConnectionTransientError);
expect(error).toMatchObject({
reason: "transport",
message: "Test environment disconnected.",
});
expect(configStreamError).toMatchObject({ _tag: "RpcClientError" });
yield* Effect.yieldNow;
expect(sockets).toHaveLength(1);
}),
@@ -287,6 +341,602 @@ describe("RpcSessionFactory", () => {
}),
);
it.effect("replays current config and broadcasts updates to every subscriber", () =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory();
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(session.ready);
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket);
yield* Fiber.join(readyFiber);
const collectTwo = session
.subscribeServerConfig({})
.pipe(Stream.take(2), Stream.runCollect);
const firstSubscriber = yield* Effect.forkChild(collectTwo);
const secondSubscriber = yield* Effect.forkChild(collectTwo);
yield* Effect.yieldNow;
const shortcut = {
key: "k",
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false,
modKey: true,
};
const request = yield* awaitRequest(socket);
socket.serverMessage(
encodeJson({
_tag: "Chunk",
requestId: request.id,
values: [
{
version: 1,
type: "keybindingsUpdated",
payload: {
keybindings: [{ command: "terminal.toggle", shortcut }],
issues: [],
},
},
],
}),
);
const firstEvents = Array.from(yield* Fiber.join(firstSubscriber));
const secondEvents = Array.from(yield* Fiber.join(secondSubscriber));
expect(firstEvents.map((event) => event.type)).toEqual(["snapshot", "keybindingsUpdated"]);
expect(secondEvents).toEqual(firstEvents);
const replay = yield* session.subscribeServerConfig({}).pipe(Stream.runHead);
expect(replay).toMatchObject({
_tag: "Some",
value: {
type: "snapshot",
config: { keybindings: [{ command: "terminal.toggle", shortcut }] },
},
});
}),
),
);
it.effect("shares only a config subscription with the same theme opt-in", () =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(session.ready);
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, {
environmentThemes: true,
});
yield* Fiber.join(readyFiber);
const shared = yield* session
.subscribeServerConfig({ environmentThemes: true })
.pipe(Stream.runHead);
expect(shared).toMatchObject({ _tag: "Some", value: { type: "snapshot" } });
expect(socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)).toHaveLength(
1,
);
const fallbackFiber = yield* session
.subscribeServerConfig({})
.pipe(Stream.runHead, Effect.forkChild);
const fallbackRequest = yield* awaitRequest(socket, 1);
expect(fallbackRequest).toMatchObject({
tag: WS_METHODS.subscribeServerConfig,
payload: {},
});
socket.serverMessage(
encodeJson({
_tag: "Chunk",
requestId: fallbackRequest.id,
values: [
{
version: 1,
type: "snapshot",
config: ENCODED_THEME_SERVER_CONFIG,
},
],
}),
);
expect(yield* Fiber.join(fallbackFiber)).toMatchObject({
_tag: "Some",
value: { type: "snapshot" },
});
}),
),
);
it.effect("replays theme updates and deletion as authoritative events", () =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(session.ready);
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, {
environmentThemes: true,
});
yield* Fiber.join(readyFiber);
const firstThemes = [
{
id: "nightfall",
name: "Nightfall",
appearance: "dark" as const,
canvas: "#1a1b26",
accent: "#7aa2f7",
},
];
const replacementThemes = [
{
id: "midnight",
name: "Midnight",
appearance: "dark" as const,
canvas: "#000000",
accent: "#ffffff",
},
];
const subscriberStarted = yield* Deferred.make<void>();
const subscriber = yield* session.subscribeServerConfig({ environmentThemes: true }).pipe(
Stream.mapEffect((event) =>
Deferred.succeed(subscriberStarted, undefined).pipe(Effect.as(event)),
),
Stream.take(4),
Stream.runCollect,
Effect.forkChild,
);
yield* Deferred.await(subscriberStarted);
yield* publishConfigEvents(socket, [
{
version: 1,
type: "environmentThemesUpdated",
payload: { themes: firstThemes },
},
{
version: 1,
type: "environmentThemesUpdated",
payload: { themes: replacementThemes },
},
{
version: 1,
type: "environmentThemesUpdated",
payload: { themes: [] },
},
]);
const liveEvents = Array.from(yield* Fiber.join(subscriber));
expect(liveEvents.map((event) => event.type)).toEqual([
"snapshot",
"environmentThemesUpdated",
"environmentThemesUpdated",
"environmentThemesUpdated",
]);
expect(liveEvents[2]).toMatchObject({ payload: { themes: replacementThemes } });
const replay = Array.from(
yield* session
.subscribeServerConfig({ environmentThemes: true })
.pipe(Stream.take(2), Stream.runCollect),
);
expect(replay.map((event) => event.type)).toEqual(["snapshot", "environmentThemesUpdated"]);
expect(replay[1]).toMatchObject({ payload: { themes: [] } });
let projection = applyServerConfigProjection(Option.none(), {
version: 1,
type: "snapshot",
config: THEME_SERVER_CONFIG,
});
projection = applyServerConfigProjection(projection, {
version: 1,
type: "environmentThemesUpdated",
payload: { themes: firstThemes },
});
for (const event of replay) {
projection = applyServerConfigProjection(projection, event);
}
expect(Option.getOrThrow(projection).config.environmentThemes).toBeUndefined();
}),
),
);
it.effect("recovers a slow subscriber after it misses theme deletion", () =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(session.ready);
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, {
environmentThemes: true,
});
yield* Fiber.join(readyFiber);
const slowSubscriberStarted = yield* Deferred.make<void>();
const releaseSlowSubscriber = yield* Deferred.make<void>();
let firstEvent = true;
const slowSubscriber = yield* session
.subscribeServerConfig({ environmentThemes: true })
.pipe(
Stream.mapEffect((event) => {
if (!firstEvent) return Effect.succeed(event);
firstEvent = false;
return Deferred.succeed(slowSubscriberStarted, undefined).pipe(
Effect.andThen(Deferred.await(releaseSlowSubscriber)),
Effect.as(event),
);
}),
Stream.take(3),
Stream.runCollect,
Effect.forkChild,
);
yield* Deferred.await(slowSubscriberStarted);
const firstThemes = [
{
id: "nightfall",
name: "Nightfall",
appearance: "dark" as const,
canvas: "#1a1b26",
accent: "#7aa2f7",
},
];
const themeEvents: ServerConfigStreamEventType[] = [
{
version: 1,
type: "environmentThemesUpdated",
payload: { themes: firstThemes },
},
{
version: 1,
type: "environmentThemesUpdated",
payload: {
themes: [{ ...firstThemes[0]!, name: "Nightfall 2" }],
},
},
{
version: 1,
type: "environmentThemesUpdated",
payload: { themes: [] },
},
];
const settingsEvents = Array.from(
{ length: 65 },
(): ServerConfigStreamEventType => ({
version: 1,
type: "settingsUpdated",
payload: { settings: DEFAULT_SERVER_SETTINGS },
}),
);
const allEvents = [...themeEvents, ...settingsEvents];
const observedByFastSubscriber = yield* Queue.unbounded<ServerConfigStreamEventType>();
yield* session.subscribeServerConfig({ environmentThemes: true }).pipe(
Stream.runForEach((event) => Queue.offer(observedByFastSubscriber, event)),
Effect.forkChild,
);
expect((yield* Queue.take(observedByFastSubscriber)).type).toBe("snapshot");
for (const event of allEvents) {
yield* publishConfigEvents(socket, [event]);
expect(yield* Queue.take(observedByFastSubscriber)).toEqual(event);
}
yield* Deferred.succeed(releaseSlowSubscriber, undefined);
const recovered = Array.from(yield* Fiber.join(slowSubscriber));
expect(recovered.map((event) => event.type)).toEqual([
"snapshot",
"snapshot",
"environmentThemesUpdated",
]);
expect(recovered[2]).toMatchObject({ payload: { themes: [] } });
let projection = applyServerConfigProjection(Option.none(), {
version: 1,
type: "snapshot",
config: THEME_SERVER_CONFIG,
});
projection = applyServerConfigProjection(projection, themeEvents[0]!);
for (const event of recovered.slice(1)) {
projection = applyServerConfigProjection(projection, event);
}
expect(Option.getOrThrow(projection).config.environmentThemes).toBeUndefined();
}),
),
);
it.effect("closes the session when the config source dies", () =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory();
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(session.ready);
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket);
yield* Fiber.join(readyFiber);
const closedFiber = yield* session.closed.pipe(Effect.exit, Effect.forkChild);
socket.serverMessage(
encodeJson({
_tag: "Defect",
defect: encodeDefect(new Error("config stream died")),
}),
);
const closed = yield* Fiber.join(closedFiber);
expect(Exit.isFailure(closed)).toBe(true);
if (Exit.isFailure(closed)) {
expect(Cause.hasDies(closed.cause)).toBe(true);
}
}),
),
);
it.effect.each([{ failure: "defect" as const }, { failure: "typed" as const }])(
"keeps durable config state alive after an owned $failure failure",
({ failure }) =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory({ environmentThemes: true });
const firstSession = yield* factory.connect(PREPARED);
const firstReady = yield* Effect.forkChild(firstSession.ready);
const firstSocket = yield* awaitSocket(sockets);
firstSocket.open();
yield* completeInitialConfig(firstSocket, ENCODED_THEME_SERVER_CONFIG, {
environmentThemes: true,
});
yield* Fiber.join(firstReady);
const activeSession = yield* SubscriptionRef.make(Option.some(firstSession));
const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
target: TARGET,
state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
session: activeSession,
prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
connect: Effect.void,
disconnect: Effect.void,
retryNow: Effect.void,
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
const cache = Persistence.EnvironmentCacheStore.of({
loadShell: () => Effect.succeed(Option.none()),
saveShell: () => Effect.void,
loadThread: () => Effect.succeed(Option.none()),
saveThread: () => Effect.void,
removeThread: () => Effect.void,
loadServerConfig: () => Effect.succeed(Option.none()),
saveServerConfig: () => Effect.void,
loadVcsRefs: () => Effect.succeed(Option.none()),
saveVcsRefs: () => Effect.void,
removeVcsRefs: () => Effect.void,
clearVcsRefs: () => Effect.void,
clear: () => Effect.void,
});
const configState = yield* makeEnvironmentServerConfigState(true).pipe(
Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
Effect.provideService(Persistence.EnvironmentCacheStore, cache),
);
const awaitConfig = (predicate: (config: ServerConfigType) => boolean) =>
SubscriptionRef.changes(configState).pipe(
Stream.filter(Option.isSome),
Stream.map((projection) => projection.value.config),
Stream.filter(predicate),
Stream.runHead,
Effect.map(Option.getOrThrow),
);
const firstThemes = [
{
id: "first-theme",
name: "First theme",
appearance: "dark" as const,
canvas: "#111111",
accent: "#ffffff",
},
];
const firstThemeState = yield* awaitConfig(
(config) => config.environmentThemes?.[0]?.id === "first-theme",
).pipe(Effect.forkChild);
yield* publishConfigEvents(firstSocket, [
{
version: 1,
type: "environmentThemesUpdated",
payload: { themes: firstThemes },
},
]);
expect((yield* Fiber.join(firstThemeState)).environmentThemes).toEqual(firstThemes);
const firstClosed = yield* firstSession.closed.pipe(Effect.exit, Effect.forkChild);
const firstRequest = yield* awaitRequest(firstSocket);
firstSocket.serverMessage(
failure === "defect"
? encodeJson({
_tag: "Defect",
defect: encodeDefect(new Error("config stream died")),
})
: encodeJson({
_tag: "Exit",
requestId: firstRequest.id,
exit: {
_tag: "Failure",
cause: [
{
_tag: "Fail",
error: {
_tag: "EnvironmentAuthorizationError",
message: "config subscription rejected",
requiredScope: "orchestration:read",
},
},
],
},
}),
);
const firstClosedExit = yield* Fiber.join(firstClosed);
expect(Exit.isFailure(firstClosedExit)).toBe(true);
if (failure === "typed" && Exit.isFailure(firstClosedExit)) {
expect(Cause.squash(firstClosedExit.cause)).toBeInstanceOf(ConnectionBlockedError);
expect(Cause.squash(firstClosedExit.cause)).toMatchObject({ reason: "permission" });
}
yield* SubscriptionRef.set(activeSession, Option.none());
const recoveredConfig = {
...THEME_SERVER_CONFIG,
environment: {
...THEME_SERVER_CONFIG.environment,
label: "Recovered environment",
},
} satisfies ServerConfigType;
const secondSession = yield* factory.connect(PREPARED);
const secondReady = yield* Effect.forkChild(secondSession.ready);
const secondSocket = yield* awaitSocket(sockets, 1);
secondSocket.open();
yield* completeInitialConfig(secondSocket, encodeServerConfig(recoveredConfig), {
environmentThemes: true,
});
yield* Fiber.join(secondReady);
const recoveredState = yield* awaitConfig(
(config) => config.environment.label === "Recovered environment",
).pipe(Effect.forkChild);
yield* SubscriptionRef.set(activeSession, Option.some(secondSession));
expect((yield* Fiber.join(recoveredState)).environmentThemes).toEqual(firstThemes);
const recoveredThemes = [
{
id: "recovered-theme",
name: "Recovered theme",
appearance: "dark" as const,
canvas: "#000000",
accent: "#eeeeee",
},
];
const liveRecoveredState = yield* awaitConfig(
(config) => config.environmentThemes?.[0]?.id === "recovered-theme",
).pipe(Effect.forkChild);
yield* publishConfigEvents(secondSocket, [
{
version: 1,
type: "environmentThemesUpdated",
payload: { themes: recoveredThemes },
},
]);
expect((yield* Fiber.join(liveRecoveredState)).environmentThemes).toEqual(
recoveredThemes,
);
}),
),
);
it.effect.each<{
readonly event: ServerConfigStreamEventType;
readonly expectedConfig: Partial<ServerConfigType>;
}>([
{
event: {
version: 1,
type: "providerStatuses",
payload: {
providers: [
{
instanceId: ProviderInstanceId.make("codex"),
driver: ProviderDriverKind.make("codex"),
enabled: true,
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-08-27T00:00:00.000Z",
models: [],
slashCommands: [],
skills: [],
},
],
},
},
expectedConfig: {
providers: [
{
instanceId: ProviderInstanceId.make("codex"),
driver: ProviderDriverKind.make("codex"),
enabled: true,
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated" },
checkedAt: "2026-08-27T00:00:00.000Z",
models: [],
slashCommands: [],
skills: [],
},
],
},
},
{
event: {
version: 1,
type: "settingsUpdated",
payload: {
settings: {
...DEFAULT_SERVER_SETTINGS,
newWorktreesStartFromOrigin: !DEFAULT_SERVER_SETTINGS.newWorktreesStartFromOrigin,
},
},
},
expectedConfig: {
settings: {
...DEFAULT_SERVER_SETTINGS,
newWorktreesStartFromOrigin: !DEFAULT_SERVER_SETTINGS.newWorktreesStartFromOrigin,
},
},
},
])(
"preserves $event.type events and includes them in replay snapshots",
({ event, expectedConfig }) =>
Effect.scoped(
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory();
const session = yield* factory.connect(PREPARED);
const readyFiber = yield* Effect.forkChild(session.ready);
const socket = yield* awaitSocket(sockets);
socket.open();
yield* completeInitialConfig(socket);
yield* Fiber.join(readyFiber);
const subscriber = yield* session
.subscribeServerConfig({})
.pipe(Stream.take(2), Stream.runCollect, Effect.forkChild);
yield* Effect.yieldNow;
const request = yield* awaitRequest(socket);
socket.serverMessage(
encodeJson({
_tag: "Chunk",
requestId: request.id,
values: [encodeServerConfigStreamEvent(event)],
}),
);
const events = Array.from(yield* Fiber.join(subscriber));
expect(events[1]).toEqual(event);
const replay = yield* session.subscribeServerConfig({}).pipe(Stream.runHead);
expect(replay).toMatchObject({
_tag: "Some",
value: {
type: "snapshot",
config: expectedConfig,
},
});
}),
),
);
it.effect("tolerates two missed pong windows before closing the session", () =>
Effect.gen(function* () {
const { factory, sockets } = yield* makeFactory();
@@ -301,7 +951,7 @@ describe("RpcSessionFactory", () => {
yield* TestClock.adjust("15 seconds");
expect(closedFiber.pollUnsafe()).toBeUndefined();
expect(socket.sent.slice(1).map((request) => decodeJson(request))).toEqual([
expect(socket.sent.map((message) => decodeJson(message)).filter(isPing)).toEqual([
{ _tag: "Ping" },
{ _tag: "Ping" },
{ _tag: "Ping" },
@@ -379,10 +1029,12 @@ describe("RpcSessionFactory", () => {
);
yield* Fiber.join(probeFiber);
expect(socket.sent.map((request) => decodeRpcRequest(decodeJson(request)).tag)).toEqual([
WS_METHODS.serverGetConfig,
WS_METHODS.serverGetConfig,
]);
expect(
socket.sent
.map((message) => decodeJson(message))
.filter(isRpcRequest)
.map((request) => request.tag),
).toEqual([WS_METHODS.subscribeServerConfig, WS_METHODS.serverGetConfig]);
}),
),
);
+207 -14
View File
@@ -1,11 +1,25 @@
import { type ServerConfig, WS_METHODS } from "@t3tools/contracts";
import {
type ServerConfig,
type ServerConfigStreamEvent,
WsSubscribeServerConfigRpc,
WS_METHODS,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import type * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import type * as Rpc from "effect/unstable/rpc/Rpc";
import * as RpcClient from "effect/unstable/rpc/RpcClient";
import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
import * as Socket from "effect/unstable/socket/Socket";
@@ -19,15 +33,27 @@ import {
ConnectionBlockedError,
ConnectionTransientError as ConnectionTransientErrorClass,
} from "../connection/model.ts";
import {
applyServerConfigProjection,
type ServerConfigProjection,
withoutEnvironmentThemes,
} from "../state/serverConfigProjection.ts";
const SOCKET_OPEN_TIMEOUT = "15 seconds";
export interface RpcSession {
readonly client: WsRpcProtocolClient;
readonly initialConfig: Effect.Effect<ServerConfig, ConnectionAttemptError>;
readonly subscribeServerConfig: (
input: ServerConfigSubscriptionInput,
) => ServerConfigSubscription;
readonly ready: Effect.Effect<void, ConnectionAttemptError>;
readonly probe: Effect.Effect<void, ConnectionAttemptError>;
readonly closed: Effect.Effect<never, ConnectionTransientError>;
readonly closed: Effect.Effect<never, ConnectionAttemptError>;
}
export interface RpcSessionOptions {
readonly environmentThemes?: boolean;
}
export class RpcSessionFactory extends Context.Service<
@@ -43,8 +69,47 @@ type InitialConfigError = Effect.Error<
ReturnType<WsRpcProtocolClient[typeof WS_METHODS.serverGetConfig]>
>;
type ProbeError = Effect.Error<ReturnType<WsRpcProtocolClient[typeof WS_METHODS.serverProbe]>>;
type ServerConfigSubscriptionError =
| Rpc.ErrorExit<typeof WsSubscribeServerConfigRpc>
| RpcClientError.RpcClientError;
type ServerConfigSubscription = Stream.Stream<
ServerConfigStreamEvent,
ServerConfigSubscriptionError
>;
type ServerConfigSubscriptionInput = Parameters<
WsRpcProtocolClient[typeof WS_METHODS.subscribeServerConfig]
>[0];
type EnvironmentThemesUpdatedEvent = Extract<
ServerConfigStreamEvent,
{ readonly type: "environmentThemesUpdated" }
>;
function mapSessionRpcError(error: InitialConfigError | ProbeError): ConnectionAttemptError {
interface ServerConfigReplayState {
readonly projection: ServerConfigProjection;
readonly revision: number;
readonly themesEvent: EnvironmentThemesUpdatedEvent | undefined;
}
interface BufferedServerConfigEvent {
readonly event: ServerConfigStreamEvent;
readonly replay: ServerConfigReplayState;
readonly revision: number;
}
function serverConfigReplayEvents(
state: ServerConfigReplayState,
): ReadonlyArray<ServerConfigStreamEvent> {
const snapshot = {
version: 1 as const,
type: "snapshot" as const,
config: withoutEnvironmentThemes(state.projection.config),
};
return state.themesEvent === undefined ? [snapshot] : [snapshot, state.themesEvent];
}
function mapSessionRpcError(
error: InitialConfigError | ProbeError | ServerConfigSubscriptionError,
): ConnectionAttemptError {
switch (error._tag) {
case "EnvironmentAuthorizationError":
return new ConnectionBlockedError({
@@ -65,8 +130,12 @@ function mapSessionRpcError(error: InitialConfigError | ProbeError): ConnectionA
}
}
export const make = Effect.gen(function* () {
export const make = Effect.fn("RpcSessionFactory.make")(function* (
options: RpcSessionOptions = {},
) {
const webSocketConstructor = yield* Socket.WebSocketConstructor;
const serverConfigInput: ServerConfigSubscriptionInput =
options.environmentThemes === true ? { environmentThemes: true } : {};
const connect = Effect.fnUntraced(function* (connection: PreparedConnection) {
yield* Effect.annotateCurrentSpan({
@@ -113,18 +182,135 @@ export const make = Effect.gen(function* () {
const protocolContext = yield* Layer.build(protocolLayer).pipe(
Effect.withSpan("environment.websocket.connect"),
);
const client = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
const initialConfig = yield* Effect.cached(
client[WS_METHODS.serverGetConfig]({}).pipe(
Effect.mapError(mapSessionRpcError),
Effect.withSpan("environment.initialSync"),
const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext));
const initialConfigDeferred = yield* Deferred.make<ServerConfig>();
const serverConfigExit = yield* Deferred.make<void, ServerConfigSubscriptionError>();
const configSubscriptionClosed = yield* Deferred.make<never, ConnectionAttemptError>();
const serverConfigState = yield* Ref.make(Option.none<ServerConfigReplayState>());
const serverConfigUpdates = yield* PubSub.sliding<BufferedServerConfigEvent>(64);
const configSubscriptionEndedError = new ConnectionTransientErrorClass({
reason: "remote-unavailable",
detail: `${connection.label} config subscription ended.`,
});
const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig](
serverConfigInput,
).pipe(
Stream.runForEach((event) =>
Effect.gen(function* () {
const buffered = yield* Ref.modify(serverConfigState, (current) => {
const projection = applyServerConfigProjection(
Option.map(current, (state) => state.projection),
event,
);
if (Option.isNone(projection)) {
return [Option.none<BufferedServerConfigEvent>(), current] as const;
}
const next = {
projection: projection.value,
revision: Option.match(current, {
onNone: () => 1,
onSome: (state) => state.revision + 1,
}),
themesEvent:
event.type === "environmentThemesUpdated"
? event
: event.type === "snapshot" &&
event.config.environment.capabilities.environmentThemes !== true
? undefined
: Option.getOrUndefined(current)?.themesEvent,
} satisfies ServerConfigReplayState;
return [
Option.some({ event, replay: next, revision: next.revision }),
Option.some(next),
] as const;
});
if (Option.isSome(buffered)) {
yield* PubSub.publish(serverConfigUpdates, buffered.value);
}
if (event.type === "snapshot") {
yield* Deferred.succeed(initialConfigDeferred, event.config);
}
}),
),
Effect.onExit((exit) => {
if (Exit.isSuccess(exit)) {
return Effect.all([
Deferred.succeed(serverConfigExit, undefined),
Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError),
]).pipe(Effect.asVoid);
}
if (Cause.hasInterruptsOnly(exit.cause)) {
return Effect.void;
}
return Effect.all([
Deferred.failCause(serverConfigExit, exit.cause),
Deferred.failCause(configSubscriptionClosed, Cause.map(exit.cause, mapSessionRpcError)),
]).pipe(Effect.asVoid);
}),
);
yield* serverConfigSource.pipe(Effect.forkScoped);
const initialConfig = Effect.raceFirst(
Deferred.await(initialConfigDeferred),
Deferred.await(serverConfigExit).pipe(
Effect.mapError(mapSessionRpcError),
Effect.flatMap(() => Effect.fail(configSubscriptionEndedError)),
),
).pipe(Effect.withSpan("environment.initialSync"));
const serverConfigEvents = Stream.unwrap(
Effect.gen(function* () {
const subscription = yield* PubSub.subscribe(serverConfigUpdates);
yield* Effect.raceFirst(
Deferred.await(initialConfigDeferred).pipe(Effect.asVoid),
Deferred.await(serverConfigExit),
);
const snapshot = yield* Ref.get(serverConfigState);
if (Option.isNone(snapshot)) {
return Stream.empty;
}
const updates = Stream.fromSubscription(subscription).pipe(
Stream.filter((buffered) => buffered.revision > snapshot.value.revision),
Stream.mapAccum(
() => snapshot.value.revision,
(revision, buffered) => [
buffered.revision,
buffered.revision === revision + 1
? [buffered.event]
: serverConfigReplayEvents(buffered.replay),
],
),
);
const terminal = Stream.fromEffect(Deferred.await(serverConfigExit)).pipe(Stream.drain);
return Stream.concat(
Stream.fromIterable(serverConfigReplayEvents(snapshot.value)),
Stream.merge(updates, terminal, { haltStrategy: "either" }),
);
}),
).pipe(
Stream.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Stream.failCause(cause);
}
// The supervisor keeps the original cause. Shared durable consumers
// need a transport-shaped failure so they wait for its replacement.
return Stream.fail(
new RpcClientError.RpcClientError({
reason: new RpcClientError.RpcClientDefect({
message: `${connection.label} config subscription failed.`,
cause,
}),
}),
);
}),
);
const subscribeServerConfig = (input: ServerConfigSubscriptionInput) =>
Equal.equals(input, serverConfigInput)
? serverConfigEvents
: protocolClient[WS_METHODS.subscribeServerConfig](input);
const probe = initialConfig.pipe(
Effect.flatMap((config) =>
(config.environment.capabilities.connectionProbe === true
? client[WS_METHODS.serverProbe]({})
: client[WS_METHODS.serverGetConfig]({})
? protocolClient[WS_METHODS.serverProbe]({})
: protocolClient[WS_METHODS.serverGetConfig]({})
).pipe(Effect.mapError(mapSessionRpcError)),
),
Effect.asVoid,
@@ -132,19 +318,26 @@ export const make = Effect.gen(function* () {
);
return {
client,
client: protocolClient,
initialConfig,
subscribeServerConfig,
ready: Deferred.await(connected).pipe(
Effect.andThen(initialConfig),
Effect.asVoid,
Effect.raceFirst(Deferred.await(disconnected)),
),
probe,
closed: Deferred.await(disconnected),
closed: Effect.raceFirst(
Deferred.await(disconnected),
Deferred.await(configSubscriptionClosed),
),
} satisfies RpcSession;
});
return RpcSessionFactory.of({ connect });
});
export const layer = Layer.effect(RpcSessionFactory, make);
export const layerWithOptions = (options: RpcSessionOptions) =>
Layer.effect(RpcSessionFactory, make(options));
export const layer = layerWithOptions({});
@@ -32,6 +32,7 @@ function session(client: WsRpcProtocolClient): RpcSession {
return {
client,
initialConfig: Effect.never,
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
@@ -30,7 +30,6 @@ import * as Persistence from "../platform/persistence.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import type { RpcSession } from "../rpc/session.ts";
import {
applyServerConfigProjection,
makeEnvironmentServerConfigState,
isLegacyUpdateHandoffLoss,
matchesServerUpdateReadyEvent,
@@ -42,6 +41,7 @@ import {
serverUpdateStateForServerVersion,
validateServerUpdateReadyEvent,
} from "./server.ts";
import { applyServerConfigProjection } from "./serverConfigProjection.ts";
const CONFIG = {
availableEditors: [],
@@ -73,6 +73,7 @@ function session(client: WsRpcProtocolClient): RpcSession {
return {
client,
initialConfig: Effect.succeed(CONFIG),
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
+8 -85
View File
@@ -41,6 +41,14 @@ import {
type EnvironmentRpcInput,
} from "../rpc/client.ts";
import { followStreamInEnvironment } from "./runtime.ts";
import {
applyServerConfigProjection,
type ServerConfigProjection,
withoutEnvironmentThemes,
} from "./serverConfigProjection.ts";
// Exported server state includes this type in its inferred public return type.
export type { ServerConfigProjection } from "./serverConfigProjection.ts";
export type ServerUpdateStage = "downloading" | "installing" | "resuming";
@@ -262,75 +270,6 @@ export function resolveServerUpdateProgressResult<E>(
return Effect.fail(new ServerUpdateProgressIncompleteError({ targetVersion }));
}
export interface ServerConfigProjection {
readonly config: ServerConfig;
readonly latestEvent: ServerConfigStreamEvent;
readonly source: "cache" | "live";
}
export function applyServerConfigProjection(
current: Option.Option<ServerConfigProjection>,
event: ServerConfigStreamEvent,
): Option.Option<ServerConfigProjection> {
switch (event.type) {
case "snapshot": {
// A snapshot never carries published themes -- the theme stream owns
// them -- so taking it wholesale would clear the set on every reconnect
// and repaint anyone wearing one until the follow-up event landed.
// Only from a server that still streams them. Reconnecting to one that
// predates the feature must drop the set rather than leave a palette on
// screen that nothing will ever update again.
const carried =
event.config.environment.capabilities.environmentThemes === true && Option.isSome(current)
? current.value.config.environmentThemes
: undefined;
return Option.some({
config:
carried === undefined ? event.config : { ...event.config, environmentThemes: carried },
latestEvent: event,
source: "live" as const,
});
}
case "keybindingsUpdated":
return Option.map(current, (projection) => ({
config: {
...projection.config,
keybindings: event.payload.keybindings,
issues: event.payload.issues,
},
latestEvent: event,
source: "live",
}));
case "providerStatuses":
return Option.map(current, (projection) => ({
config: {
...projection.config,
providers: event.payload.providers,
},
latestEvent: event,
source: "live",
}));
case "settingsUpdated":
return Option.map(current, (projection) => ({
config: {
...projection.config,
settings: event.payload.settings,
},
latestEvent: event,
source: "live",
}));
case "environmentThemesUpdated":
return Option.map(current, (projection) => ({
config: {
...projection.config,
environmentThemes: event.payload.themes.length > 0 ? event.payload.themes : undefined,
},
latestEvent: event,
source: "live",
}));
}
}
export function projectServerConfig(
current: Option.Option<ServerConfigProjection>,
event: ServerConfigStreamEvent,
@@ -345,22 +284,6 @@ const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEven
config,
});
/**
* Keeps a complete server configuration available during reconnects. Server
* config carries the provider/model catalogue used by task creation, so it is
* useful—and safe—to retain after a transport session ends.
*/
/**
* Published themes live only as long as the machine publishes them, so they
* must not survive in the config cache: a restart or an offline load would
* otherwise hand clients palettes the environment has already dropped.
*/
function withoutEnvironmentThemes(config: ServerConfig): ServerConfig {
if (config.environmentThemes === undefined) return config;
const { environmentThemes: _ephemeral, ...rest } = config;
return rest;
}
export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(
function* (environmentThemes?: boolean) {
const supervisor = yield* EnvironmentSupervisor;
@@ -0,0 +1,79 @@
import type { ServerConfig, ServerConfigStreamEvent } from "@t3tools/contracts";
import * as Option from "effect/Option";
export interface ServerConfigProjection {
readonly config: ServerConfig;
readonly latestEvent: ServerConfigStreamEvent;
readonly source: "cache" | "live";
}
/**
* Cached config keeps the provider and model catalog available across reconnects.
* Published themes are current machine state, so a cache could restore themes
* that the machine no longer publishes. Replay sends themes as a separate event.
*/
export function withoutEnvironmentThemes(config: ServerConfig): ServerConfig {
if (config.environmentThemes === undefined) return config;
const { environmentThemes: _ephemeral, ...rest } = config;
return rest;
}
export function applyServerConfigProjection(
current: Option.Option<ServerConfigProjection>,
event: ServerConfigStreamEvent,
): Option.Option<ServerConfigProjection> {
switch (event.type) {
case "snapshot": {
// Wire snapshots never contain published themes. Keep the previous set
// until a capable server sends its authoritative theme event. A legacy
// server cannot send a later removal, so a downgrade must clear the set.
const carried =
event.config.environment.capabilities.environmentThemes === true && Option.isSome(current)
? current.value.config.environmentThemes
: undefined;
return Option.some({
config:
carried === undefined ? event.config : { ...event.config, environmentThemes: carried },
latestEvent: event,
source: "live" as const,
});
}
case "keybindingsUpdated":
return Option.map(current, (projection) => ({
config: {
...projection.config,
keybindings: event.payload.keybindings,
issues: event.payload.issues,
},
latestEvent: event,
source: "live",
}));
case "providerStatuses":
return Option.map(current, (projection) => ({
config: {
...projection.config,
providers: event.payload.providers,
},
latestEvent: event,
source: "live",
}));
case "settingsUpdated":
return Option.map(current, (projection) => ({
config: {
...projection.config,
settings: event.payload.settings,
},
latestEvent: event,
source: "live",
}));
case "environmentThemesUpdated":
return Option.map(current, (projection) => ({
config: {
...projection.config,
environmentThemes: event.payload.themes.length > 0 ? event.payload.themes : undefined,
},
latestEvent: event,
source: "live",
}));
}
}
@@ -51,6 +51,7 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
return {
client,
initialConfig: Effect.succeed({ shellResumeCompletionMarker: true } as never),
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
@@ -50,6 +50,7 @@ function session(client: WsRpcProtocolClient): RpcSession {
return {
client,
initialConfig: Effect.never,
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
@@ -156,6 +156,7 @@ const makeHarness = Effect.fn("TestThreadPagination.makeHarness")(function* (opt
initialConfig: Effect.succeed({
threadSnapshotPagination: options?.paginationCapability !== false,
} as never),
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
@@ -112,6 +112,7 @@ function testSession(
? ({ threadResumeCompletionMarker: true } as never)
: ({} as never),
),
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
@@ -86,6 +86,7 @@ function session(client: WsRpcProtocolClient): RpcSession {
return {
client,
initialConfig: Effect.never,
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,
@@ -84,6 +84,7 @@ function session(client: WsRpcProtocolClient): RpcSession {
return {
client,
initialConfig: Effect.never,
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
ready: Effect.void,
probe: Effect.void,
closed: Effect.never,