@devries-cameron20 / t3code Mirror · read-only / commits / ddcde11be8
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 04:15 UTC

fix(client-runtime): queries stay pending while a connection hands off (#18155)

Tristan Knight committed Oct 18, 2026 at 20:29 UTC ddcde11be8260c01874d3dc0b5ab36ff76d244f4
4 files changed +147 -5
packages/client-runtime/src/connection/registry.test.ts
+22
@@ -630,6 +630,28 @@ describe("EnvironmentRegistry", () => {
630 }),
631 );
632
633 + it.effect("does not expose a persisted environment as disconnected while it starts", () =>
634 + Effect.gen(function* () {
635 + const connectionStarted = yield* Deferred.make<void>();
636 + const finishConnection = yield* Deferred.make<void>();
637 + const harness = yield* makeHarness([TARGET], [], [], {
638 + beforeSessionConnect: () =>
639 + Deferred.succeed(connectionStarted, undefined).pipe(
640 + Effect.andThen(Deferred.await(finishConnection)),
641 + ),
642 + });
643 +
644 + yield* Effect.gen(function* () {
645 + const registry = yield* EnvironmentRegistry.EnvironmentRegistry;
646 + expect((yield* registry.state(TARGET.environmentId)).phase).toBe("connecting");
647 +
648 + yield* Deferred.await(connectionStarted);
649 + expect((yield* registry.state(TARGET.environmentId)).phase).toBe("connecting");
650 + yield* Deferred.succeed(finishConnection, undefined);
651 + }).pipe(Effect.provide(harness.layer), Effect.scoped);
652 + }),
653 + );
654 +
655 it.effect("exposes the current RPC generation to late query subscribers", () =>
656 Effect.gen(function* () {
657 const harness = yield* makeHarness([TARGET]);
packages/client-runtime/src/connection/registry.ts
+4 -4
@@ -356,7 +356,10 @@ export const make = Effect.gen(function* () {
356 const environmentId = entry.target.environmentId;
357 const scope = yield* Scope.fork(registryScope);
358 const supervisor = yield* EnvironmentSupervisor.make(entry, {
359 - initiallyDesired: false,
359 + // An enabled environment starts out connecting. Starting it idle and
360 + // then asking it to connect would first publish the state of an
361 + // environment the user switched off.
362 + initiallyDesired: entry.enabled,
363 learnRoutes: (input) => learnRoutes({ environmentId, ...input }),
364 }).pipe(
365 Effect.provideService(Connectivity.Connectivity, connectivity),
@@ -365,9 +368,6 @@ export const make = Effect.gen(function* () {
368 Scope.provide(scope),
369 Effect.onError(() => Scope.close(scope, Exit.void)),
370 );
368 - if (entry.enabled) {
369 - yield* supervisor.connect;
370 - }
371 yield* SubscriptionRef.update(serviceScopes, (current) => {
372 const next = new Map(current);
373 next.set(environmentId, { entry, supervisor, scope });
packages/client-runtime/src/state/runtime.test.ts
+90
@@ -517,6 +517,96 @@ describe("environment query lifecycle", () => {
517 ),
518 );
519
520 + it.effect("keeps a query pending when it loses its session before the atom sees the change", () =>
521 + Effect.scoped(
522 + Effect.gen(function* () {
523 + const firstStarted = Latch.makeUnsafe();
524 + const failFirst = Latch.makeUnsafe();
525 + const firstSettled = Latch.makeUnsafe();
526 + let executions = 0;
527 + const execute = Effect.suspend(() => {
528 + executions += 1;
529 + if (executions > 1) {
530 + return Effect.succeed("recovered");
531 + }
532 + firstStarted.openUnsafe();
533 + return failFirst.await.pipe(
534 + Effect.andThen(
535 + Effect.fail(
536 + new EnvironmentRpcUnavailableError({
537 + environmentId: QUERY_ENVIRONMENT.environmentId,
538 + message: "Query environment is not connected.",
539 + }),
540 + ),
541 + ),
542 + Effect.ensuring(
543 + Effect.sync(() => {
544 + firstSettled.openUnsafe();
545 + }),
546 + ),
547 + );
548 + });
549 + const harness = yield* makeEnvironmentQueryHarness(execute);
550 + const registry = AtomRegistry.make();
551 + const observed: Array<AsyncResult.AsyncResult<string, unknown>> = [];
552 + const unsubscribe = registry.subscribe(
553 + harness.atom,
554 + (result) => {
555 + observed.push(result);
556 + },
557 + { immediate: true },
558 + );
559 + yield* Effect.addFinalizer(() =>
560 + Effect.sync(() => {
561 + unsubscribe();
562 + registry.dispose();
563 + }),
564 + );
565 +
566 + yield* firstStarted.await;
567 + // No yield before the failure: the request finds its session gone
568 + // before the atom has processed the session change.
569 + yield* SubscriptionRef.set(harness.supervisorSession, Option.none());
570 + failFirst.openUnsafe();
571 + yield* firstSettled.await;
572 + yield* Effect.yieldNow;
573 +
574 + expect(observed.some(AsyncResult.isFailure)).toBe(false);
575 +
576 + yield* SubscriptionRef.set(harness.supervisorSession, Option.some(QUERY_RPC_SESSION));
577 + yield* SubscriptionRef.set(
578 + harness.supervisorState,
579 + queryConnectionState({ generation: 2 }),
580 + );
581 + expect(
582 + yield* AtomRegistry.getResult(registry, harness.atom, {
583 + suspendOnWaiting: true,
584 + }),
585 + ).toBe("recovered");
586 + expect(observed.some(AsyncResult.isFailure)).toBe(false);
587 + }),
588 + ),
589 + );
590 +
591 + it.effect("fails a query that reports unavailable while its session is still live", () =>
592 + Effect.scoped(
593 + Effect.gen(function* () {
594 + const unavailable = new EnvironmentRpcUnavailableError({
595 + environmentId: QUERY_ENVIRONMENT.environmentId,
596 + message: "The environment did not respond to the request.",
597 + });
598 + const harness = yield* makeEnvironmentQueryHarness(Effect.fail(unavailable));
599 + const registry = yield* mountEnvironmentQuery(harness.atom);
600 +
601 + const exit = yield* AtomRegistry.getResult(registry, harness.atom, {
602 + suspendOnWaiting: true,
603 + }).pipe(Effect.exit);
604 +
605 + expect(exit).toStrictEqual(Exit.fail(unavailable));
606 + }),
607 + ),
608 + );
609 +
610 it.effect.each([
611 {
612 condition: "after a manual disconnect",
packages/client-runtime/src/state/runtime.ts
+31 -1
@@ -12,6 +12,7 @@ import * as Cause from "effect/Cause";
12 import * as Effect from "effect/Effect";
13 import * as Exit from "effect/Exit";
14 import * as Option from "effect/Option";
15 +import * as Schema from "effect/Schema";
16 import * as Stream from "effect/Stream";
17 import * as SubscriptionRef from "effect/SubscriptionRef";
18 import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
@@ -33,6 +34,30 @@ import {
34 subscribe,
35 } from "../rpc/client.ts";
36 import * as EnvironmentSupervisor from "../connection/supervisor.ts";
37 +import type * as RpcSession from "../rpc/session.ts";
38 +
39 +const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
40 +
41 +/**
42 + * Holds back the unavailable failure of a query whose session went away. The
43 + * query atom reruns when it sees that session change, so settling first would
44 + * show a failure for a query that is about to retry. While `session` is still
45 + * current no rerun is coming, and the failure stands.
46 + */
47 +const pendingOnceSessionReplaced =
48 + (session: RpcSession.RpcSession) =>
49 + <A, E, R>(effect: Effect.Effect<A, E, R>) =>
50 + effect.pipe(
51 + // The query's error type is generic, so its tags are unknown to `catchTags`.
52 + Effect.catchIf(isEnvironmentRpcUnavailable, (error) =>
53 + EnvironmentSupervisor.EnvironmentSupervisor.pipe(
54 + Effect.flatMap((supervisor) => SubscriptionRef.get(supervisor.session)),
55 + Effect.flatMap((current) =>
56 + Option.isSome(current) && current.value === session ? Effect.fail(error) : Effect.never,
57 + ),
58 + ),
59 + ),
60 + );
61
62 interface EnvironmentAtomOptions<Input, A, E, R> {
63 readonly label: string;
@@ -601,7 +626,12 @@ export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
626 switch (connectionState.phase) {
627 case "connected":
628 return Option.isSome(session)
604 - ? runInEnvironment(target.environmentId, options.execute(target.input, emit))
629 + ? runInEnvironment(
630 + target.environmentId,
631 + options
632 + .execute(target.input, emit)
633 + .pipe(pendingOnceSessionReplaced(session.value)),
634 + )
635 : Effect.never;
636 case "connecting":
637 case "backoff":