The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | DEFAULT_SERVER_SETTINGS, |
| 3 | EnvironmentId, |
| 4 | ServerConfig, |
| 5 | type ServerConfig as ServerConfigType, |
| 6 | ServerConfigStreamEvent, |
| 7 | type ServerConfigStreamEvent as ServerConfigStreamEventType, |
| 8 | ServerProvider, |
| 9 | WS_METHODS, |
| 10 | UsageLimitSourceId, |
| 11 | } from "@t3tools/contracts"; |
| 12 | import { splitSocketFrame } from "@t3tools/shared/socketFrameParts"; |
| 13 | import { describe, expect, it } from "@effect/vitest"; |
| 14 | import * as Cause from "effect/Cause"; |
| 15 | import * as Deferred from "effect/Deferred"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import * as Exit from "effect/Exit"; |
| 18 | import * as Fiber from "effect/Fiber"; |
| 19 | import * as Layer from "effect/Layer"; |
| 20 | import * as Option from "effect/Option"; |
| 21 | import * as Queue from "effect/Queue"; |
| 22 | import * as Schema from "effect/Schema"; |
| 23 | import * as Stream from "effect/Stream"; |
| 24 | import * as SubscriptionRef from "effect/SubscriptionRef"; |
| 25 | import * as Socket from "effect/socket/Socket"; |
| 26 | import * as TestClock from "effect/testing/TestClock"; |
| 27 | |
| 28 | import { |
| 29 | AVAILABLE_CONNECTION_STATE, |
| 30 | ConnectionBlockedError, |
| 31 | ConnectionTransientError, |
| 32 | PrimaryConnectionTarget, |
| 33 | type PreparedConnection, |
| 34 | } from "../connection/model.ts"; |
| 35 | import * as EnvironmentSupervisor from "../connection/supervisor.ts"; |
| 36 | import * as Persistence from "../platform/persistence.ts"; |
| 37 | import * as RpcSession from "./session.ts"; |
| 38 | import { toServerClock } from "../clock.ts"; |
| 39 | import { makeEnvironmentServerConfigState } from "../state/server.ts"; |
| 40 | import { applyServerConfigProjection } from "../state/serverConfigProjection.ts"; |
| 41 | |
| 42 | type SocketEventType = "open" | "message" | "close" | "error"; |
| 43 | type SocketEvent = { |
| 44 | readonly code?: number; |
| 45 | readonly data?: unknown; |
| 46 | readonly reason?: string; |
| 47 | readonly type: SocketEventType; |
| 48 | }; |
| 49 | type SocketListener = (event: SocketEvent) => void; |
| 50 | |
| 51 | class TestWebSocket { |
| 52 | static readonly CONNECTING = 0; |
| 53 | static readonly OPEN = 1; |
| 54 | static readonly CLOSING = 2; |
| 55 | static readonly CLOSED = 3; |
| 56 | |
| 57 | readyState = TestWebSocket.CONNECTING; |
| 58 | readonly sent: string[] = []; |
| 59 | readonly url: string; |
| 60 | readonly sentChanges: Queue.Queue<void>; |
| 61 | private readonly listeners = new Map<SocketEventType, Set<SocketListener>>(); |
| 62 | |
| 63 | constructor(url: string, sentChanges: Queue.Queue<void>) { |
| 64 | this.url = url; |
| 65 | this.sentChanges = sentChanges; |
| 66 | } |
| 67 | |
| 68 | addEventListener(type: SocketEventType, listener: SocketListener) { |
| 69 | const listeners = this.listeners.get(type) ?? new Set<SocketListener>(); |
| 70 | listeners.add(listener); |
| 71 | this.listeners.set(type, listeners); |
| 72 | } |
| 73 | |
| 74 | removeEventListener(type: SocketEventType, listener: SocketListener) { |
| 75 | this.listeners.get(type)?.delete(listener); |
| 76 | } |
| 77 | |
| 78 | send(data: string) { |
| 79 | this.sent.push(data); |
| 80 | Queue.offerUnsafe(this.sentChanges, undefined); |
| 81 | } |
| 82 | |
| 83 | close(code = 1000, reason = "") { |
| 84 | if (this.readyState === TestWebSocket.CLOSED) { |
| 85 | return; |
| 86 | } |
| 87 | this.readyState = TestWebSocket.CLOSED; |
| 88 | this.emit("close", { code, reason, type: "close" }); |
| 89 | } |
| 90 | |
| 91 | open() { |
| 92 | this.readyState = TestWebSocket.OPEN; |
| 93 | this.emit("open", { type: "open" }); |
| 94 | } |
| 95 | |
| 96 | serverMessage(data: string) { |
| 97 | this.emit("message", { data, type: "message" }); |
| 98 | } |
| 99 | |
| 100 | private emit(type: SocketEventType, event: SocketEvent) { |
| 101 | for (const listener of this.listeners.get(type) ?? []) { |
| 102 | listener(event); |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | const TARGET = new PrimaryConnectionTarget({ |
| 108 | environmentId: EnvironmentId.make("environment-1"), |
| 109 | label: "Test environment", |
| 110 | httpBaseUrl: "https://environment.example.test", |
| 111 | wsBaseUrl: "wss://environment.example.test", |
| 112 | }); |
| 113 | |
| 114 | const PREPARED: PreparedConnection = { |
| 115 | environmentId: TARGET.environmentId, |
| 116 | label: TARGET.label, |
| 117 | httpBaseUrl: TARGET.httpBaseUrl, |
| 118 | socketUrl: "wss://environment.example.test/ws?wsTicket=test", |
| 119 | httpAuthorization: null, |
| 120 | target: TARGET, |
| 121 | }; |
| 122 | |
| 123 | const SERVER_CONFIG: ServerConfigType = { |
| 124 | environment: { |
| 125 | environmentId: TARGET.environmentId, |
| 126 | label: TARGET.label, |
| 127 | platform: { |
| 128 | os: "darwin", |
| 129 | arch: "arm64", |
| 130 | }, |
| 131 | serverVersion: "0.0.0-test", |
| 132 | capabilities: { |
| 133 | repositoryIdentity: true, |
| 134 | connectionProbe: true, |
| 135 | }, |
| 136 | }, |
| 137 | auth: { |
| 138 | policy: "loopback-browser", |
| 139 | bootstrapMethods: ["one-time-token"], |
| 140 | sessionMethods: ["browser-session-cookie", "bearer-access-token"], |
| 141 | sessionCookieName: "t3_session", |
| 142 | }, |
| 143 | cwd: "/tmp/workspace", |
| 144 | keybindingsConfigPath: "/tmp/workspace/keybindings.json", |
| 145 | keybindings: [], |
| 146 | issues: [], |
| 147 | providers: [], |
| 148 | availableEditors: [], |
| 149 | observability: { |
| 150 | logsDirectoryPath: "/tmp/logs", |
| 151 | localTracingEnabled: false, |
| 152 | otlpTracesEnabled: false, |
| 153 | otlpMetricsEnabled: false, |
| 154 | otlpLogsEnabled: false, |
| 155 | }, |
| 156 | settings: DEFAULT_SERVER_SETTINGS, |
| 157 | }; |
| 158 | |
| 159 | const RpcRequest = Schema.TaggedStruct("Request", { |
| 160 | id: Schema.Union([Schema.String, Schema.Number]), |
| 161 | payload: Schema.Unknown, |
| 162 | tag: Schema.String, |
| 163 | }); |
| 164 | const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); |
| 165 | const isRpcRequest = Schema.is(RpcRequest); |
| 166 | const encodeJson = Schema.encodeUnknownSync(Schema.fromJsonString(Schema.Unknown)); |
| 167 | const encodeServerConfig = Schema.encodeSync(ServerConfig); |
| 168 | const encodeServerConfigStreamEvent = Schema.encodeSync(ServerConfigStreamEvent); |
| 169 | const encodeDefect = Schema.encodeSync(Schema.Defect()); |
| 170 | const ENCODED_SERVER_CONFIG = encodeServerConfig(SERVER_CONFIG); |
| 171 | const THEME_SERVER_CONFIG: ServerConfigType = { |
| 172 | ...SERVER_CONFIG, |
| 173 | environment: { |
| 174 | ...SERVER_CONFIG.environment, |
| 175 | capabilities: { |
| 176 | ...SERVER_CONFIG.environment.capabilities, |
| 177 | environmentThemes: true, |
| 178 | }, |
| 179 | }, |
| 180 | }; |
| 181 | const ENCODED_THEME_SERVER_CONFIG = encodeServerConfig(THEME_SERVER_CONFIG); |
| 182 | const SOURCE_SERVER_CONFIG: ServerConfigType = { |
| 183 | ...THEME_SERVER_CONFIG, |
| 184 | environment: { |
| 185 | ...THEME_SERVER_CONFIG.environment, |
| 186 | capabilities: { ...THEME_SERVER_CONFIG.environment.capabilities, usageLimitSources: true }, |
| 187 | }, |
| 188 | }; |
| 189 | const PROVIDER = Schema.decodeSync(ServerProvider)({ |
| 190 | instanceId: "codex", |
| 191 | driver: "codex", |
| 192 | enabled: true, |
| 193 | installed: true, |
| 194 | version: "1.0.0", |
| 195 | status: "ready", |
| 196 | auth: { status: "authenticated" }, |
| 197 | checkedAt: "2026-04-10T00:00:00.000Z", |
| 198 | models: [{ slug: "gpt", name: "GPT", isCustom: false, capabilities: null }], |
| 199 | slashCommands: [{ name: "compact" }], |
| 200 | }); |
| 201 | const SOURCE_EVENT: ServerConfigStreamEventType = { |
| 202 | version: 1, |
| 203 | type: "usageLimitSourcesUpdated", |
| 204 | payload: { |
| 205 | sources: [ |
| 206 | { |
| 207 | id: UsageLimitSourceId.make("proxy"), |
| 208 | kind: "cliproxy", |
| 209 | label: "Proxy", |
| 210 | checkedAt: "2026-09-04T00:00:00Z", |
| 211 | accounts: [], |
| 212 | }, |
| 213 | ], |
| 214 | }, |
| 215 | }; |
| 216 | |
| 217 | const makeFactory = Effect.fn("TestRpcSessionFactory.make")(function* ( |
| 218 | options: RpcSession.RpcSessionOptions = {}, |
| 219 | ) { |
| 220 | const sentChanges = yield* Queue.unbounded<void>(); |
| 221 | const sockets = Object.assign([] as TestWebSocket[], { changes: yield* Queue.unbounded<void>() }); |
| 222 | const layerConstructor = Layer.succeed(Socket.WebSocketConstructor, (url) => { |
| 223 | const socket = new TestWebSocket(url, sentChanges); |
| 224 | sockets.push(socket); |
| 225 | Queue.offerUnsafe(sockets.changes, undefined); |
| 226 | return socket as unknown as globalThis.WebSocket; |
| 227 | }); |
| 228 | const layer = RpcSession.layer(options).pipe(Layer.provide(layerConstructor)); |
| 229 | const factory = yield* RpcSession.RpcSessionFactory.pipe(Effect.provide(layer)); |
| 230 | return { factory, sockets }; |
| 231 | }); |
| 232 | |
| 233 | const awaitSocket = Effect.fn("TestRpcSessionFactory.awaitSocket")(function* ( |
| 234 | sockets: ReadonlyArray<TestWebSocket> & { readonly changes: Queue.Queue<void> }, |
| 235 | index = 0, |
| 236 | ) { |
| 237 | for (;;) { |
| 238 | const socket = sockets[index]; |
| 239 | if (socket) { |
| 240 | return socket; |
| 241 | } |
| 242 | yield* Queue.take(sockets.changes); |
| 243 | } |
| 244 | }); |
| 245 | |
| 246 | const awaitRequest = Effect.fn("TestRpcSessionFactory.awaitRequest")(function* ( |
| 247 | socket: TestWebSocket, |
| 248 | index = 0, |
| 249 | ) { |
| 250 | for (;;) { |
| 251 | const request = socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)[index]; |
| 252 | if (request) { |
| 253 | return request; |
| 254 | } |
| 255 | yield* Queue.take(socket.sentChanges); |
| 256 | } |
| 257 | }); |
| 258 | |
| 259 | const completeInitialConfig = Effect.fn("TestRpcSessionFactory.completeInitialConfig")(function* ( |
| 260 | socket: TestWebSocket, |
| 261 | config: unknown = ENCODED_SERVER_CONFIG, |
| 262 | payload: unknown = {}, |
| 263 | ) { |
| 264 | const request = yield* awaitRequest(socket); |
| 265 | expect(request).toMatchObject({ |
| 266 | _tag: "Request", |
| 267 | tag: WS_METHODS.subscribeServerConfig, |
| 268 | payload, |
| 269 | }); |
| 270 | socket.serverMessage( |
| 271 | encodeJson({ |
| 272 | _tag: "Chunk", |
| 273 | requestId: request.id, |
| 274 | values: [{ version: 1, type: "snapshot", config }], |
| 275 | }), |
| 276 | ); |
| 277 | }); |
| 278 | |
| 279 | const publishConfigEvents = Effect.fn("TestRpcSessionFactory.publishConfigEvents")(function* ( |
| 280 | socket: TestWebSocket, |
| 281 | events: ReadonlyArray<ServerConfigStreamEventType>, |
| 282 | ) { |
| 283 | const request = yield* awaitRequest(socket); |
| 284 | socket.serverMessage( |
| 285 | encodeJson({ |
| 286 | _tag: "Chunk", |
| 287 | requestId: request.id, |
| 288 | values: events.map((event) => encodeServerConfigStreamEvent(event)), |
| 289 | }), |
| 290 | ); |
| 291 | }); |
| 292 | |
| 293 | describe("RpcSessionFactory", () => { |
| 294 | it.effect("connects while a large config snapshot downloads at 4000 bytes per second", () => |
| 295 | Effect.gen(function* () { |
| 296 | const { factory, sockets } = yield* makeFactory(); |
| 297 | const session = yield* factory.connect(PREPARED); |
| 298 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 299 | const socket = yield* awaitSocket(sockets); |
| 300 | socket.open(); |
| 301 | const request = yield* awaitRequest(socket); |
| 302 | // Multi-byte text, so parts must be sized in UTF-8 bytes and never split a surrogate pair. |
| 303 | const config = { ...SERVER_CONFIG, cwd: "/" + "é€😀x".repeat(32 * 1024) }; |
| 304 | const frame = encodeJson({ |
| 305 | _tag: "Chunk", |
| 306 | requestId: request.id, |
| 307 | values: [{ version: 1, type: "snapshot", config: encodeServerConfig(config) }], |
| 308 | }); |
| 309 | const parts = new URL(socket.url).searchParams.has("frameParts") |
| 310 | ? splitSocketFrame(frame) |
| 311 | : [frame]; |
| 312 | |
| 313 | for (const part of parts) { |
| 314 | const bytes = new TextEncoder().encode(part); |
| 315 | yield* TestClock.adjust((bytes.length / 4000) * 1000); |
| 316 | socket.serverMessage(new TextDecoder().decode(bytes)); |
| 317 | } |
| 318 | yield* Fiber.join(readyFiber); |
| 319 | |
| 320 | expect(yield* session.initialConfig).toEqual(config); |
| 321 | }), |
| 322 | ); |
| 323 | |
| 324 | it.effect("owns one scoped websocket attempt and exposes readiness and closure", () => |
| 325 | Effect.gen(function* () { |
| 326 | const { factory, sockets } = yield* makeFactory(); |
| 327 | const session = yield* factory.connect(PREPARED); |
| 328 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 329 | const socket = yield* awaitSocket(sockets); |
| 330 | |
| 331 | expect(socket.url).toBe(`${PREPARED.socketUrl}&frameParts=1`); |
| 332 | socket.open(); |
| 333 | yield* completeInitialConfig(socket); |
| 334 | yield* Fiber.join(readyFiber); |
| 335 | |
| 336 | const config = yield* session.initialConfig; |
| 337 | expect(config).toEqual(SERVER_CONFIG); |
| 338 | expect(socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)).toHaveLength( |
| 339 | 1, |
| 340 | ); |
| 341 | |
| 342 | const probeFiber = yield* Effect.forkChild(session.probe); |
| 343 | const probeRequest = yield* awaitRequest(socket, 1); |
| 344 | expect(probeRequest).toMatchObject({ |
| 345 | _tag: "Request", |
| 346 | tag: WS_METHODS.serverProbe, |
| 347 | payload: {}, |
| 348 | }); |
| 349 | socket.serverMessage( |
| 350 | encodeJson({ |
| 351 | _tag: "Exit", |
| 352 | requestId: probeRequest.id, |
| 353 | exit: { |
| 354 | _tag: "Success", |
| 355 | value: {}, |
| 356 | }, |
| 357 | }), |
| 358 | ); |
| 359 | yield* Fiber.join(probeFiber); |
| 360 | |
| 361 | expect( |
| 362 | socket.sent |
| 363 | .map((message) => decodeJson(message)) |
| 364 | .filter(isRpcRequest) |
| 365 | .map((request) => request.tag), |
| 366 | ).toEqual([WS_METHODS.subscribeServerConfig, WS_METHODS.serverProbe]); |
| 367 | |
| 368 | socket.close(1012, "service restart"); |
| 369 | const error = yield* Effect.flip(session.closed); |
| 370 | const configStreamError = yield* session |
| 371 | .subscribeServerConfig({}) |
| 372 | .pipe(Stream.runDrain, Effect.flip); |
| 373 | |
| 374 | expect(error).toBeInstanceOf(ConnectionTransientError); |
| 375 | expect(error).toMatchObject({ |
| 376 | reason: "transport", |
| 377 | message: "Test environment disconnected.", |
| 378 | }); |
| 379 | expect(configStreamError).toMatchObject({ _tag: "RpcClientError" }); |
| 380 | yield* Effect.yieldNow; |
| 381 | expect(sockets).toHaveLength(1); |
| 382 | }), |
| 383 | ); |
| 384 | |
| 385 | it.effect("counts every inbound frame, including ones that answer no request", () => |
| 386 | Effect.gen(function* () { |
| 387 | const { factory, sockets } = yield* makeFactory(); |
| 388 | const session = yield* factory.connect(PREPARED); |
| 389 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 390 | const socket = yield* awaitSocket(sockets); |
| 391 | socket.open(); |
| 392 | yield* completeInitialConfig(socket); |
| 393 | yield* Fiber.join(readyFiber); |
| 394 | const before = yield* session.inboundFrames; |
| 395 | |
| 396 | socket.serverMessage(encodeJson({ _tag: "Pong" })); |
| 397 | |
| 398 | expect(yield* session.inboundFrames).toBe(before + 1); |
| 399 | }), |
| 400 | ); |
| 401 | |
| 402 | it.effect("closes the websocket when the session scope is released", () => |
| 403 | Effect.gen(function* () { |
| 404 | const { factory, sockets } = yield* makeFactory(); |
| 405 | |
| 406 | yield* Effect.scoped( |
| 407 | Effect.gen(function* () { |
| 408 | const session = yield* factory.connect(PREPARED); |
| 409 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 410 | const socket = yield* awaitSocket(sockets); |
| 411 | socket.open(); |
| 412 | yield* completeInitialConfig(socket); |
| 413 | yield* Fiber.join(readyFiber); |
| 414 | }), |
| 415 | ); |
| 416 | |
| 417 | expect(sockets[0]?.readyState).toBe(TestWebSocket.CLOSED); |
| 418 | }), |
| 419 | ); |
| 420 | |
| 421 | it.effect("ends a stream at once when its socket closes", () => |
| 422 | Effect.gen(function* () { |
| 423 | const { factory, sockets } = yield* makeFactory(); |
| 424 | const session = yield* factory.connect(PREPARED); |
| 425 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 426 | const socket = yield* awaitSocket(sockets); |
| 427 | socket.open(); |
| 428 | yield* completeInitialConfig(socket); |
| 429 | yield* Fiber.join(readyFiber); |
| 430 | // Like the supervisor: the closed session interrupts its streams, and a |
| 431 | // stream interrupt must not wait for a socket that is gone. |
| 432 | const ended = yield* Effect.forkChild( |
| 433 | Effect.raceFirst( |
| 434 | Effect.flip(session.closed), |
| 435 | session.client[WS_METHODS.subscribeServerLifecycle]({}).pipe( |
| 436 | Stream.runDrain, |
| 437 | Effect.andThen(Effect.never), |
| 438 | ), |
| 439 | ), |
| 440 | ); |
| 441 | yield* awaitRequest(socket, 1); |
| 442 | socket.close(1006); |
| 443 | yield* TestClock.adjust("999 millis"); |
| 444 | |
| 445 | expect(ended.pollUnsafe()).toBeDefined(); |
| 446 | // A request made after the close still fails instead of waiting forever. |
| 447 | const lateProbe = yield* Effect.forkChild(session.probe); |
| 448 | yield* TestClock.adjust("999 millis"); |
| 449 | expect(lateProbe.pollUnsafe()?._tag).toBe("Failure"); |
| 450 | }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), |
| 451 | ); |
| 452 | |
| 453 | it.effect("replays current config and broadcasts updates to every subscriber", () => |
| 454 | Effect.gen(function* () { |
| 455 | const { factory, sockets } = yield* makeFactory(); |
| 456 | const session = yield* factory.connect(PREPARED); |
| 457 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 458 | const socket = yield* awaitSocket(sockets); |
| 459 | socket.open(); |
| 460 | yield* completeInitialConfig(socket); |
| 461 | yield* Fiber.join(readyFiber); |
| 462 | |
| 463 | const collectTwo = session.subscribeServerConfig({}).pipe(Stream.take(2), Stream.runCollect); |
| 464 | const firstSubscriber = yield* Effect.forkChild(collectTwo); |
| 465 | const secondSubscriber = yield* Effect.forkChild(collectTwo); |
| 466 | yield* Effect.yieldNow; |
| 467 | |
| 468 | const shortcut = { |
| 469 | key: "k", |
| 470 | metaKey: false, |
| 471 | ctrlKey: false, |
| 472 | shiftKey: false, |
| 473 | altKey: false, |
| 474 | modKey: true, |
| 475 | }; |
| 476 | const request = yield* awaitRequest(socket); |
| 477 | socket.serverMessage( |
| 478 | encodeJson({ |
| 479 | _tag: "Chunk", |
| 480 | requestId: request.id, |
| 481 | values: [ |
| 482 | { |
| 483 | version: 1, |
| 484 | type: "keybindingsUpdated", |
| 485 | payload: { |
| 486 | keybindings: [{ command: "terminal.toggle", shortcut }], |
| 487 | issues: [], |
| 488 | }, |
| 489 | }, |
| 490 | ], |
| 491 | }), |
| 492 | ); |
| 493 | |
| 494 | const firstEvents = Array.from(yield* Fiber.join(firstSubscriber)); |
| 495 | const secondEvents = Array.from(yield* Fiber.join(secondSubscriber)); |
| 496 | expect(firstEvents.map((event) => event.type)).toEqual(["snapshot", "keybindingsUpdated"]); |
| 497 | expect(secondEvents).toEqual(firstEvents); |
| 498 | |
| 499 | const replay = yield* session.subscribeServerConfig({}).pipe(Stream.runHead); |
| 500 | expect(replay).toMatchObject({ |
| 501 | _tag: "Some", |
| 502 | value: { |
| 503 | type: "snapshot", |
| 504 | config: { keybindings: [{ command: "terminal.toggle", shortcut }] }, |
| 505 | }, |
| 506 | }); |
| 507 | }), |
| 508 | ); |
| 509 | |
| 510 | it.effect.each([ |
| 511 | { usageLimitSources: true }, |
| 512 | { environmentThemes: true, usageLimitSources: true }, |
| 513 | ])("replays usage sources and removal with %j", (options) => |
| 514 | Effect.gen(function* () { |
| 515 | const { factory, sockets } = yield* makeFactory(options); |
| 516 | const session = yield* factory.connect(PREPARED); |
| 517 | const ready = yield* Effect.forkChild(session.ready); |
| 518 | const socket = yield* awaitSocket(sockets); |
| 519 | socket.open(); |
| 520 | yield* completeInitialConfig(socket, encodeServerConfig(SOURCE_SERVER_CONFIG), options); |
| 521 | yield* Fiber.join(ready); |
| 522 | const observed = yield* Queue.unbounded<ServerConfigStreamEventType>(); |
| 523 | yield* session.subscribeServerConfig().pipe( |
| 524 | Stream.runForEach((event) => Queue.offer(observed, event)), |
| 525 | Effect.forkChild, |
| 526 | ); |
| 527 | expect((yield* Queue.take(observed)).type).toBe("snapshot"); |
| 528 | const themes: ServerConfigStreamEventType[] = options.environmentThemes |
| 529 | ? [{ version: 1, type: "environmentThemesUpdated", payload: { themes: [] } }] |
| 530 | : []; |
| 531 | for (const event of themes) { |
| 532 | yield* publishConfigEvents(socket, [event]); |
| 533 | expect(yield* Queue.take(observed)).toEqual(event); |
| 534 | } |
| 535 | const events: ServerConfigStreamEventType[] = [ |
| 536 | SOURCE_EVENT, |
| 537 | { version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } }, |
| 538 | SOURCE_EVENT, |
| 539 | ]; |
| 540 | for (const event of events) { |
| 541 | yield* publishConfigEvents(socket, [event]); |
| 542 | expect(yield* Queue.take(observed)).toEqual(event); |
| 543 | const started = yield* Deferred.make<void>(); |
| 544 | const replay = yield* session.subscribeServerConfig(options).pipe( |
| 545 | Stream.tap(() => Deferred.succeed(started, undefined)), |
| 546 | Stream.takeUntil((item) => item.type === "keybindingsUpdated"), |
| 547 | Stream.runCollect, |
| 548 | Effect.forkChild, |
| 549 | ); |
| 550 | yield* Deferred.await(started); |
| 551 | const marker: ServerConfigStreamEventType = { |
| 552 | version: 1, |
| 553 | type: "keybindingsUpdated", |
| 554 | payload: { keybindings: [], issues: [] }, |
| 555 | }; |
| 556 | yield* publishConfigEvents(socket, [marker]); |
| 557 | expect(yield* Queue.take(observed)).toEqual(marker); |
| 558 | const replayed = Array.from(yield* Fiber.join(replay)); |
| 559 | expect(replayed.slice(1)).toEqual([...themes, event, marker]); |
| 560 | let projection = applyServerConfigProjection(Option.none(), { |
| 561 | version: 1, |
| 562 | type: "snapshot", |
| 563 | config: SOURCE_SERVER_CONFIG, |
| 564 | }); |
| 565 | projection = applyServerConfigProjection(projection, SOURCE_EVENT); |
| 566 | for (const item of replayed) projection = applyServerConfigProjection(projection, item); |
| 567 | expect(Option.getOrThrow(projection).config.usageLimitSources).toEqual( |
| 568 | event.type === "usageLimitSourcesUpdated" && event.payload.sources.length > 0 |
| 569 | ? event.payload.sources |
| 570 | : undefined, |
| 571 | ); |
| 572 | } |
| 573 | expect(socket.sent.map((message) => decodeJson(message)).filter(isRpcRequest)).toHaveLength( |
| 574 | 1, |
| 575 | ); |
| 576 | }), |
| 577 | ); |
| 578 | |
| 579 | it.effect("replays theme updates and deletion as authoritative events", () => |
| 580 | Effect.gen(function* () { |
| 581 | const { factory, sockets } = yield* makeFactory({ environmentThemes: true }); |
| 582 | const session = yield* factory.connect(PREPARED); |
| 583 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 584 | const socket = yield* awaitSocket(sockets); |
| 585 | socket.open(); |
| 586 | yield* completeInitialConfig(socket, ENCODED_THEME_SERVER_CONFIG, { |
| 587 | environmentThemes: true, |
| 588 | }); |
| 589 | yield* Fiber.join(readyFiber); |
| 590 | |
| 591 | const firstThemes = [ |
| 592 | { |
| 593 | id: "nightfall", |
| 594 | name: "Nightfall", |
| 595 | appearance: "dark" as const, |
| 596 | canvas: "#1a1b26", |
| 597 | accent: "#7aa2f7", |
| 598 | }, |
| 599 | ]; |
| 600 | const replacementThemes = [ |
| 601 | { |
| 602 | id: "midnight", |
| 603 | name: "Midnight", |
| 604 | appearance: "dark" as const, |
| 605 | canvas: "#000000", |
| 606 | accent: "#ffffff", |
| 607 | }, |
| 608 | ]; |
| 609 | const subscriberStarted = yield* Deferred.make<void>(); |
| 610 | const subscriber = yield* session.subscribeServerConfig({ environmentThemes: true }).pipe( |
| 611 | Stream.mapEffect((event) => |
| 612 | Deferred.succeed(subscriberStarted, undefined).pipe(Effect.as(event)), |
| 613 | ), |
| 614 | Stream.take(4), |
| 615 | Stream.runCollect, |
| 616 | Effect.forkChild, |
| 617 | ); |
| 618 | yield* Deferred.await(subscriberStarted); |
| 619 | yield* publishConfigEvents(socket, [ |
| 620 | { |
| 621 | version: 1, |
| 622 | type: "environmentThemesUpdated", |
| 623 | payload: { themes: firstThemes }, |
| 624 | }, |
| 625 | { |
| 626 | version: 1, |
| 627 | type: "environmentThemesUpdated", |
| 628 | payload: { themes: replacementThemes }, |
| 629 | }, |
| 630 | { |
| 631 | version: 1, |
| 632 | type: "environmentThemesUpdated", |
| 633 | payload: { themes: [] }, |
| 634 | }, |
| 635 | ]); |
| 636 | |
| 637 | const liveEvents = Array.from(yield* Fiber.join(subscriber)); |
| 638 | expect(liveEvents.map((event) => event.type)).toEqual([ |
| 639 | "snapshot", |
| 640 | "environmentThemesUpdated", |
| 641 | "environmentThemesUpdated", |
| 642 | "environmentThemesUpdated", |
| 643 | ]); |
| 644 | expect(liveEvents[2]).toMatchObject({ payload: { themes: replacementThemes } }); |
| 645 | |
| 646 | const replay = Array.from( |
| 647 | yield* session |
| 648 | .subscribeServerConfig({ environmentThemes: true }) |
| 649 | .pipe(Stream.take(2), Stream.runCollect), |
| 650 | ); |
| 651 | expect(replay.map((event) => event.type)).toEqual(["snapshot", "environmentThemesUpdated"]); |
| 652 | expect(replay[1]).toMatchObject({ payload: { themes: [] } }); |
| 653 | |
| 654 | let projection = applyServerConfigProjection(Option.none(), { |
| 655 | version: 1, |
| 656 | type: "snapshot", |
| 657 | config: THEME_SERVER_CONFIG, |
| 658 | }); |
| 659 | projection = applyServerConfigProjection(projection, { |
| 660 | version: 1, |
| 661 | type: "environmentThemesUpdated", |
| 662 | payload: { themes: firstThemes }, |
| 663 | }); |
| 664 | for (const event of replay) { |
| 665 | projection = applyServerConfigProjection(projection, event); |
| 666 | } |
| 667 | expect(Option.getOrThrow(projection).config.environmentThemes).toEqual([]); |
| 668 | }), |
| 669 | ); |
| 670 | |
| 671 | it.effect("recovers a slow subscriber after it misses theme and usage-source deletion", () => |
| 672 | Effect.gen(function* () { |
| 673 | const { factory, sockets } = yield* makeFactory({ |
| 674 | environmentThemes: true, |
| 675 | usageLimitSources: true, |
| 676 | }); |
| 677 | const session = yield* factory.connect(PREPARED); |
| 678 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 679 | const socket = yield* awaitSocket(sockets); |
| 680 | socket.open(); |
| 681 | yield* completeInitialConfig( |
| 682 | socket, |
| 683 | encodeServerConfig({ ...SOURCE_SERVER_CONFIG, providers: [PROVIDER] }), |
| 684 | { environmentThemes: true, usageLimitSources: true }, |
| 685 | ); |
| 686 | yield* Fiber.join(readyFiber); |
| 687 | |
| 688 | const slowSubscriberStarted = yield* Deferred.make<void>(); |
| 689 | const releaseSlowSubscriber = yield* Deferred.make<void>(); |
| 690 | let firstEvent = true; |
| 691 | const slowSubscriber = yield* session |
| 692 | .subscribeServerConfig({ environmentThemes: true, usageLimitSources: true }) |
| 693 | .pipe( |
| 694 | Stream.mapEffect((event) => { |
| 695 | if (!firstEvent) return Effect.succeed(event); |
| 696 | firstEvent = false; |
| 697 | return Deferred.succeed(slowSubscriberStarted, undefined).pipe( |
| 698 | Effect.andThen(Deferred.await(releaseSlowSubscriber)), |
| 699 | Effect.as(event), |
| 700 | ); |
| 701 | }), |
| 702 | Stream.take(4), |
| 703 | Stream.runCollect, |
| 704 | Effect.forkChild, |
| 705 | ); |
| 706 | yield* Deferred.await(slowSubscriberStarted); |
| 707 | |
| 708 | const firstThemes = [ |
| 709 | { |
| 710 | id: "nightfall", |
| 711 | name: "Nightfall", |
| 712 | appearance: "dark" as const, |
| 713 | canvas: "#1a1b26", |
| 714 | accent: "#7aa2f7", |
| 715 | }, |
| 716 | ]; |
| 717 | const themeEvents: ServerConfigStreamEventType[] = [ |
| 718 | { |
| 719 | version: 1, |
| 720 | type: "environmentThemesUpdated", |
| 721 | payload: { themes: firstThemes }, |
| 722 | }, |
| 723 | { |
| 724 | version: 1, |
| 725 | type: "environmentThemesUpdated", |
| 726 | payload: { |
| 727 | themes: [{ ...firstThemes[0]!, name: "Nightfall 2" }], |
| 728 | }, |
| 729 | }, |
| 730 | { |
| 731 | version: 1, |
| 732 | type: "environmentThemesUpdated", |
| 733 | payload: { themes: [] }, |
| 734 | }, |
| 735 | ]; |
| 736 | const settingsEvents = Array.from({ length: 65 }, (): ServerConfigStreamEventType => ({ |
| 737 | version: 1, |
| 738 | type: "settingsUpdated", |
| 739 | payload: { settings: DEFAULT_SERVER_SETTINGS }, |
| 740 | })); |
| 741 | const sourceEvents: ServerConfigStreamEventType[] = [ |
| 742 | SOURCE_EVENT, |
| 743 | { version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } }, |
| 744 | ]; |
| 745 | // A delta carries no lists; a subscriber that misses it must still get its result. |
| 746 | const { models: _models, slashCommands: _commands, skills: _skills, ...status } = PROVIDER; |
| 747 | const providerEvent: ServerConfigStreamEventType = { |
| 748 | version: 1, |
| 749 | type: "providerStatusDeltas", |
| 750 | payload: { |
| 751 | providers: [{ ...status, checkedAt: "2026-04-10T00:05:00.000Z", message: "Checked" }], |
| 752 | }, |
| 753 | }; |
| 754 | const allEvents = [providerEvent, ...themeEvents, ...sourceEvents, ...settingsEvents]; |
| 755 | const observedByFastSubscriber = yield* Queue.unbounded<ServerConfigStreamEventType>(); |
| 756 | yield* session |
| 757 | .subscribeServerConfig({ environmentThemes: true, usageLimitSources: true }) |
| 758 | .pipe( |
| 759 | Stream.runForEach((event) => Queue.offer(observedByFastSubscriber, event)), |
| 760 | Effect.forkChild, |
| 761 | ); |
| 762 | expect((yield* Queue.take(observedByFastSubscriber)).type).toBe("snapshot"); |
| 763 | for (const event of allEvents) { |
| 764 | yield* publishConfigEvents(socket, [event]); |
| 765 | expect(yield* Queue.take(observedByFastSubscriber)).toEqual(event); |
| 766 | } |
| 767 | yield* Deferred.succeed(releaseSlowSubscriber, undefined); |
| 768 | |
| 769 | const recovered = Array.from(yield* Fiber.join(slowSubscriber)); |
| 770 | expect(recovered.map((event) => event.type)).toEqual([ |
| 771 | "snapshot", |
| 772 | "snapshot", |
| 773 | "environmentThemesUpdated", |
| 774 | "usageLimitSourcesUpdated", |
| 775 | ]); |
| 776 | expect(recovered[1]).toMatchObject({ |
| 777 | config: { |
| 778 | providers: [{ ...PROVIDER, checkedAt: "2026-04-10T00:05:00.000Z", message: "Checked" }], |
| 779 | }, |
| 780 | }); |
| 781 | expect(recovered[2]).toMatchObject({ payload: { themes: [] } }); |
| 782 | expect(recovered[3]).toMatchObject({ payload: { sources: [] } }); |
| 783 | |
| 784 | let projection = applyServerConfigProjection(Option.none(), { |
| 785 | version: 1, |
| 786 | type: "snapshot", |
| 787 | config: SOURCE_SERVER_CONFIG, |
| 788 | }); |
| 789 | projection = applyServerConfigProjection(projection, themeEvents[0]!); |
| 790 | projection = applyServerConfigProjection(projection, SOURCE_EVENT); |
| 791 | for (const event of recovered.slice(1)) { |
| 792 | projection = applyServerConfigProjection(projection, event); |
| 793 | } |
| 794 | expect(Option.getOrThrow(projection).config.environmentThemes).toEqual([]); |
| 795 | expect(Option.getOrThrow(projection).config.usageLimitSources).toBeUndefined(); |
| 796 | }), |
| 797 | ); |
| 798 | |
| 799 | it.effect("closes the session when the config source dies", () => |
| 800 | Effect.gen(function* () { |
| 801 | const { factory, sockets } = yield* makeFactory(); |
| 802 | const session = yield* factory.connect(PREPARED); |
| 803 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 804 | const socket = yield* awaitSocket(sockets); |
| 805 | socket.open(); |
| 806 | yield* completeInitialConfig(socket); |
| 807 | yield* Fiber.join(readyFiber); |
| 808 | |
| 809 | const closedFiber = yield* session.closed.pipe(Effect.exit, Effect.forkChild); |
| 810 | socket.serverMessage( |
| 811 | encodeJson({ |
| 812 | _tag: "Defect", |
| 813 | defect: encodeDefect(new Error("config stream died")), |
| 814 | }), |
| 815 | ); |
| 816 | |
| 817 | const closed = yield* Fiber.join(closedFiber); |
| 818 | expect(Exit.isFailure(closed)).toBe(true); |
| 819 | if (Exit.isFailure(closed)) { |
| 820 | expect(Cause.hasDies(closed.cause)).toBe(true); |
| 821 | } |
| 822 | }), |
| 823 | ); |
| 824 | |
| 825 | it.effect.each([{ failure: "defect" as const }, { failure: "typed" as const }])( |
| 826 | "keeps durable config state alive after an owned $failure failure", |
| 827 | ({ failure }) => |
| 828 | Effect.gen(function* () { |
| 829 | const { factory, sockets } = yield* makeFactory({ environmentThemes: true }); |
| 830 | const firstSession = yield* factory.connect(PREPARED); |
| 831 | const firstReady = yield* Effect.forkChild(firstSession.ready); |
| 832 | const firstSocket = yield* awaitSocket(sockets); |
| 833 | firstSocket.open(); |
| 834 | yield* completeInitialConfig(firstSocket, ENCODED_THEME_SERVER_CONFIG, { |
| 835 | environmentThemes: true, |
| 836 | }); |
| 837 | yield* Fiber.join(firstReady); |
| 838 | |
| 839 | const activeSession = yield* SubscriptionRef.make(Option.some(firstSession)); |
| 840 | const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ |
| 841 | target: TARGET, |
| 842 | state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE), |
| 843 | session: activeSession, |
| 844 | prepared: yield* SubscriptionRef.make(Option.some(PREPARED)), |
| 845 | connect: Effect.void, |
| 846 | disconnect: Effect.void, |
| 847 | retryNow: Effect.void, |
| 848 | } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); |
| 849 | const cache = Persistence.EnvironmentCacheStore.of({ |
| 850 | loadShell: () => Effect.succeedNone, |
| 851 | saveShell: () => Effect.void, |
| 852 | loadThread: () => Effect.succeedNone, |
| 853 | saveThread: () => Effect.void, |
| 854 | removeThread: () => Effect.void, |
| 855 | loadServerConfig: () => Effect.succeedNone, |
| 856 | saveServerConfig: () => Effect.void, |
| 857 | loadVcsRefs: () => Effect.succeedNone, |
| 858 | saveVcsRefs: () => Effect.void, |
| 859 | removeVcsRefs: () => Effect.void, |
| 860 | clearVcsRefs: () => Effect.void, |
| 861 | clear: () => Effect.void, |
| 862 | }); |
| 863 | const configState = yield* makeEnvironmentServerConfigState({ |
| 864 | environmentThemes: true, |
| 865 | }).pipe( |
| 866 | Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), |
| 867 | Effect.provideService(Persistence.EnvironmentCacheStore, cache), |
| 868 | ); |
| 869 | const awaitConfig = (predicate: (config: ServerConfigType) => boolean) => |
| 870 | SubscriptionRef.changes(configState).pipe( |
| 871 | Stream.filter(Option.isSome), |
| 872 | Stream.map((projection) => projection.value.config), |
| 873 | Stream.filter(predicate), |
| 874 | Stream.runHead, |
| 875 | Effect.map(Option.getOrThrow), |
| 876 | ); |
| 877 | |
| 878 | const firstThemes = [ |
| 879 | { |
| 880 | id: "first-theme", |
| 881 | name: "First theme", |
| 882 | appearance: "dark" as const, |
| 883 | canvas: "#111111", |
| 884 | accent: "#ffffff", |
| 885 | }, |
| 886 | ]; |
| 887 | const firstThemeState = yield* awaitConfig( |
| 888 | (config) => config.environmentThemes?.[0]?.id === "first-theme", |
| 889 | ).pipe(Effect.forkChild); |
| 890 | yield* publishConfigEvents(firstSocket, [ |
| 891 | { |
| 892 | version: 1, |
| 893 | type: "environmentThemesUpdated", |
| 894 | payload: { themes: firstThemes }, |
| 895 | }, |
| 896 | ]); |
| 897 | expect((yield* Fiber.join(firstThemeState)).environmentThemes).toEqual(firstThemes); |
| 898 | |
| 899 | const firstClosed = yield* firstSession.closed.pipe(Effect.exit, Effect.forkChild); |
| 900 | const firstRequest = yield* awaitRequest(firstSocket); |
| 901 | firstSocket.serverMessage( |
| 902 | failure === "defect" |
| 903 | ? encodeJson({ |
| 904 | _tag: "Defect", |
| 905 | defect: encodeDefect(new Error("config stream died")), |
| 906 | }) |
| 907 | : encodeJson({ |
| 908 | _tag: "Exit", |
| 909 | requestId: firstRequest.id, |
| 910 | exit: { |
| 911 | _tag: "Failure", |
| 912 | cause: [ |
| 913 | { |
| 914 | _tag: "Fail", |
| 915 | error: { |
| 916 | _tag: "EnvironmentAuthorizationError", |
| 917 | message: "config subscription rejected", |
| 918 | requiredScope: "orchestration:read", |
| 919 | }, |
| 920 | }, |
| 921 | ], |
| 922 | }, |
| 923 | }), |
| 924 | ); |
| 925 | const firstClosedExit = yield* Fiber.join(firstClosed); |
| 926 | expect(Exit.isFailure(firstClosedExit)).toBe(true); |
| 927 | if (failure === "typed" && Exit.isFailure(firstClosedExit)) { |
| 928 | expect(Cause.squash(firstClosedExit.cause)).toBeInstanceOf(ConnectionBlockedError); |
| 929 | expect(Cause.squash(firstClosedExit.cause)).toMatchObject({ reason: "permission" }); |
| 930 | } |
| 931 | yield* SubscriptionRef.set(activeSession, Option.none()); |
| 932 | |
| 933 | const recoveredConfig = { |
| 934 | ...THEME_SERVER_CONFIG, |
| 935 | environment: { |
| 936 | ...THEME_SERVER_CONFIG.environment, |
| 937 | label: "Recovered environment", |
| 938 | }, |
| 939 | } satisfies ServerConfigType; |
| 940 | const secondSession = yield* factory.connect(PREPARED); |
| 941 | const secondReady = yield* Effect.forkChild(secondSession.ready); |
| 942 | const secondSocket = yield* awaitSocket(sockets, 1); |
| 943 | secondSocket.open(); |
| 944 | yield* completeInitialConfig(secondSocket, encodeServerConfig(recoveredConfig), { |
| 945 | environmentThemes: true, |
| 946 | }); |
| 947 | yield* Fiber.join(secondReady); |
| 948 | |
| 949 | const recoveredState = yield* awaitConfig( |
| 950 | (config) => config.environment.label === "Recovered environment", |
| 951 | ).pipe(Effect.forkChild); |
| 952 | yield* SubscriptionRef.set(activeSession, Option.some(secondSession)); |
| 953 | expect((yield* Fiber.join(recoveredState)).environmentThemes).toEqual(firstThemes); |
| 954 | |
| 955 | const recoveredThemes = [ |
| 956 | { |
| 957 | id: "recovered-theme", |
| 958 | name: "Recovered theme", |
| 959 | appearance: "dark" as const, |
| 960 | canvas: "#000000", |
| 961 | accent: "#eeeeee", |
| 962 | }, |
| 963 | ]; |
| 964 | const liveRecoveredState = yield* awaitConfig( |
| 965 | (config) => config.environmentThemes?.[0]?.id === "recovered-theme", |
| 966 | ).pipe(Effect.forkChild); |
| 967 | yield* publishConfigEvents(secondSocket, [ |
| 968 | { |
| 969 | version: 1, |
| 970 | type: "environmentThemesUpdated", |
| 971 | payload: { themes: recoveredThemes }, |
| 972 | }, |
| 973 | ]); |
| 974 | expect((yield* Fiber.join(liveRecoveredState)).environmentThemes).toEqual(recoveredThemes); |
| 975 | }), |
| 976 | ); |
| 977 | |
| 978 | it.effect("rejects a server config for a different environment", () => |
| 979 | Effect.gen(function* () { |
| 980 | const { factory, sockets } = yield* makeFactory(); |
| 981 | const session = yield* factory.connect(PREPARED); |
| 982 | const readyFiber = yield* Effect.forkChild(Effect.flip(session.ready)); |
| 983 | const configFiber = yield* session |
| 984 | .subscribeServerConfig({}) |
| 985 | .pipe(Stream.runHead, Effect.flip, Effect.forkChild); |
| 986 | const customConfigFiber = yield* session |
| 987 | .subscribeServerConfig({ environmentThemes: true }) |
| 988 | .pipe(Stream.runHead, Effect.flip, Effect.forkChild); |
| 989 | const socket = yield* awaitSocket(sockets); |
| 990 | socket.open(); |
| 991 | yield* completeInitialConfig(socket, { |
| 992 | ...ENCODED_SERVER_CONFIG, |
| 993 | environment: { |
| 994 | ...ENCODED_SERVER_CONFIG.environment, |
| 995 | environmentId: "environment-2", |
| 996 | }, |
| 997 | }); |
| 998 | |
| 999 | const error = yield* Fiber.join(readyFiber); |
| 1000 | expect(error).toMatchObject({ |
| 1001 | reason: "configuration", |
| 1002 | message: "Connected environment environment-2 does not match environment-1.", |
| 1003 | }); |
| 1004 | expect((yield* Fiber.join(configFiber))._tag).toBe("RpcClientError"); |
| 1005 | expect((yield* Fiber.join(customConfigFiber))._tag).toBe("RpcClientError"); |
| 1006 | }), |
| 1007 | ); |
| 1008 | |
| 1009 | it.effect("keeps reading replies after closing a stream with a full buffer", () => |
| 1010 | Effect.gen(function* () { |
| 1011 | const { factory, sockets } = yield* makeFactory(); |
| 1012 | const session = yield* factory.connect(PREPARED); |
| 1013 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 1014 | const socket = yield* awaitSocket(sockets); |
| 1015 | socket.open(); |
| 1016 | yield* completeInitialConfig(socket); |
| 1017 | yield* Fiber.join(readyFiber); |
| 1018 | |
| 1019 | const consuming = yield* Deferred.make<void>(); |
| 1020 | const streamFiber = yield* session.client[WS_METHODS.subscribeServerConfig]({}).pipe( |
| 1021 | Stream.runForEach(() => |
| 1022 | Deferred.succeed(consuming, undefined).pipe(Effect.andThen(Effect.never)), |
| 1023 | ), |
| 1024 | Effect.forkChild, |
| 1025 | ); |
| 1026 | const streamRequest = yield* awaitRequest(socket, 1); |
| 1027 | const snapshot = { version: 1, type: "snapshot", config: ENCODED_SERVER_CONFIG }; |
| 1028 | socket.serverMessage( |
| 1029 | encodeJson({ |
| 1030 | _tag: "Chunk", |
| 1031 | requestId: streamRequest.id, |
| 1032 | values: Array.from({ length: 64 }, () => snapshot), |
| 1033 | }), |
| 1034 | ); |
| 1035 | yield* Deferred.await(consuming); |
| 1036 | yield* Fiber.interrupt(streamFiber); |
| 1037 | |
| 1038 | const probeFiber = yield* Effect.forkChild(session.probe); |
| 1039 | const probeRequest = yield* awaitRequest(socket, 2); |
| 1040 | expect(probeRequest).toMatchObject({ tag: WS_METHODS.serverProbe }); |
| 1041 | socket.serverMessage( |
| 1042 | encodeJson({ |
| 1043 | _tag: "Exit", |
| 1044 | requestId: probeRequest.id, |
| 1045 | exit: { _tag: "Success", value: {} }, |
| 1046 | }), |
| 1047 | ); |
| 1048 | yield* Fiber.join(probeFiber); |
| 1049 | }), |
| 1050 | ); |
| 1051 | |
| 1052 | it.effect("reads the host clock from each connection's config, dropping it when absent", () => |
| 1053 | Effect.gen(function* () { |
| 1054 | const { factory, sockets } = yield* makeFactory(); |
| 1055 | const connectWith = (config: unknown) => |
| 1056 | Effect.scoped( |
| 1057 | Effect.gen(function* () { |
| 1058 | const socketIndex = sockets.length; |
| 1059 | const session = yield* factory.connect(PREPARED); |
| 1060 | const ready = yield* Effect.forkChild(session.ready); |
| 1061 | const socket = yield* awaitSocket(sockets, socketIndex); |
| 1062 | socket.open(); |
| 1063 | yield* completeInitialConfig(socket, config); |
| 1064 | yield* Fiber.join(ready); |
| 1065 | }), |
| 1066 | ); |
| 1067 | |
| 1068 | yield* connectWith({ ...ENCODED_SERVER_CONFIG, serverTime: "1970-01-01T01:00:00.000Z" }); |
| 1069 | expect(toServerClock(PREPARED.environmentId, 0)).toBe(3_600_000); |
| 1070 | yield* connectWith(ENCODED_SERVER_CONFIG); |
| 1071 | expect(toServerClock(PREPARED.environmentId, 0)).toBe(0); |
| 1072 | }), |
| 1073 | ); |
| 1074 | |
| 1075 | it.effect("reaches ready when a newer server sends unknown config members", () => |
| 1076 | Effect.gen(function* () { |
| 1077 | const { factory, sockets } = yield* makeFactory(); |
| 1078 | const session = yield* factory.connect(PREPARED); |
| 1079 | const readyFiber = yield* Effect.forkChild(session.ready); |
| 1080 | const socket = yield* awaitSocket(sockets); |
| 1081 | socket.open(); |
| 1082 | |
| 1083 | const shortcut = { |
| 1084 | key: "p", |
| 1085 | metaKey: false, |
| 1086 | ctrlKey: false, |
| 1087 | shiftKey: false, |
| 1088 | altKey: false, |
| 1089 | modKey: true, |
| 1090 | }; |
| 1091 | yield* completeInitialConfig(socket, { |
| 1092 | ...ENCODED_SERVER_CONFIG, |
| 1093 | keybindings: [ |
| 1094 | { command: "someFuture.toggle", shortcut }, |
| 1095 | { command: "terminal.toggle", shortcut }, |
| 1096 | ], |
| 1097 | issues: [{ kind: "keybindings.future-issue", message: "From a newer server" }], |
| 1098 | availableEditors: ["some-future-editor", "zed"], |
| 1099 | }); |
| 1100 | yield* Fiber.join(readyFiber); |
| 1101 | |
| 1102 | const config = yield* session.initialConfig; |
| 1103 | expect(config.keybindings).toEqual([{ command: "terminal.toggle", shortcut }]); |
| 1104 | expect(config.issues).toEqual([]); |
| 1105 | expect(config.availableEditors).toEqual(["zed"]); |
| 1106 | }), |
| 1107 | ); |
| 1108 | }); |