import { observeAtomQuery, observeAtomCommand, createAtomCommandScheduler, createEnvironmentQueryAtomFamily, createEnvironmentRpcSubscriptionAtomFamily, isAtomCommandInterrupted, selectEnvironmentQueryData, createEnvironmentSubscriptionAtomFamily, createRuntimeCommand, environmentSessionGenerationAtom, type QueryAnswerHandler, } from "./runtime.ts"; import { describe, expect, it } from "@effect/vitest"; import * as NodeV8 from "node:v8"; import * as NodeVM from "node:vm"; import { vi } from "vite-plus/test"; import { DEFAULT_MAX_TERMINAL_BUFFER_BYTES, EnvironmentId, type FilesystemBrowseEntry, ORCHESTRATION_V2_WS_METHODS, type OrchestrationV2ArchivedShellSnapshot, ThreadId, ProjectId, type ReviewDiffPreviewInput, type PreviewEvent, type TerminalAttachInput, type TerminalAttachStreamEvent, type TerminalMetadataStreamEvent, type TerminalSummary, WS_METHODS, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; 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 Latch from "effect/Latch"; 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 type { HttpClient } from "effect/http"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { AVAILABLE_CONNECTION_STATE, ConnectionBlockedError, ConnectionTransientError, PrimaryConnectionTarget, type PreparedConnection, type SupervisorConnectionState, } from "../connection/model.ts"; import * as EnvironmentRegistry from "../connection/registry.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import { EnvironmentRpcUnavailableError } from "../rpc/client.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import type * as RpcSession from "../rpc/session.ts"; import { createOrchestrationEnvironmentAtoms } from "./orchestration.ts"; import { createReviewEnvironmentAtoms } from "./review.ts"; import { createPreviewEnvironmentAtoms } from "./preview.ts"; import { createFilesystemEnvironmentAtoms } from "./filesystem.ts"; import type { QueryPersistence } from "./queryPersistence.ts"; import type { EnvironmentShellState } from "./shell.ts"; import { v2Now, v2Project, v2ThreadId, v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; import { createTerminalEnvironmentAtoms } from "./terminal.ts"; const QUERY_ENVIRONMENT = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("query-environment"), label: "Query environment", httpBaseUrl: "https://query.example.test", wsBaseUrl: "wss://query.example.test", }); const decodeNumber = Schema.decodeUnknownEffect(Schema.Number); const QUERY_RPC_SESSION = {} as RpcSession.RpcSession; class TestQueryError extends Schema.TaggedError()("TestQueryError", { message: Schema.String, }) {} const OFFLINE_QUERY_FAILURE = new ConnectionTransientError({ reason: "transport", detail: "Relay is unavailable.", }); const BLOCKED_QUERY_FAILURE = new ConnectionBlockedError({ reason: "permission", detail: "Access denied.", }); function queryConnectionState( overrides: Partial = {}, ): SupervisorConnectionState { return { ...AVAILABLE_CONNECTION_STATE, desired: true, network: "online", phase: "connected", attempt: 1, generation: 1, ...overrides, }; } const makeEnvironmentQueryHarness = Effect.fn("TestEnvironmentQuery.makeHarness")(function* ( execute: Effect.Effect, { refreshTrigger, idleTtlMs, persistence, initialState, rpcSession, isFinal, onAnswer, }: { readonly refreshTrigger?: Atom.Atom; readonly onAnswer?: QueryAnswerHandler; readonly isFinal?: (value: A) => boolean; readonly idleTtlMs?: number; readonly persistence?: QueryPersistence; readonly initialState?: SupervisorConnectionState; readonly rpcSession?: RpcSession.RpcSession; } = {}, ) { const supervisorState = yield* SubscriptionRef.make(initialState ?? queryConnectionState()); const supervisorSession = yield* SubscriptionRef.make( Option.some(rpcSession ?? QUERY_RPC_SESSION), ); const streamGeneration = yield* SubscriptionRef.make(0); const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ target: QUERY_ENVIRONMENT, state: supervisorState, session: supervisorSession, prepared: yield* SubscriptionRef.make>(Option.none()), connect: Effect.void, disconnect: Effect.void, retryNow: Effect.void, } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (_environmentId, effect) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor); const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = ( _environmentId, stream, ) => SubscriptionRef.changes(streamGeneration).pipe( Stream.switchMap(() => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor), ), ); const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({ run, followStream, stateChanges: () => SubscriptionRef.changes(supervisorState), } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); const runtime = Atom.runtime( Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), ); const family = createEnvironmentQueryAtomFamily(runtime, { label: "test.environment-query", staleTimeMs: 60_000, ...(persistence === undefined ? {} : { persistence }), execute: () => execute, ...(refreshTrigger === undefined ? {} : { refreshTrigger: () => refreshTrigger }), ...(idleTtlMs === undefined ? {} : { idleTtlMs }), ...(isFinal === undefined ? {} : { isFinal }), ...(onAnswer === undefined ? {} : { onAnswer }), }); return { runtime, family, atom: family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }), supervisorSession, supervisorState, streamGeneration, }; }); /** * `getResult` resumes from inside the query's listener, so it only unsubscribes * once the reader yields. */ const readEnvironmentQuery = ( registry: AtomRegistry.AtomRegistry, atom: Atom.Atom>, ) => AtomRegistry.getResult(registry, atom, { suspendOnWaiting: true }).pipe( Effect.tap(() => Effect.yieldNow), ); const mountEnvironmentQuery = Effect.fn("TestEnvironmentQuery.mount")(function* ( atom: Atom.Atom>, ) { const registry = AtomRegistry.make(); const unmount = registry.mount(atom); yield* Effect.addFinalizer(() => Effect.sync(() => { unmount(); registry.dispose(); }), ); return registry; }); it.effect("keeps complete review metadata visible while a refresh is held", () => Effect.gen(function* () { const started = yield* Deferred.make(); const release = yield* Deferred.make(); let fullReads = 0; const rpcSession = { client: { [WS_METHODS.reviewGetDiffPreview]: (input: ReviewDiffPreviewInput) => Effect.gen(function* () { if (!input.trackedOnly && ++fullReads > 1) { yield* Deferred.succeed(started, undefined); yield* Deferred.await(release); } return { cwd: input.cwd, generatedAt: DateTime.makeUnsafe(0), ...(input.trackedOnly ? { incomplete: true } : {}), sources: [ { id: "working-tree", kind: "working-tree" as const, title: "Uncommitted", baseRef: "HEAD", headRef: null, diff: "", diffHash: String(fullReads), truncated: false, patchesDeferred: true, files: (input.trackedOnly ? ["tracked"] : ["tracked", "untracked"]).map( (path) => ({ path, previousPath: null, additions: 1, deletions: 0 }), ), }, ], }; }), }, } as unknown as RpcSession.RpcSession; const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession }); const atom = createReviewEnvironmentAtoms(harness.runtime).diffPreview({ environmentId: QUERY_ENVIRONMENT.environmentId, input: { cwd: "/project", sourceKind: "working-tree", metadataOnly: true }, }); const registry = yield* mountEnvironmentQuery(atom); expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.files).toHaveLength(2); registry.refresh(atom); yield* Deferred.await(started); yield* Effect.sync(() => { const value = AsyncResult.getOrElse(registry.get(atom), () => null); expect(value?.incomplete).not.toBe(true); expect(value?.sources[0]!.files).toHaveLength(2); }).pipe(Effect.ensuring(Deferred.succeed(release, undefined))); expect((yield* readEnvironmentQuery(registry, atom)).sources[0]!.diffHash).toBe("2"); }), ); describe("preview event subscriptions", () => { it.effect("delivers every open and close when RPC events arrive in batches", () => Effect.gen(function* () { const opened: PreviewEvent[] = ["thread-a", "thread-b"].map((threadId, index) => ({ type: "opened", threadId, tabId: `tab-${index}`, serverEpoch: "epoch-1", revision: index + 1, createdAt: "2026-10-02T00:00:00.000Z", snapshot: { threadId, tabId: `tab-${index}`, navStatus: { _tag: "Idle" }, canGoBack: false, canGoForward: false, updatedAt: "2026-10-02T00:00:00.000Z", }, })); const closed: PreviewEvent[] = opened.map((event, index) => ({ type: "closed", threadId: event.threadId, tabId: event.tabId, serverEpoch: event.serverEpoch, revision: opened.length + index + 1, createdAt: event.createdAt, })); const releaseEvents = yield* Deferred.make(); // Each iterable is one RPC chunk; separate emissions would hide lost events. const stream = Stream.fromEffect(Deferred.await(releaseEvents)).pipe( Stream.flatMap(() => Stream.fromIterable(opened).pipe( Stream.concat(Stream.fromIterable(closed)), Stream.concat(Stream.never), ), ), ); const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession: { client: { [WS_METHODS.subscribePreviewEvents]: () => stream }, } as unknown as RpcSession.RpcSession, }); const atom = createPreviewEnvironmentAtoms(harness.runtime).events({ environmentId: QUERY_ENVIRONMENT.environmentId, input: {}, }); const registry = AtomRegistry.make(); const observed: PreviewEvent[] = []; const sawLast = yield* Deferred.make(); const unsubscribe = registry.subscribe( atom, (result) => { if (!AsyncResult.isSuccess(result)) return; observed.push(result.value); if (result.value === closed[closed.length - 1]) { Deferred.doneUnsafe(sawLast, Exit.void); } }, { immediate: true }, ); yield* Effect.addFinalizer(() => Effect.sync(() => { unsubscribe(); registry.dispose(); }), ); yield* Deferred.succeed(releaseEvents, undefined); yield* Deferred.await(sawLast); expect(observed).toEqual([...opened, ...closed]); }), ); }); describe("finite environment subscription lifecycle", () => { it.effect( "exposes early values and settles on the terminal value without waiting for a reconnect", () => Effect.gen(function* () { const releaseFinal = yield* Deferred.make(); const sawEarly = yield* Deferred.make(); const sawFinal = yield* Deferred.make(); const closed = yield* Deferred.make(); const stream = Stream.concat( Stream.succeed({ complete: false, count: 1 }), Stream.fromEffect( Deferred.await(releaseFinal).pipe(Effect.as({ complete: true, count: 123 })), ), ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))); const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({ followStream: (_environmentId: EnvironmentId, source: typeof stream) => Stream.concat(source, Stream.never), } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); const runtime = Atom.runtime( Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), ); const family = createEnvironmentSubscriptionAtomFamily(runtime, { label: "test.finite-subscription", subscribe: () => stream, completeWhen: (value) => value.complete, idleTtlMs: 0, }); const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }); const registry = AtomRegistry.make(); const observed: Array< AsyncResult.AsyncResult<{ complete: boolean; count: number }, unknown> > = []; const unsubscribe = registry.subscribe( atom, (result) => { observed.push(result); if (AsyncResult.isSuccess(result)) { if (!result.value.complete) Deferred.doneUnsafe(sawEarly, Exit.void); if (result.value.complete && !result.waiting) Deferred.doneUnsafe(sawFinal, Exit.void); } }, { immediate: true }, ); yield* Effect.addFinalizer(() => Effect.sync(() => { unsubscribe(); registry.dispose(); }), ); yield* Deferred.await(sawEarly); const early = registry.get(atom); expect(AsyncResult.isSuccess(early) && early.value.count).toBe(1); expect(early.waiting).toBe(true); yield* Deferred.succeed(releaseFinal, undefined); yield* Deferred.await(sawFinal); yield* Deferred.await(closed); const final = registry.get(atom); expect(AsyncResult.isSuccess(final) && final.value.count).toBe(123); expect(final.waiting).toBe(false); expect(observed.some((result) => AsyncResult.isFailure(result))).toBe(false); }), ); it.effect( "surfaces a decode defect from a finite RPC subscription instead of resubscribing", () => Effect.scoped( Effect.gen(function* () { const firstSubscribed = yield* Deferred.make(); const resubscribed = yield* Deferred.make(); const surfaced = yield* Deferred.make>(); let subscriptions = 0; // Mirrors RpcClient, which decodes each chunk with `Effect.orDie`. const decodeDefect = decodeNumber("not a number").pipe(Effect.orDie); const client = { [ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: () => { subscriptions += 1; Deferred.doneUnsafe(subscriptions === 1 ? firstSubscribed : resubscribed, Exit.void); return Stream.fromEffect(decodeDefect).pipe(Stream.drain); }, } as unknown as WsRpcProtocolClient; const rpcSession = { client, initialConfig: Effect.never, subscribeServerConfig: () => Stream.never, ready: Effect.void, probe: Effect.void, closed: Effect.never, } as unknown as RpcSession.RpcSession; const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ target: QUERY_ENVIRONMENT, state: yield* SubscriptionRef.make(queryConnectionState()), session: yield* SubscriptionRef.make(Option.some(rpcSession)), prepared: yield* SubscriptionRef.make>(Option.none()), connect: Effect.void, disconnect: Effect.void, retryNow: Effect.void, } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({ followStream: (_environmentId: EnvironmentId, stream: Stream.Stream) => Stream.provideService( stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor, ), } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); // Atoms run their own fibers; share the test clock so a pending retry is driven by it. const runtime = Atom.runtime( Layer.mergeAll( Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), Layer.succeed(Clock.Clock, yield* Clock.Clock), ), ); // Same options as the progressive thread find in orchestration.ts. const family = createEnvironmentRpcSubscriptionAtomFamily(runtime, { label: "test.finite-rpc-subscription", tag: ORCHESTRATION_V2_WS_METHODS.searchThreadStream, completeWhen: (result) => result.complete !== false, idleTtlMs: 0, }); const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: {} as never, }); const registry = AtomRegistry.make(); const unsubscribe = registry.subscribe( atom, (result) => { if (AsyncResult.isFailure(result)) Deferred.doneUnsafe(surfaced, Exit.succeed(result.cause)); }, { immediate: true }, ); yield* Effect.addFinalizer(() => Effect.sync(() => { unsubscribe(); registry.dispose(); }), ); yield* Deferred.await(firstSubscribed); // Lets any same-session retry run, so its resubscription can win the race below. yield* TestClock.adjust("1 minute"); const outcome = yield* Effect.raceFirst( Deferred.await(surfaced).pipe( Effect.map((cause) => ({ _tag: "surfaced", cause }) as const), ), Deferred.await(resubscribed).pipe(Effect.as({ _tag: "resubscribed" } as const)), ); expect( outcome._tag, "finite subscription resubscribed after a decode defect instead of failing its consumer", ).toBe("surfaced"); if (outcome._tag === "surfaced") { expect(Cause.hasDies(outcome.cause)).toBe(true); expect(Schema.isSchemaError(Cause.squash(outcome.cause))).toBe(true); } expect(subscriptions).toBe(1); }), ), ); it.effect.each([ { completedTtlMs: undefined, subscriptions: 2 }, { completedTtlMs: 60_000, subscriptions: 1 }, ])( "reopening a completed subscription subscribes $subscriptions time(s) with completedTtlMs $completedTtlMs", ({ completedTtlMs, subscriptions }) => Effect.gen(function* () { let subscribed = 0; const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({ followStream: (_environmentId: EnvironmentId, source: Stream.Stream) => source, } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]); const runtime = Atom.runtime( Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry), ); const family = createEnvironmentSubscriptionAtomFamily(runtime, { label: "test.completed-subscription", subscribe: () => Stream.suspend(() => { subscribed += 1; return Stream.make({ complete: false }, { complete: true }); }), completeWhen: (value) => value.complete, idleTtlMs: 0, ...(completedTtlMs === undefined ? {} : { completedTtlMs }), }); const atom = family({ environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }); // Flushed after each close: idle removals have run by the time a user reopens a row. const scheduled: Array<() => void> = []; const registry = AtomRegistry.make({ scheduleTask: (task) => { scheduled.push(task); return () => undefined; }, }); const open = Effect.gen(function* () { const settled = yield* Deferred.make(); const unsubscribe = registry.subscribe( atom, (result) => { if (AsyncResult.isSuccess(result) && !result.waiting) { Deferred.doneUnsafe(settled, Exit.succeed(result.value.complete)); } }, { immediate: true }, ); const complete = yield* Deferred.await(settled); unsubscribe(); for (const task of scheduled.splice(0)) task(); return complete; }); expect(yield* open).toBe(true); expect(yield* open).toBe(true); expect(subscribed).toBe(subscriptions); registry.dispose(); }), ); }); describe("environment query lifecycle", () => { it.effect( "terminal metadata waits for snapshots and retains known sessions across restarts", () => Effect.gen(function* () { const harness = yield* makeEnvironmentQueryHarness(Effect.void); const started = yield* Queue.unbounded(); const events = yield* Queue.unbounded(); const receivedCheckout = yield* Deferred.make(); const receivedEmpty = yield* Deferred.make(); const checkout: TerminalSummary = { threadId: "thread-1", terminalId: "terminal-1", cwd: "/repo/root/packages/app", worktreePath: null, status: "running", pid: 123, exitCode: null, exitSignal: null, hasRunningSubprocess: false, label: "Terminal 1", updatedAt: "2026-04-01T00:00:00.000Z", }; const client = { [WS_METHODS.subscribeTerminalMetadata]: () => Stream.fromEffect(Queue.offer(started, undefined)).pipe( Stream.drain, Stream.concat(Stream.fromQueue(events)), ), } as unknown as RpcSession.RpcSession["client"]; const session = { ...QUERY_RPC_SESSION, client }; yield* SubscriptionRef.set(harness.supervisorSession, Option.some(session)); const atoms = createTerminalEnvironmentAtoms(harness.runtime); const atom = atoms.metadata({ environmentId: QUERY_ENVIRONMENT.environmentId, input: null, }); const registry = AtomRegistry.make(); const observed: Array> = []; const unsubscribe = registry.subscribe( atom, (result) => { if (!AsyncResult.isSuccess(result)) return; observed.push(result.value); if (result.value.length > 0) Deferred.doneUnsafe(receivedCheckout, Exit.void); else Deferred.doneUnsafe(receivedEmpty, Exit.void); }, { immediate: true }, ); yield* Effect.addFinalizer(() => Effect.sync(() => { unsubscribe(); registry.dispose(); }), ); yield* Queue.take(started); expect(selectEnvironmentQueryData(registry.get(atom))).toBeNull(); expect(observed).toEqual([]); yield* Queue.offer(events, { type: "snapshot", terminals: [checkout] }); yield* Deferred.await(receivedCheckout); expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]); yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...session })); yield* Queue.take(started); expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]); yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1); yield* Queue.take(started); expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([checkout]); yield* Queue.offer(events, { type: "snapshot", terminals: [] }); yield* Deferred.await(receivedEmpty); expect(selectEnvironmentQueryData(registry.get(atom))).toEqual([]); }), ); it.effect("terminal attach resubscribes with resume only after the stream replied", () => Effect.gen(function* () { const harness = yield* makeEnvironmentQueryHarness(Effect.void); const inputs = yield* Queue.unbounded(); const events = yield* Queue.unbounded(); const received = yield* Deferred.make(); const client = { [WS_METHODS.terminalAttach]: (input: TerminalAttachInput) => Stream.fromEffect(Queue.offer(inputs, input)).pipe( Stream.drain, Stream.concat(Stream.fromQueue(events)), ), } as unknown as RpcSession.RpcSession["client"]; const firstSession = { ...QUERY_RPC_SESSION, client }; yield* SubscriptionRef.set(harness.supervisorSession, Option.some(firstSession)); const input = { threadId: "thread-1", terminalId: "terminal-1", cwd: "/tmp/project", restartIfNotRunning: true, }; const sent = { ...input, maxHistoryBytes: DEFAULT_MAX_TERMINAL_BUFFER_BYTES }; const atoms = createTerminalEnvironmentAtoms(harness.runtime); const registry = AtomRegistry.make(); const atom = atoms.attach({ environmentId: QUERY_ENVIRONMENT.environmentId, input }); const unmount = registry.subscribe( atom, (result) => { if (AsyncResult.isSuccess(result) && result.value.version > 0) { Deferred.doneUnsafe(received, Exit.void); } }, { immediate: true }, ); yield* Effect.addFinalizer(() => Effect.sync(() => { unmount(); registry.dispose(); }), ); expect(yield* Queue.take(inputs)).toEqual(sent); yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession })); expect(yield* Queue.take(inputs)).toEqual(sent); yield* Queue.offer(events, { type: "closed", threadId: input.threadId, terminalId: input.terminalId, }); yield* Deferred.await(received); yield* SubscriptionRef.set(harness.supervisorSession, Option.some({ ...firstSession })); expect(yield* Queue.take(inputs)).toEqual({ ...sent, resume: true }); // Catalog replacements rerun the same stream through followStream's switchMap. yield* SubscriptionRef.update(harness.streamGeneration, (generation) => generation + 1); expect(yield* Queue.take(inputs)).toEqual({ ...sent, resume: true }); unmount(); registry.dispose(); const remountedRegistry = AtomRegistry.make(); const remount = remountedRegistry.subscribe(atom, () => {}, { immediate: true }); yield* Effect.addFinalizer(() => Effect.sync(() => { remount(); remountedRegistry.dispose(); }), ); expect(yield* Queue.take(inputs)).toEqual(sent); }), ); // The server sizes a shared PTY to every attached viewer, so a lingering attach pins its grid. it.effect("terminal attach detaches as soon as its last viewer leaves", () => Effect.gen(function* () { const harness = yield* makeEnvironmentQueryHarness(Effect.void); const attached = yield* Deferred.make(); const detached = yield* Deferred.make(); const client = { [WS_METHODS.terminalAttach]: () => Stream.fromEffect(Deferred.succeed(attached, undefined)).pipe( Stream.drain, Stream.concat(Stream.never), Stream.ensuring(Deferred.succeed(detached, undefined)), ), } as unknown as RpcSession.RpcSession["client"]; yield* SubscriptionRef.set( harness.supervisorSession, Option.some({ ...QUERY_RPC_SESSION, client }), ); const atoms = createTerminalEnvironmentAtoms(harness.runtime); const registry = AtomRegistry.make(); yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); const unsubscribe = registry.subscribe( atoms.attach({ environmentId: QUERY_ENVIRONMENT.environmentId, input: { threadId: "thread-1", terminalId: "terminal-1", cwd: "/tmp/project" }, }), () => {}, { immediate: true }, ); yield* Deferred.await(attached); unsubscribe(); yield* Deferred.await(detached); }), ); it.effect( "hides a session replacement, reports the relay backoff, and recovers on reconnect", () => Effect.gen(function* () { const firstStarted = Latch.makeUnsafe(); const failFirst = Latch.makeUnsafe(); const firstSettled = Latch.makeUnsafe(); const unavailable = new EnvironmentRpcUnavailableError({ environmentId: QUERY_ENVIRONMENT.environmentId, message: "Query environment is not connected.", }); let executions = 0; const execute = Effect.suspend(() => { executions += 1; if (executions > 1) { return Effect.succeed("recovered"); } firstStarted.openUnsafe(); return failFirst.await.pipe( Effect.andThen(Effect.fail(unavailable)), Effect.ensuring( Effect.sync(() => { firstSettled.openUnsafe(); }), ), ); }); const harness = yield* makeEnvironmentQueryHarness(execute); const registry = AtomRegistry.make(); const observed: Array> = []; const unsubscribe = registry.subscribe( harness.atom, (result) => { observed.push(result); }, { immediate: true }, ); yield* Effect.addFinalizer(() => Effect.sync(() => { unsubscribe(); registry.dispose(); }), ); yield* firstStarted.await; yield* SubscriptionRef.set(harness.supervisorSession, Option.none()); yield* Effect.yieldNow; failFirst.openUnsafe(); yield* firstSettled.await; yield* Effect.yieldNow; expect(observed.some(AsyncResult.isFailure)).toBe(false); yield* SubscriptionRef.set( harness.supervisorState, queryConnectionState({ phase: "connecting", stage: "preparing" }), ); yield* Effect.yieldNow; const relayFailure = new ConnectionTransientError({ reason: "transport", detail: "Relay session is reconnecting.", }); yield* SubscriptionRef.set( harness.supervisorState, queryConnectionState({ phase: "backoff", stage: null, lastFailure: relayFailure, retryAt: 1, }), ); yield* Effect.yieldNow; // The query has never answered, so it reports why the environment is retrying. const backingOff = registry.get(harness.atom); expect(backingOff.waiting).toBe(false); expect(AsyncResult.isFailure(backingOff) && Cause.squash(backingOff.cause)).toBe( relayFailure, ); yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION)); yield* SubscriptionRef.set( harness.supervisorState, queryConnectionState({ generation: 2 }), ); yield* Effect.yieldNow; expect( yield* AtomRegistry.getResult(registry, harness.atom, { suspendOnWaiting: true, }), ).toBe("recovered"); }), ); it.effect("keeps a query pending when it loses its session before the atom sees the change", () => Effect.gen(function* () { const firstStarted = Latch.makeUnsafe(); const failFirst = Latch.makeUnsafe(); const firstSettled = Latch.makeUnsafe(); let executions = 0; const execute = Effect.suspend(() => { executions += 1; if (executions > 1) { return Effect.succeed("recovered"); } firstStarted.openUnsafe(); return failFirst.await.pipe( Effect.andThen( Effect.fail( new EnvironmentRpcUnavailableError({ environmentId: QUERY_ENVIRONMENT.environmentId, message: "Query environment is not connected.", }), ), ), Effect.ensuring( Effect.sync(() => { firstSettled.openUnsafe(); }), ), ); }); const harness = yield* makeEnvironmentQueryHarness(execute); const registry = AtomRegistry.make(); const observed: Array> = []; const unsubscribe = registry.subscribe( harness.atom, (result) => { observed.push(result); }, { immediate: true }, ); yield* Effect.addFinalizer(() => Effect.sync(() => { unsubscribe(); registry.dispose(); }), ); yield* firstStarted.await; // No yield before the failure: the request finds its session gone // before the atom has processed the session change. yield* SubscriptionRef.set(harness.supervisorSession, Option.none()); failFirst.openUnsafe(); yield* firstSettled.await; yield* Effect.yieldNow; expect(observed.some(AsyncResult.isFailure)).toBe(false); yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION)); yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 })); expect( yield* AtomRegistry.getResult(registry, harness.atom, { suspendOnWaiting: true, }), ).toBe("recovered"); expect(observed.some(AsyncResult.isFailure)).toBe(false); }), ); it.effect("fails a query that reports unavailable while its session is still live", () => Effect.gen(function* () { const unavailable = new EnvironmentRpcUnavailableError({ environmentId: QUERY_ENVIRONMENT.environmentId, message: "The environment did not respond to the request.", }); const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable)); const registry = yield* mountEnvironmentQuery(harness.atom); const exit = yield* AtomRegistry.getResult(registry, harness.atom, { suspendOnWaiting: true, }).pipe(Effect.exit); expect(exit).toStrictEqual(Exit.fail(unavailable)); }), ); it.effect.each([ { condition: "after a manual disconnect", state: queryConnectionState({ desired: false, phase: "available", stage: null, attempt: 0, }), expectedFailure: null, }, { condition: "while the environment is offline", state: queryConnectionState({ network: "offline", phase: "offline", stage: null, lastFailure: OFFLINE_QUERY_FAILURE, }), expectedFailure: OFFLINE_QUERY_FAILURE, }, { condition: "when connection recovery is blocked", state: queryConnectionState({ phase: "blocked", stage: null, lastFailure: BLOCKED_QUERY_FAILURE, }), expectedFailure: BLOCKED_QUERY_FAILURE, }, ] as const)("settles as unavailable $condition", ({ state, expectedFailure }) => Effect.gen(function* () { const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected")); const registry = yield* mountEnvironmentQuery(harness.atom); expect( yield* AtomRegistry.getResult(registry, harness.atom, { suspendOnWaiting: true, }), ).toBe("connected"); yield* SubscriptionRef.set(harness.supervisorState, state); yield* Effect.yieldNow; const result = registry.get(harness.atom); expect(AsyncResult.isFailure(result)).toBe(true); expect(result.waiting).toBe(false); if (AsyncResult.isFailure(result) && expectedFailure !== null) { expect(Cause.squash(result.cause)).toBe(expectedFailure); } }), ); it.effect.each([ { phase: "backoff", stage: null, retryAt: 1 }, { phase: "connecting", stage: "opening", retryAt: null }, ] as const)( "settles a query it never answered while its environment retries ($phase)", (retrying) => Effect.gen(function* () { const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), { initialState: queryConnectionState({ ...retrying, lastFailure: OFFLINE_QUERY_FAILURE }), }); const registry = yield* mountEnvironmentQuery(harness.atom); yield* Effect.yieldNow; const result = registry.get(harness.atom); expect(result.waiting).toBe(false); expect(AsyncResult.isFailure(result) && Cause.squash(result.cause)).toBe( OFFLINE_QUERY_FAILURE, ); yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState()); yield* Effect.yieldNow; expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("connected"); }), ); it.effect("a refresh started on a new session generation answers from that session", () => Effect.gen(function* () { const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("connected"), { initialState: queryConnectionState({ phase: "backoff", stage: null, lastFailure: OFFLINE_QUERY_FAILURE, retryAt: 1, }), }); const registry = yield* mountEnvironmentQuery(harness.atom); // Callers hold the failure a read got while the environment was retrying. const failed = yield* observeAtomQuery(registry, harness.atom, { reportFailure: false }); expect(AsyncResult.isFailure(failed)).toBe(true); const generationChanged = yield* Deferred.make(); const sessionGeneration = environmentSessionGenerationAtom( harness.runtime, QUERY_ENVIRONMENT.environmentId, ); const unmount = registry.mount(sessionGeneration); const unsubscribe = registry.subscribe(sessionGeneration, () => { Deferred.doneUnsafe(generationChanged, Effect.void); }); const answered = yield* Effect.forkChild( Deferred.await(generationChanged).pipe( Effect.andThen( observeAtomQuery(registry, harness.atom, { refresh: true, reportFailure: false, }), ), ), ); yield* Effect.addFinalizer(() => Effect.sync(() => { unsubscribe(); unmount(); }), ); yield* Effect.yieldNow; yield* SubscriptionRef.set( harness.supervisorSession, Option.some({} as RpcSession.RpcSession), ); yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 })); expect(yield* Fiber.join(answered)).toMatchObject({ _tag: "Success", value: "connected", }); }), ); it.effect("keeps a genuine query failure settled while reconnecting", () => Effect.gen(function* () { const expectedFailure = new TestQueryError({ message: "Query failed." }); const firstStarted = Latch.makeUnsafe(); const failFirst = Latch.makeUnsafe(); const refreshStarted = Latch.makeUnsafe(); const finishRefresh = Latch.makeUnsafe(); let executions = 0; const execute = Effect.suspend(() => { executions += 1; if (executions === 1) { firstStarted.openUnsafe(); return failFirst.await.pipe(Effect.andThen(Effect.fail(expectedFailure))); } refreshStarted.openUnsafe(); return finishRefresh.await.pipe(Effect.as("recovered")); }); const harness = yield* makeEnvironmentQueryHarness(execute); const registry = yield* mountEnvironmentQuery(harness.atom); yield* firstStarted.await; failFirst.openUnsafe(); const initial = yield* AtomRegistry.getResult(registry, harness.atom, { suspendOnWaiting: true, }).pipe(Effect.exit); expect(Exit.isFailure(initial)).toBe(true); if (Exit.isFailure(initial)) { expect(Cause.squash(initial.cause)).toBe(expectedFailure); } yield* SubscriptionRef.set( harness.supervisorState, queryConnectionState({ phase: "connecting", stage: "opening" }), ); yield* Effect.yieldNow; const refreshing = registry.get(harness.atom); expect(AsyncResult.isFailure(refreshing)).toBe(true); expect(refreshing.waiting).toBe(true); if (AsyncResult.isFailure(refreshing)) { expect(Cause.squash(refreshing.cause)).toBe(expectedFailure); } yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 })); yield* refreshStarted.await; finishRefresh.openUnsafe(); expect( yield* AtomRegistry.getResult(registry, harness.atom, { suspendOnWaiting: true, }), ).toBe("recovered"); }), ); it.effect("retains the last successful value while reconnecting", () => Effect.gen(function* () { const refreshStarted = Latch.makeUnsafe(); const finishRefresh = Latch.makeUnsafe(); let executions = 0; const execute = Effect.suspend(() => { executions += 1; if (executions === 1) { return Effect.succeed("cached"); } refreshStarted.openUnsafe(); return finishRefresh.await.pipe(Effect.as("updated")); }); const harness = yield* makeEnvironmentQueryHarness(execute); const registry = yield* mountEnvironmentQuery(harness.atom); expect( yield* AtomRegistry.getResult(registry, harness.atom, { suspendOnWaiting: true, }), ).toBe("cached"); yield* SubscriptionRef.set( harness.supervisorState, queryConnectionState({ phase: "connecting", stage: "opening" }), ); yield* Effect.yieldNow; expect(registry.get(harness.atom)).toMatchObject({ _tag: "Success", value: "cached", waiting: true, }); yield* SubscriptionRef.set( harness.supervisorState, queryConnectionState({ phase: "backoff", stage: null, lastFailure: new ConnectionTransientError({ reason: "transport", detail: "Retrying.", }), retryAt: 1, }), ); yield* Effect.yieldNow; expect(registry.get(harness.atom)).toMatchObject({ _tag: "Success", value: "cached", waiting: true, }); yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState({ generation: 2 })); yield* refreshStarted.await; expect(registry.get(harness.atom)).toMatchObject({ _tag: "Success", value: "cached", waiting: true, }); finishRefresh.openUnsafe(); expect( yield* AtomRegistry.getResult(registry, harness.atom, { suspendOnWaiting: true, }), ).toBe("updated"); }), ); it.effect("filesystem browse lists the directory afresh when a picker reopens it", () => Effect.gen(function* () { const harness = yield* makeEnvironmentQueryHarness(Effect.void); const entry = (name: string): FilesystemBrowseEntry => ({ name, fullPath: `/tmp/t3-11476-repro/${name}`, }); let onDisk = [entry("existing")]; const client = { [WS_METHODS.filesystemBrowse]: () => Effect.sync(() => ({ parentPath: "/tmp/t3-11476-repro/", entries: onDisk })), } as unknown as RpcSession.RpcSession["client"]; yield* SubscriptionRef.set( harness.supervisorSession, Option.some({ ...QUERY_RPC_SESSION, client }), ); const atom = createFilesystemEnvironmentAtoms(harness.runtime).browse({ environmentId: QUERY_ENVIRONMENT.environmentId, input: { partialPath: "/tmp/t3-11476-repro/" }, }); const registry = AtomRegistry.make(); yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); // Stale-while-revalidate refreshes from a task on the registry scheduler; // queue behind it so the read sees the revalidation instead of racing it. const afterScheduledTasks = Effect.callback((resume) => { registry.schedulerAsync.makeDispatcher().scheduleTask(() => resume(Effect.void), 0); }); const listNames = afterScheduledTasks.pipe( Effect.andThen(readEnvironmentQuery(registry, atom)), Effect.map((result) => result.entries.map((browseEntry) => browseEntry.name)), ); const closePicker = registry.mount(atom); expect(yield* listNames).toEqual(["existing"]); closePicker(); // A closed picker stays closed past the registry's scheduled node // removal; a remount within the same tick keeps the live node. yield* afterScheduledTasks; onDisk = [entry("created-externally"), entry("existing")]; registry.mount(atom); expect(yield* listNames).toEqual(["created-externally", "existing"]); }), ); it.effect("refreshes on its trigger while read, and once on its next read when idle", () => Effect.gen(function* () { let executions = 0; const trigger = Atom.make(0).pipe(Atom.keepAlive); const harness = yield* makeEnvironmentQueryHarness( Effect.sync(() => (executions += 1)), { refreshTrigger: trigger }, ); const registry = AtomRegistry.make(); yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); const read = readEnvironmentQuery(registry, harness.atom); const unmount = registry.mount(harness.atom); expect(yield* read).toBe(1); registry.set(trigger, 1); expect(yield* read).toBe(2); unmount(); registry.set(trigger, 2); registry.set(trigger, 3); expect(executions).toBe(2); expect(yield* read).toBe(3); }), ); it.effect("refetches a stale query on remount while another view keeps the cache live", () => Effect.gen(function* () { let now = 0; using _now = vi.spyOn(Date, "now").mockImplementation(() => now); let contents = "before edit"; let fetches = 0; const harness = yield* makeEnvironmentQueryHarness( Effect.sync(() => { fetches += 1; return contents; }), ); const registry = AtomRegistry.make(); yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); const sidebar = harness.family( { environmentId: QUERY_ENVIRONMENT.environmentId, input: undefined }, "sidebar", ); registry.mount(sidebar); const read = readEnvironmentQuery(registry, harness.atom); const remount = Effect.gen(function* () { const unmount = registry.mount(harness.atom); yield* Effect.yieldNow; const value = yield* read; unmount(); yield* Effect.yieldNow; return value; }); expect(yield* remount).toBe("before edit"); contents = "after edit"; // Inside the harness's 60s stale time: the cached value stands. now = 30_000; expect(yield* remount).toBe("before edit"); expect(fetches).toBe(1); // Past the stale time, well inside the default 5 minute idle TTL. now = 61_000; expect(yield* remount).toBe("after edit"); expect(yield* readEnvironmentQuery(registry, sidebar)).toBe("after edit"); expect(fetches).toBe(2); }), ); it.effect("keeps its cache when collected while unmounted, inside its stale time", () => Effect.gen(function* () { NodeV8.setFlagsFromString("--expose-gc"); const gc = NodeVM.runInNewContext("gc") as () => void; using _now = vi.spyOn(Date, "now").mockReturnValue(0); let fetches = 0; const harness = yield* makeEnvironmentQueryHarness( Effect.sync(() => { fetches += 1; return fetches; }), ); const registry = AtomRegistry.make(); yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); // `Atom.family` holds members weakly, so the test must hold none: another environment // than `harness.atom`'s, which the harness holds. const environmentId = EnvironmentId.make("unheld-environment"); const query = () => harness.family({ environmentId, input: undefined }); const first = new WeakRef(query()); const remount = Effect.gen(function* () { const unmount = registry.mount(query()); yield* Effect.yieldNow; const value = yield* readEnvironmentQuery(registry, query()); unmount(); return value; }); // A WeakRef target survives until the current job ends, so collect after it. const collect = Effect.yieldNow.pipe(Effect.andThen(Effect.sync(gc))); expect(yield* remount).toBe(1); yield* collect; expect(yield* remount).toBe(1); yield* collect; expect(first.deref()).toBe(query()); expect(fetches).toBe(1); }), ); it.effect.each([true, false])("loads thread link metadata with server support %s", (supported) => Effect.gen(function* () { const projectId = ProjectId.make("project"); const tag = supported ? ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata : ORCHESTRATION_V2_WS_METHODS.getThreadTitles; const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession: { initialConfig: Effect.succeed({ threadLinkMetadata: supported }), client: { [tag]: () => Effect.succeed(supported ? { fork: { title: "Fork", projectId } } : { fork: "Fork" }), }, } as unknown as RpcSession.RpcSession, }); const runtime = harness.runtime as unknown as Atom.AtomRuntime< EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient >; const atom = createOrchestrationEnvironmentAtoms(runtime).threadLinkMetadata({ environmentId: QUERY_ENVIRONMENT.environmentId, input: { threadIds: [ThreadId.make("fork")] }, }); const registry = yield* mountEnvironmentQuery(atom); expect(yield* readEnvironmentQuery(registry, atom)).toEqual({ fork: { title: "Fork", projectId: supported ? projectId : null }, }); }), ); it.effect("re-checks thread titles when one of their threads leaves the shell", () => Effect.gen(function* () { const requests = yield* Queue.unbounded>>(); const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession: { client: { [ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: () => Effect.gen(function* () { const answer = yield* Deferred.make>(); yield* Queue.offer(requests, answer); return yield* Deferred.await(answer); }), }, } as unknown as RpcSession.RpcSession, }); const shellState = Atom.make>({ removedAt: new Map(), }).pipe(Atom.keepAlive); const removed = (entries: ReadonlyArray) => ({ removedAt: new Map(entries.map(([id, sequence]) => [ThreadId.make(id), sequence])), }); // Thread titles never use the HTTP client. const runtime = harness.runtime as unknown as Atom.AtomRuntime< EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient >; const atom = createOrchestrationEnvironmentAtoms(runtime, { shellState: () => shellState, }).threadTitles({ environmentId: QUERY_ENVIRONMENT.environmentId, input: { threadIds: [ThreadId.make("fork")] }, }); const registry = yield* mountEnvironmentQuery(atom); const settled: Array> = []; const unsubscribe = registry.subscribe(atom, (result) => { if (AsyncResult.isSuccess(result) && !result.waiting) settled.push(result.value); }); yield* Effect.addFinalizer(() => Effect.sync(unsubscribe)); yield* Deferred.succeed(yield* Queue.take(requests), { fork: "Fork" }); expect(yield* readEnvironmentQuery(registry, atom)).toEqual({ fork: "Fork" }); registry.set(shellState, removed([["other", 5]])); expect(registry.get(atom).waiting).toBe(false); // Archiving and then deleting the fork both remove it from the shell. registry.set(shellState, removed([["fork", 6]])); const beforeDelete = yield* Queue.take(requests); registry.set(shellState, removed([["fork", 7]])); const afterDelete = yield* Queue.take(requests); yield* Deferred.succeed(beforeDelete, { fork: "Fork" }); yield* Deferred.succeed(afterDelete, {}); expect(yield* readEnvironmentQuery(registry, atom)).toEqual({}); expect(settled).toEqual([{ fork: "Fork" }, {}]); }), ); it.effect("re-reads an open archive when a thread leaves the shell", () => Effect.gen(function* () { const requests = yield* Queue.unbounded>(); const harness = yield* makeEnvironmentQueryHarness(Effect.void, { rpcSession: { client: { [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: () => Effect.gen(function* () { const answer = yield* Deferred.make(); yield* Queue.offer(requests, answer); return yield* Deferred.await(answer); }), }, } as unknown as RpcSession.RpcSession, }); const shellState = Atom.make>({ removedAt: new Map(), }).pipe(Atom.keepAlive); const runtime = harness.runtime as unknown as Atom.AtomRuntime< EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient >; const atom = createOrchestrationEnvironmentAtoms(runtime, { shellState: () => shellState, }).archivedShellSnapshot({ environmentId: QUERY_ENVIRONMENT.environmentId, input: {} }); const page = (threads: OrchestrationV2ArchivedShellSnapshot["threads"]) => ({ schemaVersion: 1, snapshotSequence: 1, projects: [v2Project], threads, }); const registry = yield* mountEnvironmentQuery(atom); const archivedIds = Effect.map(readEnvironmentQuery(registry, atom), (snapshot) => snapshot.threads.map((thread) => thread.id), ); yield* Deferred.succeed(yield* Queue.take(requests), page([])); expect(yield* archivedIds).toEqual([]); // Another client archives the thread, then deletes it from the archive. registry.set(shellState, { removedAt: new Map([[v2ThreadId, 2]]) }); expect(registry.get(atom).waiting).toBe(true); yield* Deferred.succeed( yield* Queue.take(requests), page([{ ...v2ThreadShell, archivedAt: v2Now }]), ); expect(yield* archivedIds).toEqual([v2ThreadId]); registry.set(shellState, { removedAt: new Map([[v2ThreadId, 3]]) }); yield* Deferred.succeed(yield* Queue.take(requests), page([])); expect(yield* archivedIds).toEqual([]); }), ); }); describe("executeAtomQuery", () => { it.effect("keeps concurrent query results correlated to their atoms", () => Effect.gen(function* () { const firstLatch = Latch.makeUnsafe(); const secondLatch = Latch.makeUnsafe(); const firstAtom = Atom.make(firstLatch.await.pipe(Effect.as("first"))); const secondAtom = Atom.make(secondLatch.await.pipe(Effect.as("second"))); const registry = AtomRegistry.make(); const firstResult = yield* Effect.forkChild(observeAtomQuery(registry, firstAtom), { startImmediately: true, }); const secondResult = yield* Effect.forkChild(observeAtomQuery(registry, secondAtom), { startImmediately: true, }); secondLatch.openUnsafe(); firstLatch.openUnsafe(); const [first, second] = yield* Effect.all([ Fiber.join(firstResult), Fiber.join(secondResult), ]); expect(first._tag).toBe("Success"); expect(second._tag).toBe("Success"); if (first._tag === "Success" && second._tag === "Success") { expect(first.value).toBe("first"); expect(second.value).toBe("second"); } registry.dispose(); }), ); it.effect("settles when its caller aborts a waiting query", () => Effect.gen(function* () { const registry = AtomRegistry.make(); const running = yield* Effect.forkChild(observeAtomQuery(registry, Atom.make(Effect.never)), { startImmediately: true, }); yield* Fiber.interrupt(running); const result = AsyncResult.fromExit(yield* Fiber.await(running)); expect(result._tag).toBe("Failure"); if (result._tag === "Failure") { expect(Cause.hasInterruptsOnly(result.cause)).toBe(true); } registry.dispose(); }), ); }); describe("runtime command runner", () => { it.effect("settles generated command scheduler defects from direct callers", () => Effect.gen(function* () { const defect = new Error("invalid command key"); const runtime = Atom.runtime(Layer.empty); const command = createRuntimeCommand(runtime, { label: "test.invalid-key", concurrency: { mode: "serial", key: () => { throw defect; }, }, execute: () => Effect.void, }); const registry = AtomRegistry.make(); const result = yield* observeAtomCommand(registry, command, undefined); expect(result._tag).toBe("Failure"); if (result._tag === "Failure") { expect(Cause.hasDies(result.cause)).toBe(true); expect(Cause.squash(result.cause)).toBe(defect); } registry.dispose(); }), ); it.effect("stops a caller's own run when its fiber is interrupted", () => Effect.gen(function* () { const started = yield* Deferred.make(); const stopped = yield* Deferred.make(); const command = createRuntimeCommand(Atom.runtime(Layer.empty), { label: "test.abortable", execute: () => Deferred.succeed(started, undefined).pipe( Effect.andThen(Effect.never), Effect.onInterrupt(() => Deferred.succeed(stopped, undefined)), ), }); const registry = AtomRegistry.make(); const caller = yield* Effect.forkChild(command.run(registry, undefined)); yield* Deferred.await(started); yield* Fiber.interrupt(caller); yield* Deferred.await(stopped); registry.dispose(); }), ); it.effect("settles a queued serial command immediately when its signal aborts", () => Effect.gen(function* () { let markFirstStarted!: () => void; const firstStarted = new Promise((resolve) => { markFirstStarted = resolve; }); const releaseFirst = Latch.makeUnsafe(); let secondStarted = false; const command = createRuntimeCommand(Atom.runtime(Layer.empty), { label: "test.serial-abortable", concurrency: { mode: "serial", key: () => "lane" }, execute: (id: number) => id === 1 ? Effect.sync(markFirstStarted).pipe(Effect.andThen(releaseFirst.await)) : Effect.sync(() => { secondStarted = true; }), }); const registry = AtomRegistry.make(); const first = yield* Effect.forkChild(observeAtomCommand(registry, command, 1), { startImmediately: true, }); yield* Effect.promise(() => firstStarted); const second = yield* Effect.forkChild(observeAtomCommand(registry, command, 2), { startImmediately: true, }); yield* Fiber.interrupt(second); const secondResult = AsyncResult.fromExit(yield* Fiber.await(second)); expect(isAtomCommandInterrupted(secondResult)).toBe(true); expect(secondStarted).toBe(false); releaseFirst.openUnsafe(); expect((yield* Fiber.join(first))._tag).toBe("Success"); expect(secondStarted).toBe(false); registry.dispose(); }), ); it.effect("serializes commands that share a scheduler and lane", () => Effect.gen(function* () { const firstLatch = Latch.makeUnsafe(); const events: string[] = []; const runtime = Atom.runtime(Layer.empty); const scheduler = createAtomCommandScheduler(); const concurrency = { mode: "serial" as const, key: () => "shared" }; const firstCommand = createRuntimeCommand(runtime, { label: "test.first", scheduler, concurrency, execute: () => Effect.sync(() => events.push("first:start")).pipe( Effect.andThen(firstLatch.await), Effect.tap(() => Effect.sync(() => events.push("first:end"))), ), }); const secondCommand = createRuntimeCommand(runtime, { label: "test.second", scheduler, concurrency, execute: () => Effect.sync(() => events.push("second:start")), }); const registry = AtomRegistry.make(); const first = yield* Effect.forkChild(observeAtomCommand(registry, firstCommand, undefined), { startImmediately: true, }); const second = yield* Effect.forkChild( observeAtomCommand(registry, secondCommand, undefined), { startImmediately: true }, ); yield* Effect.promise(() => Promise.resolve()); expect(events).toEqual(["first:start"]); firstLatch.openUnsafe(); yield* Effect.all([Fiber.join(first), Fiber.join(second)]); expect(events).toEqual(["first:start", "first:end", "second:start"]); registry.dispose(); }), ); it.effect("releases a shared scheduler lane before the outer command finishes", () => Effect.gen(function* () { const handoffStarted = Latch.makeUnsafe(); const handoffComplete = Latch.makeUnsafe(); const resumeComplete = Latch.makeUnsafe(); const runtime = Atom.runtime(Layer.empty); const scheduler = createAtomCommandScheduler(); const concurrency = { mode: "serial" as const, key: () => "shared" }; const updateCommand = createRuntimeCommand(runtime, { label: "test.update", execute: (_input: void, registry) => scheduler .schedule( registry, concurrency, undefined, Effect.sync(() => handoffStarted.openUnsafe()).pipe( Effect.andThen(handoffComplete.await), ), ) .pipe(Effect.andThen(resumeComplete.await)), }); const configCommand = createRuntimeCommand(runtime, { label: "test.config", scheduler, concurrency, execute: () => Effect.succeed("configured"), }); const registry = AtomRegistry.make(); const update = yield* Effect.forkChild( observeAtomCommand(registry, updateCommand, undefined), { startImmediately: true }, ); yield* handoffStarted.await; const config = yield* Effect.forkChild( observeAtomCommand(registry, configCommand, undefined), { startImmediately: true }, ); handoffComplete.openUnsafe(); expect(yield* Fiber.join(config)).toMatchObject({ _tag: "Success", value: "configured", waiting: false, }); resumeComplete.openUnsafe(); expect(yield* Fiber.join(update)).toMatchObject({ _tag: "Success", waiting: false, }); registry.dispose(); }), ); it.effect("keeps an outer reconnect observer alive after a scheduled handoff returns", () => Effect.gen(function* () { const commitStarting = yield* Deferred.make(); const observerArmed = yield* Deferred.make(); const reconnected = yield* Deferred.make(); const states = yield* Queue.unbounded<{ readonly phase: string }>(); yield* Queue.offer(states, { phase: "connected" }); const runtime = Atom.runtime(Layer.empty); const scheduler = createAtomCommandScheduler(); const concurrency = { mode: "serial" as const, key: () => "shared" }; const command = createRuntimeCommand(runtime, { label: "test.desktop-update-handoff", execute: (_input: void, registry) => Effect.gen(function* () { yield* Deferred.await(commitStarting).pipe( Effect.andThen( Stream.fromQueue(states).pipe( Stream.tap(() => Deferred.succeed(observerArmed, undefined)), Stream.dropWhile((state) => state.phase === "connected"), Stream.filter((state) => state.phase === "connected"), Stream.runHead, ), ), Effect.andThen(Deferred.succeed(reconnected, undefined)), Effect.forkChild, ); yield* scheduler.schedule( registry, concurrency, undefined, Deferred.succeed(commitStarting, undefined).pipe( Effect.andThen(Deferred.await(observerArmed)), ), ); yield* Queue.offer(states, { phase: "backoff" }); yield* Queue.offer(states, { phase: "connected" }); yield* Deferred.await(reconnected); }), }); const registry = AtomRegistry.make(); expect(yield* observeAtomCommand(registry, command, undefined)).toMatchObject({ _tag: "Success", }); registry.dispose(); }), ); it.effect("shares single-flight work when the first caller stops waiting", () => Effect.gen(function* () { const started = yield* Deferred.make(); const finish = yield* Deferred.make(); let executions = 0; const runtime = Atom.runtime(Layer.empty); const command = createRuntimeCommand(runtime, { label: "test.single-flight", concurrency: { mode: "singleFlight", key: (key: string) => key }, execute: () => Effect.sync(() => executions++).pipe( Effect.andThen(Deferred.succeed(started, undefined)), Effect.andThen(Deferred.await(finish)), Effect.as("done"), ), }); const registry = AtomRegistry.make(); const first = yield* Effect.forkChild(command.run(registry, "same")); yield* Deferred.await(started); const second = yield* Effect.forkChild(command.run(registry, "same"), { startImmediately: true, }); yield* Fiber.interrupt(first); yield* Deferred.succeed(finish, undefined); expect(yield* Fiber.join(second)).toBe("done"); expect(executions).toBe(1); registry.dispose(); }), ); it.effect("coalesces pending latest-value commands without interrupting the active call", () => Effect.gen(function* () { const firstLatch = Latch.makeUnsafe(); const executed: number[] = []; const runtime = Atom.runtime(Layer.empty); const command = createRuntimeCommand(runtime, { label: "test.latest", concurrency: { mode: "latest", key: () => "shared" }, execute: (value: number) => Effect.sync(() => executed.push(value)).pipe( Effect.andThen(value === 1 ? firstLatch.await : Effect.void), Effect.as(value), ), }); const registry = AtomRegistry.make(); const first = yield* Effect.forkChild(observeAtomCommand(registry, command, 1), { startImmediately: true, }); yield* Effect.promise(() => Promise.resolve()); const second = yield* Effect.forkChild(observeAtomCommand(registry, command, 2), { startImmediately: true, }); const third = yield* Effect.forkChild(observeAtomCommand(registry, command, 3), { startImmediately: true, }); firstLatch.openUnsafe(); expect(yield* Fiber.join(first)).toMatchObject({ _tag: "Success", value: 1, waiting: false }); expect(yield* Fiber.join(second)).toMatchObject({ _tag: "Success", value: 3, waiting: false, }); expect(yield* Fiber.join(third)).toMatchObject({ _tag: "Success", value: 3, waiting: false }); expect(executed).toEqual([1, 3]); registry.dispose(); }), ); }); describe("persisted environment queries", () => { it.effect("keeps an in-memory cached page pending until revalidation settles", () => Effect.gen(function* () { const refreshStarted = Latch.makeUnsafe(); const finishRefresh = Latch.makeUnsafe(); let executions = 0; const harness = yield* makeEnvironmentQueryHarness( Effect.suspend(() => { if (++executions === 1) return Effect.succeed("cached"); refreshStarted.openUnsafe(); return finishRefresh.await.pipe(Effect.as("fresh")); }), { persistence: { load: () => Effect.succeedNone, save: () => Effect.void } }, ); const registry = yield* mountEnvironmentQuery(harness.atom); expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached"); registry.refresh(harness.atom); yield* refreshStarted.await; expect(registry.get(harness.atom)).toMatchObject({ _tag: "Success", value: "cached", waiting: true, }); finishRefresh.openUnsafe(); expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh"); }), ); it.effect( "restores cached data in a new registry while offline, then refreshes on reconnect", () => Effect.gen(function* () { let saved = Option.none(); const saves = yield* Queue.unbounded(); const persistence: QueryPersistence = { load: () => Effect.sync(() => saved), save: (_environmentId, _key, value) => Effect.sync(() => { saved = Option.some(value); }).pipe(Effect.andThen(Queue.offer(saves, value))), }; const first = yield* makeEnvironmentQueryHarness(Effect.succeed("first"), { persistence, }); const firstRegistry = yield* mountEnvironmentQuery(first.atom); expect(yield* readEnvironmentQuery(firstRegistry, first.atom)).toBe("first"); expect(yield* Queue.take(saves)).toBe("first"); const restarted = yield* makeEnvironmentQueryHarness(Effect.succeed("updated"), { persistence, initialState: queryConnectionState({ phase: "offline", network: "offline" }), }); const registry = yield* mountEnvironmentQuery(restarted.atom); expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("first"); yield* SubscriptionRef.set(restarted.supervisorState, queryConnectionState()); yield* Effect.yieldNow; expect(yield* readEnvironmentQuery(registry, restarted.atom)).toBe("updated"); expect(yield* Queue.take(saves)).toBe("updated"); }), ); it.effect("answers readers while its save is pending, and ends the save with the query", () => Effect.gen(function* () { const saveEnded = Latch.makeUnsafe(); const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("fresh"), { persistence: { load: () => Effect.succeedNone, // The registry's scheduler stops on dispose, so signal synchronously. save: () => Effect.never.pipe(Effect.onInterrupt(() => Effect.sync(() => saveEnded.openUnsafe()))), }, }); yield* Effect.scoped( Effect.gen(function* () { const registry = yield* mountEnvironmentQuery(harness.atom); expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("fresh"); }), ); yield* saveEnded.await; }), ); it.effect("hands each server answer to onAnswer before readers see it", () => Effect.gen(function* () { const answers: Array = []; let served = 0; const recorded = Atom.make(null).pipe(Atom.keepAlive); const harness = yield* makeEnvironmentQueryHarness( Effect.sync(() => `answer-${++served}`), { onAnswer: (_target, value, registry) => Effect.sync(() => { answers.push([value, registry.get(recorded)]); registry.set(recorded, value); }), }, ); const registry = yield* mountEnvironmentQuery(harness.atom); expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-1"); expect(registry.get(recorded)).toBe("answer-1"); registry.refresh(harness.atom); expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("answer-2"); expect(answers).toEqual([ ["answer-1", null], ["answer-2", "answer-1"], ]); }), ); it.effect("does not hand a value restored from persistence to onAnswer", () => Effect.gen(function* () { const answers: Array = []; const harness = yield* makeEnvironmentQueryHarness(Effect.succeed("server"), { persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void }, initialState: queryConnectionState({ phase: "offline", network: "offline" }), onAnswer: (_target, value) => Effect.sync(() => answers.push(value)), }); const registry = yield* mountEnvironmentQuery(harness.atom); expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("cached"); expect(answers).toEqual([]); yield* SubscriptionRef.set(harness.supervisorState, queryConnectionState()); yield* Effect.yieldNow; expect(yield* readEnvironmentQuery(registry, harness.atom)).toBe("server"); expect(answers).toEqual(["server"]); }), ); it.effect("keeps cached content available when revalidation fails", () => Effect.gen(function* () { const harness = yield* makeEnvironmentQueryHarness( Effect.fail(new TestQueryError({ message: "failed" })), { persistence: { load: () => Effect.succeedSome("cached"), save: () => Effect.void }, }, ); const registry = yield* mountEnvironmentQuery(harness.atom); yield* Effect.result(readEnvironmentQuery(registry, harness.atom)); expect(AsyncResult.getOrElse(registry.get(harness.atom), () => null)).toBe("cached"); }), ); });