TypeScript
fix(client-runtime): report terminated thread loads (#10216)
Julius Marmingebd16b86d50c1
diff --git a/packages/client-runtime/src/rpc/client.test.ts b/packages/client-runtime/src/rpc/client.test.tsindex f2141add930..9e4e8a600d5 100644--- a/packages/client-runtime/src/rpc/client.test.ts+++ b/packages/client-runtime/src/rpc/client.test.ts@@ -465,36 +465,112 @@ describe("environment RPC", () => {}),);- it.effect("does not classify subscription defects as expected failures", () =>+ it.effect.each(["input", "stream"] as const)(+ "does not classify %s subscription defects as expected failures",+ (where) =>+ Effect.gen(function* () {+ const defect = new Error("subscription invariant failed");+ let expectedFailureCount = 0;+ let inputs = 0;+ let streams = 0;+ const observedDefects: unknown[] = [];+ const client = {+ [WS_METHODS.subscribeTerminalEvents]: () => {+ streams += 1;+ return where === "stream" ? Stream.die(defect) : Stream.never;+ },+ } as unknown as WsRpcProtocolClient;+ const { activeSession, supervisor } = yield* makeHarness();++ yield* SubscriptionRef.set(activeSession, Option.some(session(client)));+ const exit = yield* subscribeDynamicWithSession(+ WS_METHODS.subscribeTerminalEvents,+ () =>+ Effect.sync(() => {+ inputs += 1;+ }).pipe(Effect.andThen(where === "input" ? Effect.die(defect) : Effect.succeed({}))),+ {+ onDefect: (cause) =>+ Effect.sync(() => {+ observedDefects.push(Cause.squash(cause));+ }),+ onExpectedFailure: () =>+ Effect.sync(() => {+ expectedFailureCount += 1;+ }),+ retryExpectedFailureAfter: "250 millis",+ },+ ).pipe(+ Stream.runDrain,+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),+ Effect.exit,+ );++ expect(Exit.isFailure(exit)).toBe(true);+ if (Exit.isFailure(exit)) {+ expect(Cause.hasDies(exit.cause)).toBe(true);+ expect(Cause.squash(exit.cause)).toBe(defect);+ }+ expect(inputs).toBe(1);+ expect(streams).toBe(where === "input" ? 0 : 1);+ expect(expectedFailureCount).toBe(0);+ expect(observedDefects).toEqual([defect]);+ }),+ );++ it.effect("reports an initializer defect once after an expected failure retries", () =>Effect.gen(function* () {- const defect = new Error("subscription invariant failed");- let expectedFailureCount = 0;+ const defect = new Error("Synthetic retry initializer defect");+ const expectedFailure = yield* Deferred.make<void>();+ const observations: string[] = [];+ const observedDefects: unknown[] = [];+ let inputs = 0;const client = {- [WS_METHODS.subscribeTerminalEvents]: () => Stream.die(defect),+ [WS_METHODS.subscribeTerminalEvents]: () => {+ observations.push("stream");+ return Stream.fail(new Error("subscription not ready"));+ },} as unknown as WsRpcProtocolClient;const { activeSession, supervisor } = yield* makeHarness();-yield* SubscriptionRef.set(activeSession, Option.some(session(client)));- const exit = yield* subscribe(+ const fiber = yield* subscribeDynamicWithSession(WS_METHODS.subscribeTerminalEvents,- {},+ () =>+ Effect.sync(() => {+ inputs += 1;+ observations.push(`input ${inputs}`);+ return inputs;+ }).pipe(+ Effect.flatMap((attempt) => (attempt === 1 ? Effect.succeed({}) : Effect.die(defect))),+ ),{- onExpectedFailure: () =>+ onDefect: (cause) =>Effect.sync(() => {- expectedFailureCount += 1;+ observations.push("defect");+ observedDefects.push(Cause.squash(cause));}),+ onExpectedFailure: () =>+ Effect.sync(() => {+ observations.push("expected failure");+ }).pipe(Effect.andThen(Deferred.succeed(expectedFailure, undefined)), Effect.asVoid),+ retryExpectedFailureAfter: "250 millis",},).pipe(Stream.runDrain,Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),Effect.exit,+ Effect.forkChild,);-+ yield* Deferred.await(expectedFailure);+ yield* TestClock.adjust("250 millis");+ const exit = yield* Fiber.join(fiber);expect(Exit.isFailure(exit)).toBe(true);if (Exit.isFailure(exit)) {expect(Cause.hasDies(exit.cause)).toBe(true);+ expect(Cause.squash(exit.cause)).toBe(defect);}- expect(expectedFailureCount).toBe(0);+ expect(observations).toEqual(["input 1", "stream", "expected failure", "input 2", "defect"]);+ expect(observedDefects).toEqual([defect]);}),);});diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.tsindex e7c5117954c..bc13d429ac9 100644--- a/packages/client-runtime/src/rpc/client.ts+++ b/packages/client-runtime/src/rpc/client.ts@@ -171,6 +171,10 @@ export function runStream<TTag extends EnvironmentStreamCommandRpcTag>(}interface SubscriptionOptions<TTag extends EnvironmentSubscriptionRpcTag> {+ /** Reports protocol or programming defects without changing their recovery policy. */+ readonly onDefect?: (+ cause: Cause.Cause<EnvironmentRpcStreamFailure<TTag>>,+ ) => Effect.Effect<void, never, never>;readonly onExpectedFailure?: (cause: Cause.Cause<EnvironmentRpcStreamFailure<TTag>>,) => Effect.Effect<void, never, never>;@@ -228,47 +232,60 @@ function subscribeDynamicMapped<TTag extends EnvironmentSubscriptionRpcTag, A>(});return mapStream(session, method(input)).pipe(Stream.ensuring(completeObservation),- Stream.catchCause((cause) => {- const hasOnlyExpectedFailures =- cause.reasons.length > 0 &&- cause.reasons.every((reason) => reason._tag === "Fail");- const isTransportFailure =- hasOnlyExpectedFailures &&- cause.reasons.every(- (reason) => reason._tag === "Fail" && isRpcClientError(reason.error),- );- if (isTransportFailure) {- return Stream.fromEffect(- Effect.logWarning(- "Durable RPC subscription lost its transport; waiting for the next session.",- {- cause: Cause.pretty(cause),- method: tag,- environmentId: supervisor.target.environmentId,- },- ),- ).pipe(Stream.drain);- }- if (hasOnlyExpectedFailures && options?.onExpectedFailure !== undefined) {- const handled = Stream.fromEffect(- options.onExpectedFailure(cause),- ).pipe(Stream.drain);- if (options.retryExpectedFailureAfter === undefined) {- return handled;- }- return handled.pipe(- Stream.concat(- Stream.fromEffect(- Effect.sleep(options.retryExpectedFailureAfter),- ).pipe(Stream.drain),- ),- Stream.concat(subscribeToSession()),- );- }- return Stream.failCause(cause);- }),);}),+ ).pipe(+ Stream.tapCause((cause) =>+ options?.onDefect !== undefined &&+ cause.reasons.some(+ (reason) =>+ reason._tag === "Die" ||+ (reason._tag === "Fail" &&+ isRpcClientError(reason.error) &&+ reason.error.reason._tag === "RpcClientDefect"),+ )+ ? options.onDefect(cause)+ : Effect.void,+ ),+ Stream.catchCause((cause) => {+ const hasOnlyExpectedFailures =+ cause.reasons.length > 0 &&+ cause.reasons.every((reason) => reason._tag === "Fail");+ const isTransportFailure =+ hasOnlyExpectedFailures &&+ cause.reasons.every(+ (reason) => reason._tag === "Fail" && isRpcClientError(reason.error),+ );+ if (isTransportFailure) {+ return Stream.fromEffect(+ Effect.logWarning(+ "Durable RPC subscription lost its transport; waiting for the next session.",+ {+ cause: Cause.pretty(cause),+ method: tag,+ environmentId: supervisor.target.environmentId,+ },+ ),+ ).pipe(Stream.drain);+ }+ if (hasOnlyExpectedFailures && options?.onExpectedFailure !== undefined) {+ const handled = Stream.fromEffect(options.onExpectedFailure(cause)).pipe(+ Stream.drain,+ );+ if (options.retryExpectedFailureAfter === undefined) {+ return handled;+ }+ return handled.pipe(+ Stream.concat(+ Stream.fromEffect(Effect.sleep(options.retryExpectedFailureAfter)).pipe(+ Stream.drain,+ ),+ ),+ Stream.concat(subscribeToSession()),+ );+ }+ return Stream.failCause(cause);+ }),),);return subscribeToSession();diff --git a/packages/client-runtime/src/state/threads-atoms.test.ts b/packages/client-runtime/src/state/threads-atoms.test.tsindex 27229a7aff6..54b6f9e73e9 100644--- a/packages/client-runtime/src/state/threads-atoms.test.ts+++ b/packages/client-runtime/src/state/threads-atoms.test.ts@@ -11,6 +11,8 @@ import {type OrchestrationThreadStreamItem,} from "@t3tools/contracts";import { afterEach, describe, expect, it, vi } from "@effect/vitest";+import * as Cause from "effect/Cause";+import * as Clock from "effect/Clock";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";import * as Layer from "effect/Layer";@@ -18,7 +20,10 @@ import * as Option from "effect/Option";import * as Queue from "effect/Queue";import * as Stream from "effect/Stream";import * as SubscriptionRef from "effect/SubscriptionRef";+import * as TestClock from "effect/testing/TestClock";import { Atom, AtomRegistry } from "effect/unstable/reactivity";+import { RpcClientError } from "effect/unstable/rpc";+import { Socket } from "effect/unstable/socket";import type { ConnectionCatalogEntry } from "../connection/catalog.ts";import { EnvironmentRegistry } from "../connection/registry.ts";@@ -30,6 +35,7 @@ import {type SupervisorConnectionState,} from "../connection/model.ts";import { EnvironmentSupervisor } from "../connection/supervisor.ts";+import { ConnectionWakeups, type ConnectionWakeup } from "../connection/wakeups.ts";import { EnvironmentCacheStore } from "../platform/persistence.ts";import type { WsRpcProtocolClient } from "../rpc/protocol.ts";import type { RpcSession } from "../rpc/session.ts";@@ -38,6 +44,7 @@ import { THREAD_SNAPSHOT_IDLE_TTL_MS } from "./threadRetention.ts";import type { ThreadSnapshotWindow } from "./threadSnapshotHttp.ts";import {createEnvironmentThreadStateAtoms,+ makeEnvironmentThreadState,requestOlderThreadTurns,ThreadSnapshotLoader,type EnvironmentThreadState,@@ -54,7 +61,7 @@ const THREAD: OrchestrationThread = {id: THREAD_ID,projectId: ProjectId.make("project-1"),title: "Cached thread",- modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "ModelA" },runtimeMode: "full-access",interactionMode: "default",branch: "main",@@ -86,10 +93,15 @@ const CONNECTED_STATE: SupervisorConnectionState = {const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?: {readonly snapshot?: OrchestrationThreadDetailSnapshot;readonly connected?: boolean;+ readonly httpNone?: boolean;+ readonly initialLoad?: Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;+ readonly stream?: Stream.Stream<OrchestrationThreadStreamItem, Error>;}) {+ const clock = yield* Clock.Clock;+ const wakeups = yield* Queue.unbounded<ConnectionWakeup>();const subscriptions = yield* Queue.unbounded<{readonly afterSequence: number | undefined;- readonly events: Queue.Queue<OrchestrationThreadStreamItem>;+ readonly events: Queue.Queue<OrchestrationThreadStreamItem, Error>;readonly closed: Deferred.Deferred<void>;}>();const olderLoads = yield* Queue.unbounded<{@@ -106,7 +118,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?[ORCHESTRATION_WS_METHODS.subscribeThread]: (input: { readonly afterSequence?: number }) =>Stream.unwrap(Effect.gen(function* () {- const events = yield* Queue.unbounded<OrchestrationThreadStreamItem>();+ const events = yield* Queue.unbounded<OrchestrationThreadStreamItem, Error>();const closed = yield* Deferred.make<void>();yield* Effect.acquireRelease(Effect.sync(() => {@@ -119,7 +131,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?}).pipe(Effect.andThen(Deferred.succeed(closed, undefined))),);yield* Queue.offer(subscriptions, { afterSequence: input.afterSequence, events, closed });- return Stream.fromQueue(events);+ return options?.stream ?? Stream.fromQueue(events);}),),} as unknown as WsRpcProtocolClient;@@ -179,6 +191,8 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?});const runtime = Atom.runtime(Layer.mergeAll(+ Layer.succeed(Clock.Clock, clock),+ Layer.succeed(ConnectionWakeups, { changes: Stream.fromQueue(wakeups) }),Layer.succeed(EnvironmentRegistry, environmentRegistry),Layer.succeed(EnvironmentCacheStore,@@ -208,8 +222,12 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?if (window?.beforeCursor === undefined) {return Effect.sync(() => {httpLoads += 1;- return Option.some(snapshot);- });+ }).pipe(+ Effect.andThen(+ options?.initialLoad ??+ Effect.succeed(options?.httpNone ? Option.none() : Option.some(snapshot)),+ ),+ );}return Effect.gen(function* () {const response =@@ -235,6 +253,8 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?const registry = yield* makeRegistry;return {+ runtime,+ supervisor,registry,makeRegistry,rawAtoms: raw,@@ -246,6 +266,7 @@ const makeHarness = Effect.fn("TestThreadAtoms.makeHarness")(function* (options?connectionState,session,sessionRef,+ wakeups,counts: () => ({ httpLoads, diskLoads, opened, active }),};});@@ -275,6 +296,311 @@ describe("createEnvironmentThreadStateAtoms", () => {vi.restoreAllMocks();});+ it.effect("exposes snapshot loader defects before the RPC subscription starts", () =>+ Effect.gen(function* () {+ const completed = yield* Deferred.make<void>();+ const h = yield* makeHarness({+ connected: true,+ initialLoad: Effect.die(+ new Error("SYNTHETIC_RAW_SNAPSHOT_DEFECT_SHOULD_NOT_REACH_THREAD_UI"),+ ).pipe(Effect.ensuring(Deferred.succeed(completed, undefined))),+ });+ const unmount = h.registry.mount(h.stateAtom);+ yield* Deferred.await(completed);+ const failed = yield* observeState(h.registry, h.stateAtom, (state) =>+ Option.isSome(state.error),+ );+ expect(failed.status).toBe("empty");+ expect(failed.error).toEqual(Option.some("Could not synchronize the thread."));+ expect(failed.data).toEqual(Option.none());+ expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 0, active: 0 });+ yield* TestClock.adjust("1 second");+ expect(h.registry.get(h.stateAtom)).toEqual(failed);+ expect(h.counts()).toEqual({ httpLoads: 1, diskLoads: 1, opened: 0, active: 0 });+ unmount();+ }),+ );++ it.effect.each([+ { kind: "protocol", httpNone: true },+ { kind: "protocol", httpNone: false },+ { kind: "fatal", httpNone: true },+ { kind: "fatal", httpNone: false },+ ] as const)(+ "retains a terminated $kind load diagnostic across connection updates (empty: $httpNone)",+ ({ kind, httpNone }) =>+ Effect.gen(function* () {+ const h = yield* makeHarness({ connected: true, httpNone });+ const unmount = h.registry.mount(h.stateAtom);+ const first = yield* Queue.take(h.subscriptions);+ const error = new Error("SYNTHETIC_RAW_DEFECT_SHOULD_NOT_REACH_THREAD_UI");+ yield* Queue.failCause(+ first.events,+ kind === "fatal"+ ? Cause.die(error)+ : Cause.fail(+ new RpcClientError.RpcClientError({+ reason: new RpcClientError.RpcClientDefect({+ message: error.message,+ cause: error,+ }),+ }),+ ),+ );+ yield* Deferred.await(first.closed);+ // The real finalizer has run; advancing the atom runtime's test clock+ // also verifies that a defect does not enter the domain retry loop.+ yield* TestClock.adjust("1 second");+ const failed = h.registry.get(h.stateAtom);+ expect(failed.status).toBe(httpNone ? "empty" : "cached");+ expect(failed.error).toEqual(Option.some("Could not synchronize the thread."));+ expect(failed.data).toEqual(httpNone ? Option.none() : Option.some(THREAD));+ expect(h.counts().opened).toBe(1);+ expect(h.counts().active).toBe(0);++ // Session publication can precede connected, and a fatal child cannot+ // restart just because its supervisor reconnects.+ for (const connection of [+ AVAILABLE_CONNECTION_STATE,+ { ...CONNECTED_STATE, phase: "connecting" as const },+ CONNECTED_STATE,+ ]) {+ yield* SubscriptionRef.set(h.connectionState, connection);+ yield* TestClock.adjust("0 millis");+ expect(h.registry.get(h.stateAtom)).toEqual(failed);+ }+ yield* SubscriptionRef.set(h.sessionRef, Option.some({ ...h.session }));+ if (kind === "fatal") {+ yield* TestClock.adjust("1 second");+ expect(h.counts().opened).toBe(1);+ expect(h.registry.get(h.stateAtom)).toEqual(failed);+ unmount();+ return;+ }+ const next = yield* Queue.take(h.subscriptions);+ expect(h.registry.get(h.stateAtom).error).toEqual(Option.none());+ expect(h.registry.get(h.stateAtom).status).toBe("synchronizing");+ yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });+ yield* Queue.offer(next.events, { kind: "synchronized" });+ const recovered = yield* observeState(+ h.registry,+ h.stateAtom,+ (state) => state.status === "live",+ );+ expect(recovered.error).toEqual(Option.none());+ expect(recovered.data).toEqual(Option.some(THREAD));+ unmount();+ yield* Deferred.await(next.closed);+ }),+ );++ it.effect("retries a protocol failure on foreground without replacing the session", () =>+ Effect.gen(function* () {+ const h = yield* makeHarness({ connected: true, httpNone: true });+ const unmount = h.registry.mount(h.stateAtom);+ const first = yield* Queue.take(h.subscriptions);+ yield* Queue.fail(+ first.events,+ new RpcClientError.RpcClientError({+ reason: new RpcClientError.RpcClientDefect({+ message: "incompatible snapshot",+ cause: new Error("incompatible snapshot"),+ }),+ }),+ );+ yield* Deferred.await(first.closed);+ yield* TestClock.adjust("0 millis");+ expect(Option.isSome(h.registry.get(h.stateAtom).error)).toBe(true);+ yield* Queue.offer(h.wakeups, "application-active");+ const next = yield* Queue.take(h.subscriptions);+ expect(h.registry.get(h.stateAtom).error).toEqual(Option.none());+ yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });+ yield* Queue.offer(next.events, { kind: "synchronized" });+ yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");+ unmount();+ yield* Deferred.await(next.closed);+ }),+ );++ it.effect("keeps transport loss nonterminal and recovers with a replacement session", () =>+ Effect.gen(function* () {+ const h = yield* makeHarness({ connected: true, httpNone: true });+ const unmount = h.registry.mount(h.stateAtom);+ const first = yield* Queue.take(h.subscriptions);+ yield* Queue.fail(+ first.events,+ new RpcClientError.RpcClientError({+ reason: new Socket.SocketCloseError({ code: 1006, closeReason: "connection lost" }),+ }),+ );+ yield* Deferred.await(first.closed);+ yield* TestClock.adjust("1 second");+ expect(h.registry.get(h.stateAtom)).toMatchObject({+ status: "synchronizing",+ error: Option.none(),+ data: Option.none(),+ });+ expect(h.counts().opened).toBe(1);+ yield* SubscriptionRef.set(h.sessionRef, Option.some({ ...h.session }));+ const next = yield* Queue.take(h.subscriptions);+ yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });+ yield* Queue.offer(next.events, { kind: "synchronized" });+ yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live");+ unmount();+ yield* Deferred.await(next.closed);+ }),+ );++ it.effect("retains ordinary domain error reporting and same-session retries", () =>+ Effect.gen(function* () {+ const h = yield* makeHarness({ connected: true, httpNone: true });+ const unmount = h.registry.mount(h.stateAtom);+ const first = yield* Queue.take(h.subscriptions);+ yield* Queue.fail(first.events, new Error("thread not found yet"));+ yield* Deferred.await(first.closed);+ const failed = yield* observeState(h.registry, h.stateAtom, (state) =>+ Option.isSome(state.error),+ );+ expect(failed.error).toEqual(Option.some("thread not found yet"));+ yield* TestClock.adjust("250 millis");+ const next = yield* Queue.take(h.subscriptions);+ expect(h.counts().opened).toBe(2);+ yield* Queue.offer(next.events, { kind: "snapshot", snapshot: SNAPSHOT });+ yield* Queue.offer(next.events, { kind: "synchronized" });+ const recovered = yield* observeState(+ h.registry,+ h.stateAtom,+ (state) => state.status === "live",+ );+ expect(recovered.error).toEqual(Option.none());+ unmount();+ yield* Deferred.await(next.closed);+ }),+ );++ it.effect.each([+ { kind: "protocol", deleted: false },+ { kind: "fatal", deleted: false },+ { kind: "domain", deleted: false },+ { kind: "protocol", deleted: true },+ ] as const)(+ "keeps buffered outcomes after a $kind failure (deleted: $deleted)",+ ({ kind, deleted }) =>+ Effect.gen(function* () {+ const burst = yield* Deferred.make<void>();+ const error = new Error(+ kind === "domain"+ ? "buffered thread failure"+ : "SYNTHETIC_BUFFERED_DEFECT_SHOULD_NOT_REACH_THREAD_UI",+ );+ const items: OrchestrationThreadStreamItem[] = [+ { kind: "snapshot", snapshot: SNAPSHOT },+ { kind: "synchronized" },+ {+ kind: "event",+ event: {+ eventId: EventId.make("buffered-event"),+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ sequence: 8,+ occurredAt: THREAD.createdAt,+ aggregateKind: "thread",+ aggregateId: THREAD_ID,+ type: "thread.meta-updated",+ payload: {+ threadId: THREAD_ID,+ title: "Buffer drained",+ updatedAt: THREAD.createdAt,+ },+ },+ },+ ];+ if (deleted) {+ items.push({+ kind: "event",+ event: {+ eventId: EventId.make("buffered-deletion"),+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ sequence: 9,+ occurredAt: THREAD.createdAt,+ aggregateKind: "thread",+ aggregateId: THREAD_ID,+ type: "thread.deleted",+ payload: { threadId: THREAD_ID, deletedAt: THREAD.createdAt },+ },+ });+ }+ const failure =+ kind === "fatal"+ ? Cause.die(error)+ : Cause.fail(+ kind === "domain"+ ? error+ : new RpcClientError.RpcClientError({+ reason: new RpcClientError.RpcClientDefect({+ message: error.message,+ cause: error,+ }),+ }),+ );+ const h = yield* makeHarness({+ connected: true,+ httpNone: true,+ stream: Stream.fromEffect(Deferred.await(burst)).pipe(+ Stream.flatMap(() => Stream.fromIterable(items)),+ Stream.concat(Stream.failCause(failure)),+ ),+ });+ yield* Effect.gen(function* () {+ const state = yield* makeEnvironmentThreadState(THREAD_ID);+ const initial = yield* Deferred.make<void>();+ const drained = yield* Deferred.make<void>();+ yield* SubscriptionRef.changes(state).pipe(+ Stream.runForEach((value) =>+ Deferred.succeed(initial, undefined).pipe(+ Effect.andThen(+ (+ deleted+ ? value.status === "deleted"+ : Option.getOrNull(value.data)?.title === "Buffer drained"+ )+ ? Deferred.succeed(drained, undefined)+ : Effect.void,+ ),+ ),+ ),+ Effect.forkScoped,+ );+ yield* Deferred.await(initial);+ const subscription = yield* Queue.take(h.subscriptions);+ yield* Deferred.succeed(burst, undefined);+ yield* Deferred.await(subscription.closed);+ yield* Deferred.await(drained);+ const final = yield* SubscriptionRef.get(state);+ if (deleted) {+ expect(final.status).toBe("deleted");+ expect(final.data).toEqual(Option.none());+ expect(final.error).toEqual(Option.none());+ return;+ }+ expect(Option.getOrThrow(final.data).title).toBe("Buffer drained");+ expect(final.error).toEqual(+ Option.some(kind === "domain" ? error.message : "Could not synchronize the thread."),+ );+ expect(final.status).toBe("cached");+ }).pipe(+ Effect.provideService(EnvironmentSupervisor, h.supervisor),+ Effect.provide(h.registry.get(h.runtime.layer)),+ Effect.scoped,+ );+ }),+ );+it.effect("shares one live stream and closes it after the last detail consumer leaves", () =>Effect.gen(function* () {const h = yield* makeHarness();diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.tsindex 1311469c0ee..83b85bf02f0 100644--- a/packages/client-runtime/src/state/threads.ts+++ b/packages/client-runtime/src/state/threads.ts@@ -310,8 +310,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makeEffect.forkScoped,);- const setSynchronizing = SubscriptionRef.update(state, (current) =>- current.status === "deleted"+ const setConnecting = SubscriptionRef.update(state, (current) =>+ current.status === "deleted" || Option.isSome(current.error)? current: {...current,@@ -320,7 +320,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make},);const setReady = SubscriptionRef.update(state, (current) =>- current.status === "live" || current.status === "deleted"+ current.status === "live" || current.status === "deleted" || Option.isSome(current.error)? current: {...current,@@ -341,14 +341,14 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makestatus: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),}));});- const setStreamError = (cause: Cause.Cause<unknown>) =>+ const setStreamError = (message: string) =>Ref.set(awaitingCompletion, false).pipe(Effect.andThen(SubscriptionRef.update(state, (current) => ({...current,status:current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),- error: Option.some(formatThreadError(cause)),+ error: Option.some(message),})),),);@@ -362,8 +362,13 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makeconst waiting = yield* Ref.get(awaitingCompletion);yield* SubscriptionRef.update(state, (current) => ({data: Option.some(thread),- status: waiting ? ("synchronizing" as const) : ("live" as const),- error: Option.none(),+ // Buffered values from the failed attempt can still arrive after its error.+ status: Option.isSome(current.error)+ ? ("cached" as const)+ : waiting+ ? ("synchronizing" as const)+ : ("live" as const),+ error: current.error,page: page === "keep" ? current.page : page,}));// Active threads can update many times per second and retain large tool@@ -423,7 +428,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makeif (item.kind === "synchronized") {yield* Ref.set(awaitingCompletion, false);yield* SubscriptionRef.update(state, (current) =>- Option.isSome(current.data) && current.status !== "deleted"+ Option.isSome(current.data) && current.status !== "deleted" && Option.isNone(current.error)? { ...current, status: "live" as const, error: Option.none() }: current,);@@ -639,7 +644,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makeStream.runForEach((connectionState) => {switch (connectionProjectionPhase(connectionState)) {case "synchronizing":- return setSynchronizing;+ return setConnecting;case "disconnected":return setDisconnected;case "ready":@@ -661,7 +666,13 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.makeconst resumingLive = yield* Ref.make(initialState.status === "live");const markSynchronizing = Effect.gen(function* () {if (yield* Ref.get(resumingLive)) return;- yield* setSynchronizing;+ // Connection notifications do not establish that a terminated load restarted.+ // Clear its diagnostic only when this subscription actually tries again.+ yield* SubscriptionRef.update(state, (current) =>+ current.status === "deleted"+ ? current+ : { ...current, status: "synchronizing" as const, error: Option.none() },+ );});yield* markSynchronizing;@@ -757,7 +768,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make};}),{- onExpectedFailure: setStreamError,+ onDefect: () => setStreamError("Could not synchronize the thread."),+ onExpectedFailure: (cause) => setStreamError(formatThreadError(cause)),retryExpectedFailureAfter: "250 millis",resubscribe: foregroundResubscriptions,},