Skip to content
TypeScript

perf(mobile): show the cached thread list sooner and stop the freeze after it (#16713)

Julius Marmingef9e16b3f6647
diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.ts
index 8e4ce3e6211..e1d627b5046 100644
--- a/apps/mobile/src/connection/environment-cache-store.test.ts
+++ b/apps/mobile/src/connection/environment-cache-store.test.ts
@@ -10,12 +10,14 @@ import {
ThreadId,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ThreadDetailSnapshot,
+ type ThreadPullRequestLink,
type VcsListRefsResult,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
+import * as Logger from "effect/Logger";
import * as Schema from "effect/Schema";
import { vi } from "vite-plus/test";
import * as Deferred from "effect/Deferred";
@@ -254,6 +256,79 @@ describe("mobile SQLite environment cache store", () => {
}),
);
+ it.live("returns cached threads before their pull request links, which load after", () =>
+ Effect.gen(function* () {
+ const memory = makeDatabase();
+ const store = yield* make().pipe(
+ Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
+ );
+ const link: ThreadPullRequestLink = {
+ host: "github.com",
+ repository: "pingdotgg/t3code",
+ number: 42,
+ url: "https://github.com/pingdotgg/t3code/pull/42",
+ source: "agent",
+ linkedAt: "2026-07-29T12:00:00.000Z",
+ snapshot: null,
+ stack: null,
+ };
+ const linked = { ...SHELL_SNAPSHOT.threads[0]!, pullRequests: [link] };
+ const unlinked = { ...SHELL_SNAPSHOT.threads[0]!, id: ThreadId.make("thread-2") };
+ yield* store.saveShell(ENVIRONMENT_ID, {
+ ...SHELL_SNAPSHOT,
+ threads: [linked, unlinked],
+ });
+
+ const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
+ expect(shell.threads.map((thread) => thread.pullRequests)).toEqual([undefined, undefined]);
+ const links = yield* shell.loadPullRequests!;
+ expect([...links]).toEqual([[THREAD_ID, [link]]]);
+ }),
+ );
+
+ it.live("keeps cached threads when their pull request links cannot be read", () => {
+ const messages: Array<unknown> = [];
+ const logger = Logger.make(({ message }) => {
+ messages.push(message);
+ });
+ return Effect.gen(function* () {
+ const memory = makeDatabase();
+ const store = yield* make().pipe(
+ Effect.provideService(MobileDatabase.MobileDatabase, memory.database),
+ );
+ const link: ThreadPullRequestLink = {
+ host: "github.com",
+ repository: "pingdotgg/t3code",
+ number: 5,
+ url: "https://github.com/pingdotgg/t3code/pull/5",
+ source: "agent",
+ linkedAt: "2026-07-29T12:00:00.000Z",
+ snapshot: null,
+ stack: null,
+ };
+ const readable = {
+ ...SHELL_SNAPSHOT.threads[0]!,
+ id: ThreadId.make("thread-2"),
+ pullRequests: [link],
+ };
+ yield* store.saveShell(ENVIRONMENT_ID, {
+ ...SHELL_SNAPSHOT,
+ threads: [SHELL_SNAPSHOT.threads[0]!, readable],
+ });
+ const id = cacheId(ENVIRONMENT_ID, "shell", "snapshot");
+ const payload = JSON.parse(memory.values.get(id)!);
+ payload.snapshot.threads[0].pullRequests = [{ number: -1 }];
+ memory.values.set(id, JSON.stringify(payload));
+
+ const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
+ expect(shell.threads.map((thread) => thread.id)).toEqual([THREAD_ID, readable.id]);
+ // Only the thread with the unreadable link loses its links.
+ expect([...(yield* shell.loadPullRequests!)]).toEqual([[readable.id, [link]]]);
+ expect(messages).toHaveLength(1);
+ expect(memory.removed).toEqual([]);
+ }).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
+ });
+
it.effect("round-trips schema-validated VCS refs", () =>
Effect.gen(function* () {
const memory = makeDatabase();
diff --git a/apps/mobile/src/connection/environment-cache-store.ts b/apps/mobile/src/connection/environment-cache-store.ts
index 70c2a91f67a..99019d1d692 100644
--- a/apps/mobile/src/connection/environment-cache-store.ts
+++ b/apps/mobile/src/connection/environment-cache-store.ts
@@ -1,6 +1,5 @@
import {
ORCHESTRATION_CACHE_SCHEMA_VERSION,
- StoredOrchestrationShellSnapshot,
StoredOrchestrationThreadSnapshot,
Persistence,
} from "@t3tools/client-runtime/platform";
@@ -16,6 +15,7 @@ import {
attachProjectFaviconDatabase,
projectFaviconDatabaseCache,
} from "../lib/projectFaviconDatabaseCache";
+import { decodeStoredShellSnapshot } from "./shell-cache-decoding";
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
@@ -32,9 +32,6 @@ const StoredVcsRefs = Schema.Struct({
refs: VcsListRefsResult,
});
-const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
- Schema.fromJsonString(StoredOrchestrationShellSnapshot),
-);
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
);
@@ -113,7 +110,15 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
decode: decodeStoredShellSnapshot,
select: (stored) =>
stored.environmentId === environmentId ? Option.some(stored.snapshot) : Option.none(),
- }).pipe(Effect.tap(() => Effect.promise(() => projectFaviconDatabaseCache.hydrate()))),
+ }).pipe(
+ // Read cached project icons in parallel with the shell so the first rows can show
+ // them, instead of making the thread list wait for the icon read after the decode.
+ Effect.zipWith(
+ Effect.promise(() => projectFaviconDatabaseCache.hydrate()),
+ (snapshot) => snapshot,
+ { concurrent: true },
+ ),
+ ),
),
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
const payload = yield* encodeStoredShellSnapshot({
diff --git a/apps/mobile/src/connection/shell-cache-decoding.ts b/apps/mobile/src/connection/shell-cache-decoding.ts
new file mode 100644
index 00000000000..ef70036e524
--- /dev/null
+++ b/apps/mobile/src/connection/shell-cache-decoding.ts
@@ -0,0 +1,19 @@
+import { StoredOrchestrationShellSnapshot } from "@t3tools/client-runtime/platform";
+import { deferPullRequests, detachPullRequests } from "@t3tools/client-runtime/state/shell";
+import * as Effect from "effect/Effect";
+import * as Predicate from "effect/Predicate";
+import * as Schema from "effect/Schema";
+
+const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
+const decodeStoredShell = Schema.decodeUnknownEffect(StoredOrchestrationShellSnapshot);
+
+/**
+ * Decode the shell cache payload with each thread's pull request links left out, so the
+ * thread list can paint first; `loadPullRequests` decodes the links afterwards.
+ */
+export const decodeStoredShellSnapshot = Effect.fnUntraced(function* (raw: string) {
+ const parsed = yield* decodeJson(raw);
+ const rawLinks = Predicate.isObject(parsed) ? detachPullRequests(parsed.snapshot) : [];
+ const stored = yield* decodeStoredShell(parsed);
+ return { ...stored, snapshot: deferPullRequests(stored.snapshot, rawLinks) };
+});
diff --git a/packages/client-runtime/src/platform/persistence.ts b/packages/client-runtime/src/platform/persistence.ts
index c146adee1e8..29463ce6da5 100644
--- a/packages/client-runtime/src/platform/persistence.ts
+++ b/packages/client-runtime/src/platform/persistence.ts
@@ -12,6 +12,7 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type { ConnectionRegistration } from "../connection/catalog.ts";
+import type { DeferredShellSnapshot } from "../state/shellPullRequests.ts";
import type { ConnectionTarget, PersistedConnectionTarget } from "../connection/model.ts";
export class ConnectionPersistenceError extends Schema.TaggedError<ConnectionPersistenceError>()(
@@ -82,7 +83,7 @@ export class EnvironmentCacheStore extends Context.Service<
{
readonly loadShell: (
environmentId: EnvironmentId,
- ) => Effect.Effect<Option.Option<OrchestrationV2ShellSnapshot>, ConnectionPersistenceError>;
+ ) => Effect.Effect<Option.Option<DeferredShellSnapshot>, ConnectionPersistenceError>;
readonly saveShell: (
environmentId: EnvironmentId,
snapshot: OrchestrationV2ShellSnapshot,
diff --git a/packages/client-runtime/src/state/environmentHttpAuth.test.ts b/packages/client-runtime/src/state/environmentHttpAuth.test.ts
index c7c7fc53197..61504668427 100644
--- a/packages/client-runtime/src/state/environmentHttpAuth.test.ts
+++ b/packages/client-runtime/src/state/environmentHttpAuth.test.ts
@@ -204,7 +204,11 @@ const LOADERS: ReadonlyArray<{
path: "/api/orchestration/shell",
response: SHELL,
expected: SHELL,
- load: fetchEnvironmentShellSnapshot,
+ // Pull request links decode separately; the rows match the response on their own.
+ load: (input: HttpInput) =>
+ fetchEnvironmentShellSnapshot(input).pipe(
+ Effect.map(({ loadPullRequests: _links, ...snapshot }) => snapshot),
+ ),
},
{
name: "thread snapshot",
@@ -254,6 +258,20 @@ describe("authenticated environment HTTP requests", () => {
}),
);
+ it.effect("keeps the status of a shell snapshot error that is not a declared error", () =>
+ Effect.gen(function* () {
+ const harness = makeHarness(() => Response.json({ error: "bad_gateway" }, { status: 502 }));
+ const error = yield* fetchEnvironmentShellSnapshot(harness.input).pipe(
+ Effect.provide(harness.httpLayer),
+ Effect.flip,
+ );
+ expect(error).toMatchObject({
+ _tag: "RemoteEnvironmentAuthUndeclaredStatusError",
+ status: 502,
+ });
+ }),
+ );
+
it.effect.each(LOADERS)("uses current relay authorization and endpoint for $name", (loader) =>
Effect.gen(function* () {
const harness = makeHarness(() => Response.json(loader.response));
diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.ts
index 69d72831649..b20d3e9cda1 100644
--- a/packages/client-runtime/src/state/shell-sync.test.ts
+++ b/packages/client-runtime/src/state/shell-sync.test.ts
@@ -3,6 +3,8 @@ import {
ORCHESTRATION_V2_WS_METHODS,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ShellStreamItem,
+ ThreadId,
+ type ThreadPullRequestLink,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
@@ -29,7 +31,7 @@ import * as RpcSession from "../rpc/session.ts";
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
import { makeEnvironmentShellState } from "./shell.ts";
import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
-import { v2Project, v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts";
+import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
@@ -953,4 +955,346 @@ describe("environment shell synchronization", () => {
expect(Option.getOrThrow(state.snapshot).projects[0]?.title).toBe("Server reset");
}),
);
+
+ it.effect("fills deferred cached pull request links without overwriting newer rows", () =>
+ Effect.gen(function* () {
+ const link = (number: number): ThreadPullRequestLink => ({
+ host: "github.com",
+ repository: "pingdotgg/t3code",
+ number,
+ url: `https://github.com/pingdotgg/t3code/pull/${number}`,
+ source: "agent",
+ linkedAt: "2026-06-20T00:00:00.000Z",
+ snapshot: null,
+ stack: null,
+ });
+ const otherThreadId = ThreadId.make("thread-other");
+ const cachedSnapshot: OrchestrationV2ShellSnapshot = {
+ ...v2ShellSnapshot,
+ snapshotSequence: 5,
+ threads: [v2ThreadShell, { ...v2ThreadShell, id: otherThreadId }],
+ };
+ const linksReady = yield* Deferred.make<void>();
+ const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
+ const client = {
+ [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events),
+ } as unknown as WsRpcProtocolClient;
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
+ target: TARGET,
+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
+ session: yield* SubscriptionRef.make(Option.some(session(client))),
+ prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
+ connect: Effect.void,
+ disconnect: Effect.void,
+ retryNow: Effect.void,
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
+ const cache = Persistence.EnvironmentCacheStore.of({
+ loadShell: () =>
+ Effect.succeedSome({
+ ...cachedSnapshot,
+ loadPullRequests: Deferred.await(linksReady).pipe(
+ Effect.as(
+ new Map([
+ [v2ThreadShell.id, [link(1)]],
+ [otherThreadId, [link(2)]],
+ ]),
+ ),
+ ),
+ }),
+ saveShell: () => Effect.void,
+ loadThread: () => Effect.succeedNone,
+ saveThread: () => Effect.void,
+ removeThread: () => Effect.void,
+ loadServerConfig: () => Effect.succeedNone,
+ saveServerConfig: () => Effect.void,
+ loadVcsRefs: () => Effect.succeedNone,
+ saveVcsRefs: () => Effect.void,
+ removeVcsRefs: () => Effect.void,
+ clearVcsRefs: () => Effect.void,
+ clear: () => Effect.void,
+ });
+ // No HTTP snapshot, so the cached rows stay until the socket sends deltas.
+ const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
+ load: () => Effect.succeedNone,
+ });
+ const shellState = yield* makeEnvironmentShellState().pipe(
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),
+ Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
+ );
+
+ const threadsOf = (state: {
+ readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
+ }) => Option.getOrThrow(state.snapshot).threads;
+ expect(threadsOf(yield* SubscriptionRef.get(shellState))).toEqual(cachedSnapshot.threads);
+
+ // The server updates one row before the cached links finish decoding.
+ const serverRow = { ...v2ThreadShell, title: "From server", pullRequests: [link(9)] };
+ yield* Queue.offer(events, {
+ kind: "thread.updated",
+ sequence: 6,
+ location: "active",
+ thread: serverRow,
+ });
+ yield* SubscriptionRef.changes(shellState).pipe(
+ Stream.filter((state) => threadsOf(state)[0]?.title === "From server"),
+ Stream.runHead,
+ );
+
+ yield* Deferred.succeed(linksReady, undefined);
+ const filled = yield* SubscriptionRef.changes(shellState).pipe(
+ Stream.map(threadsOf),
+ Stream.filter((threads) => threads[1]?.pullRequests !== undefined),
+ Stream.runHead,
+ Effect.map(Option.getOrThrow),
+ );
+ expect(filled[0]).toBe(serverRow);
+ expect(filled[1]?.pullRequests).toEqual([link(2)]);
+ }),
+ );
+
+ it.effect("shows HTTP rows before their pull request links and saves them once filled", () =>
+ Effect.gen(function* () {
+ const link: ThreadPullRequestLink = {
+ host: "github.com",
+ repository: "pingdotgg/t3code",
+ number: 7,
+ url: "https://github.com/pingdotgg/t3code/pull/7",
+ source: "agent",
+ linkedAt: "2026-06-20T00:00:00.000Z",
+ snapshot: null,
+ stack: null,
+ };
+ const httpSnapshot: OrchestrationV2ShellSnapshot = {
+ ...v2ShellSnapshot,
+ snapshotSequence: 3,
+ };
+ const linksReady = yield* Deferred.make<void>();
+ const saved = yield* Queue.unbounded<OrchestrationV2ShellSnapshot>();
+ const client = {
+ [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.never,
+ } as unknown as WsRpcProtocolClient;
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
+ target: TARGET,
+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
+ session: yield* SubscriptionRef.make(Option.some(session(client))),
+ prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
+ connect: Effect.void,
+ disconnect: Effect.void,
+ retryNow: Effect.void,
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
+ const cache = Persistence.EnvironmentCacheStore.of({
+ loadShell: () => Effect.succeedNone,
+ saveShell: (_environmentId, snapshot) => Queue.offer(saved, snapshot),
+ loadThread: () => Effect.succeedNone,
+ saveThread: () => Effect.void,
+ removeThread: () => Effect.void,
+ loadServerConfig: () => Effect.succeedNone,
+ saveServerConfig: () => Effect.void,
+ loadVcsRefs: () => Effect.succeedNone,
+ saveVcsRefs: () => Effect.void,
+ removeVcsRefs: () => Effect.void,
+ clearVcsRefs: () => Effect.void,
+ clear: () => Effect.void,
+ });
+ const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
+ load: () =>
+ Effect.succeedSome({
+ ...httpSnapshot,
+ loadPullRequests: Deferred.await(linksReady).pipe(
+ Effect.as(new Map([[v2ThreadShell.id, [link]]])),
+ ),
+ }),
+ });
+ const shellState = yield* makeEnvironmentShellState().pipe(
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),
+ Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
+ );
+
+ const rows = yield* SubscriptionRef.changes(shellState).pipe(
+ Stream.filter((state) => Option.isSome(state.snapshot)),
+ Stream.runHead,
+ Effect.map((state) => Option.getOrThrow(Option.getOrThrow(state).snapshot)),
+ );
+ expect(rows.threads[0]?.pullRequests).toBeUndefined();
+ expect(rows).not.toHaveProperty("loadPullRequests");
+
+ yield* Deferred.succeed(linksReady, undefined);
+ const filled = yield* SubscriptionRef.changes(shellState).pipe(
+ Stream.map((state) => Option.getOrThrow(state.snapshot).threads[0]),
+ Stream.filter((thread) => thread?.pullRequests !== undefined),
+ Stream.runHead,
+ Effect.map(Option.getOrThrow),
+ );
+ expect(filled?.pullRequests).toEqual([link]);
+
+ // The cache must end up with the links: the last save carries them.
+ yield* TestClock.adjust("30 seconds");
+ const saves = yield* Queue.takeAll(saved);
+ expect(saves.at(-1)?.threads[0]?.pullRequests).toEqual([link]);
+ }),
+ );
+
+ it.effect("does not save rows whose deferred links are still pending", () =>
+ Effect.gen(function* () {
+ const link: ThreadPullRequestLink = {
+ host: "github.com",
+ repository: "pingdotgg/t3code",
+ number: 8,
+ url: "https://github.com/pingdotgg/t3code/pull/8",
+ source: "agent",
+ linkedAt: "2026-06-20T00:00:00.000Z",
+ snapshot: null,
+ stack: null,
+ };
+ const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);
+ const client = {
+ [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.never,
+ } as unknown as WsRpcProtocolClient;
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
+ target: TARGET,
+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
+ session: yield* SubscriptionRef.make(Option.some(session(client))),
+ prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
+ connect: Effect.void,
+ disconnect: Effect.void,
+ retryNow: Effect.void,
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
+ const cache = Persistence.EnvironmentCacheStore.of({
+ loadShell: () => Effect.succeedNone,
+ saveShell: (_environmentId, snapshot) => Ref.update(saved, (all) => [...all, snapshot]),
+ loadThread: () => Effect.succeedNone,
+ saveThread: () => Effect.void,
+ removeThread: () => Effect.void,
+ loadServerConfig: () => Effect.succeedNone,
+ saveServerConfig: () => Effect.void,
+ loadVcsRefs: () => Effect.succeedNone,
+ saveVcsRefs: () => Effect.void,
+ removeVcsRefs: () => Effect.void,
+ clearVcsRefs: () => Effect.void,
+ clear: () => Effect.void,
+ });
+ const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
+ load: () =>
+ Effect.succeedSome({
+ ...v2ShellSnapshot,
+ snapshotSequence: 3,
+ // Links never finish decoding before the shell closes.
+ loadPullRequests: Effect.never.pipe(Effect.as(new Map([[v2ThreadShell.id, [link]]]))),
+ }),
+ });
+ const scope = yield* Scope.make();
+ const shellState = yield* makeEnvironmentShellState().pipe(
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),
+ Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
+ Scope.provide(scope),
+ );
+ yield* SubscriptionRef.changes(shellState).pipe(
+ Stream.filter((state) => Option.isSome(state.snapshot)),
+ Stream.runHead,
+ );
+
+ // Neither the throttled worker nor the closing flush may save the rows without links.
+ yield* TestClock.adjust("30 seconds");
+ yield* Scope.close(scope, Exit.void);
+ expect(yield* Ref.get(saved)).toEqual([]);
+ }),
+ );
+
+ it.effect("drops an older snapshot's links once a newer snapshot reuses its rows", () =>
+ Effect.gen(function* () {
+ const link = (number: number): ThreadPullRequestLink => ({
+ host: "github.com",
+ repository: "pingdotgg/t3code",
+ number,
+ url: `https://github.com/pingdotgg/t3code/pull/${number}`,
+ source: "agent",
+ linkedAt: "2026-06-20T00:00:00.000Z",
+ snapshot: null,
+ stack: null,
+ });
+ const firstLinks = yield* Deferred.make<void>();
+ const secondLinks = yield* Deferred.make<void>();
+ // Set once each snapshot's links start decoding, i.e. once its rows are applied.
+ const firstFillStarted = yield* Deferred.make<void>();
+ const loads = yield* Ref.make(0);
+ const subscriptions = yield* Ref.make(0);
+ const client = {
+ [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () =>
+ Stream.unwrap(Ref.update(subscriptions, (n) => n + 1).pipe(Effect.as(Stream.never))),
+ } as unknown as WsRpcProtocolClient;
+ const activeSession = yield* SubscriptionRef.make<Option.Option<RpcSession.RpcSession>>(
+ Option.some(session(client)),
+ );
+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
+ target: TARGET,
+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),
+ session: activeSession,
+ prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),
+ connect: Effect.void,
+ disconnect: Effect.void,
+ retryNow: Effect.void,
+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
+ const cache = Persistence.EnvironmentCacheStore.of({
+ loadShell: () => Effect.succeedNone,
+ saveShell: () => Effect.void,
+ loadThread: () => Effect.succeedNone,
+ saveThread: () => Effect.void,
+ removeThread: () => Effect.void,
+ loadServerConfig: () => Effect.succeedNone,
+ saveServerConfig: () => Effect.void,
+ loadVcsRefs: () => Effect.succeedNone,
+ saveVcsRefs: () => Effect.void,
+ removeVcsRefs: () => Effect.void,
+ clearVcsRefs: () => Effect.void,
+ clear: () => Effect.void,
+ });
+ // Both snapshots carry the same row; only its pull request links differ.
+ const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({
+ load: () =>
+ Ref.updateAndGet(loads, (n) => n + 1).pipe(
+ Effect.map((n) =>
+ Option.some({
+ ...v2ShellSnapshot,
+ snapshotSequence: n,
+ loadPullRequests: (n === 1
+ ? Deferred.succeed(firstFillStarted, undefined).pipe(
+ Effect.andThen(Deferred.await(firstLinks)),
+ )
+ : Deferred.await(secondLinks)
+ ).pipe(Effect.as(new Map([[v2ThreadShell.id, [link(n)]]]))),
+ }),
+ ),
+ ),
+ });
+ const shellState = yield* makeEnvironmentShellState().pipe(
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),
+ Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),
+ );
+ yield* Deferred.await(firstFillStarted);
+
+ // A new session loads a second snapshot that reuses the bare row.
+ yield* SubscriptionRef.set(activeSession, Option.some(session(client)));
+ yield* SubscriptionRef.changes(shellState).pipe(
+ Stream.filter(
+ (state) => Option.isSome(state.snapshot) && state.snapshot.value.snapshotSequence === 2,
+ ),
+ Stream.runHead,
+ );
+
+ // The superseded first fill finishes first, then the second.
+ yield* Deferred.succeed(firstLinks, undefined);
+ yield* Deferred.succeed(secondLinks, undefined);
+ const filled = yield* SubscriptionRef.changes(shellState).pipe(
+ Stream.map((state) => Option.getOrThrow(state.snapshot).threads[0]?.pullRequests),
+ Stream.filter((links) => links !== undefined),
+ Stream.runHead,
+ Effect.map(Option.getOrThrow),
+ );
+ expect(filled).toEqual([link(2)]);
+ }),
+ );
});
diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts
index 2c479489e31..dbc4405a9fa 100644
--- a/packages/client-runtime/src/state/shell.ts
+++ b/packages/client-runtime/src/state/shell.ts
@@ -3,10 +3,14 @@ import {
type EnvironmentId,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ShellStreamItem,
+ type OrchestrationV2ThreadShell,
type ServerConfig,
+ type ThreadId,
+ type ThreadPullRequestLink,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
@@ -25,7 +29,13 @@ import { runCachePersistence } from "./cachePersistence.ts";
import { subscribeDynamic } from "../rpc/client.ts";
import type { RpcSession } from "../rpc/session.ts";
import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
-import { applyShellStreamEvent, mergeShellSnapshotProjects } from "./shellReducer.ts";
+import type { DeferredShellSnapshot } from "./shellPullRequests.ts";
+import {
+ applyShellStreamEvent,
+ mergeShellSnapshotProjects,
+ reuseUnchangedThreadShells,
+ sameThreadPullRequests,
+} from "./shellReducer.ts";
import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts";
import { followStreamInEnvironment } from "./runtime.ts";
@@ -49,6 +59,12 @@ function shellStatusForSnapshot(
return Option.isSome(snapshot) ? "cached" : "empty";
}
+function withoutDeferredPullRequests(value: DeferredShellSnapshot): OrchestrationV2ShellSnapshot {
+ if (value.loadPullRequests === undefined) return value;
+ const { loadPullRequests: _deferred, ...snapshot } = value;
+ return snapshot;
+}
+
const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = "Could not synchronize environment data.";
export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")(function* () {
@@ -57,17 +73,18 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
const snapshotLoader = yield* ShellSnapshotLoader.ShellSnapshotLoader;
const wakeups = yield* Effect.serviceOption(ConnectionWakeups.ConnectionWakeups);
const environmentId = supervisor.target.environmentId;
- const cachedSnapshot = yield* cache.loadShell(environmentId).pipe(
+ const cached = yield* cache.loadShell(environmentId).pipe(
Effect.catch((error) =>
Effect.logWarning("Could not load cached environment shell.").pipe(
Effect.annotateLogs({
environmentId,
...safeErrorLogAttributes(error),
}),
- Effect.as(Option.none<OrchestrationV2ShellSnapshot>()),
+ Effect.as(Option.none<DeferredShellSnapshot>()),
),
),
);
+ const cachedSnapshot = Option.map(cached, withoutDeferredPullRequests);
const state = yield* SubscriptionRef.make<EnvironmentShellState>({
snapshot: cachedSnapshot,
status: shellStatusForSnapshot(cachedSnapshot),
@@ -83,12 +100,16 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
const persistenceLock = yield* Semaphore.make(1);
let lastPersisted: OrchestrationV2ShellSnapshot | undefined;
+ // Rows still waiting for their deferred pull request links, which must not be saved:
+ // the cache would keep them without links until the next server refresh.
+ let pendingLinkRows: ReadonlySet<OrchestrationV2ThreadShell> = new Set();
const persistLatest = Effect.fn("EnvironmentShellState.persistLatest")(function* (
flush: boolean,
) {
while (true) {
const latest = yield* Ref.get(latestLiveSnapshot);
if (Option.isNone(latest) || latest.value === lastPersisted) return;
+ if (latest.value.threads.some((thread) => pendingLinkRows.has(thread))) return;
const snapshot = latest.value;
const saved = yield* cache.saveShell(environmentId, snapshot).pipe(
Effect.as(true),
@@ -155,11 +176,17 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
),
);
+ // Server items and deferred link fills both read the snapshot and write it back; one at a
+ // time, so neither can overwrite what the other wrote in between.
+ const snapshotWriteLock = yield* Semaphore.make(1);
+
// Apply each received batch with one state write. The RPC client's bounded
// buffer can split a server chunk, so a bulk action can still need several
// writes, but each write includes every event in that batch.
const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* (
items: ReadonlyArray<OrchestrationV2ShellStreamItem>,
+ // Ids of rows whose links will fill later; they are held out of saves before one queues.
+ pendingLinkIds?: ReadonlySet<ThreadId>,
) {
const initial = yield* SubscriptionRef.get(state);
let waiting = yield* Ref.get(awaitingCompletion);
@@ -201,6 +228,11 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
}
yield* Ref.set(awaitingCompletion, waiting);
if (next === initial) return;
+ if (pendingLinkIds !== undefined && Option.isSome(next.snapshot)) {
+ pendingLinkRows = new Set(
+ next.snapshot.value.threads.filter((thread) => pendingLinkIds.has(thread.id)),
+ );
+ }
if (Option.isSome(next.snapshot)) {
yield* Ref.set(latestLiveSnapshot, next.snapshot);
}
@@ -214,7 +246,81 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) {
yield* Queue.offer(persistence, next.snapshot.value);
}
+ }, snapshotWriteLock.withPermit);
+
+ // Rows can arrive before their pull request links (see DeferredShellSnapshot), so the list
+ // paints first. The links then fill into the rows that still hold the object they arrived
+ // with; a row the server has replaced since carries its own links.
+ // Captured so fills started from the subscription callback still end with this state.
+ const stateScope = yield* Effect.scope;
+ // Each full snapshot supersedes the previous one's fill; links from an older snapshot must
+ // not land on rows a newer snapshot reused. A cancelled fill's rows stay pending until the
+ // next snapshot replaces the pending set.
+ let activeFill: Fiber.Fiber<void> | undefined;
+ const cancelActiveFill = Effect.suspend(() => {
+ const fill = activeFill;
+ activeFill = undefined;
+ return fill === undefined ? Effect.void : Fiber.interrupt(fill);
});
+ const fillDeferredPullRequests = Effect.fnUntraced(function* (
+ source: DeferredShellSnapshot,
+ applied: OrchestrationV2ShellSnapshot,
+ ) {
+ yield* cancelActiveFill;
+ if (source.loadPullRequests === undefined) return;
+ const arrivedRows = new Set(applied.threads);
+ const arrivedIds = new Set(source.threads.map((thread) => thread.id));
+ pendingLinkRows = new Set(applied.threads.filter((thread) => arrivedIds.has(thread.id)));
+ activeFill = yield* source.loadPullRequests.pipe(
+ Effect.flatMap((linksByThreadId) =>
+ writeFilledLinks(linksByThreadId, arrivedRows, arrivedIds),
+ ),
+ Effect.forkIn(stateScope),
+ );
+ });
+ const writeFilledLinks = Effect.fnUntraced(
+ function* (
+ linksByThreadId: ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>,
+ arrivedRows: ReadonlySet<OrchestrationV2ThreadShell>,
+ arrivedIds: ReadonlySet<ThreadId>,
+ ) {
+ const filled = yield* SubscriptionRef.modify(
+ state,
+ (current): [Option.Option<OrchestrationV2ShellSnapshot>, EnvironmentShellState] => {
+ if (Option.isNone(current.snapshot)) return [Option.none(), current];
+ const snapshot = current.snapshot.value;
+ let changed = false;
+ const threads = snapshot.threads.map((thread) => {
+ if (!arrivedRows.has(thread) || !arrivedIds.has(thread.id)) return thread;
+ const links = linksByThreadId.get(thread.id);
+ // A reused row may already hold these links from an earlier fill.
+ if (sameThreadPullRequests(thread.pullRequests, links)) return thread;
+ changed = true;
+ if (links === undefined) {
+ const { pullRequests: _previous, ...row } = thread;
+ return row;
+ }
+ return { ...thread, pullRequests: links };
+ });
+ if (!changed) return [Option.none(), current];
+ const next = { ...snapshot, threads };
+ return [Option.some(next), { ...current, snapshot: Option.some(next) }];
+ },
+ );
+ // Saves skipped while links were pending are queued again. Cached rows are never live:
+ // until a server snapshot arrives there is nothing new to save.
+ pendingLinkRows = new Set();
+ const live = yield* Ref.get(latestLiveSnapshot);
+ if (Option.isNone(live)) return;
+ const latest = Option.isSome(filled) ? filled : live;
+ yield* Ref.set(latestLiveSnapshot, latest);
+ yield* Queue.offer(persistence, latest.value);
+ },
+ (effect) => snapshotWriteLock.withPermit(effect),
+ );
+ if (Option.isSome(cached) && Option.isSome(cachedSnapshot)) {
+ yield* fillDeferredPullRequests(cached.value, cachedSnapshot.value);
+ }
const foregroundResubscriptions = Option.match(wakeups, {
onNone: () => Stream.never,
@@ -258,9 +364,23 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
);
const httpSnapshot = yield* snapshotLoader.load(prepared);
if (Option.isSome(httpSnapshot)) {
- yield* applyItems([{ kind: "snapshot", snapshot: httpSnapshot.value }]);
+ yield* cancelActiveFill;
+ const previous = yield* SubscriptionRef.get(state);
+ const snapshot = reuseUnchangedThreadShells(
+ Option.getOrNull(previous.snapshot),
+ withoutDeferredPullRequests(httpSnapshot.value),
+ );
+ const pendingLinkIds = new Set(
+ httpSnapshot.value.loadPullRequests === undefined
+ ? []
+ : httpSnapshot.value.threads.map((thread) => thread.id),
+ );
+ yield* applyItems([{ kind: "snapshot", snapshot }], pendingLinkIds);
canResume = true;
current = yield* SubscriptionRef.get(state);
+ if (Option.isSome(current.snapshot)) {
+ yield* fillDeferredPullRequests(httpSnapshot.value, current.snapshot.value);
+ }
}
}
@@ -288,7 +408,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
retryExpectedFailureAfter: "250 millis",
resubscribe: foregroundResubscriptions,
},
- ).pipe(Stream.runForEachArray(applyItems)),
+ ).pipe(Stream.runForEachArray((items) => applyItems(items))),
);
yield* SubscriptionRef.changes(supervisor.state).pipe(
Stream.runForEach((connectionState) => {
@@ -449,5 +569,6 @@ export function createEnvironmentShellAtoms<R, E>(
export * from "./models.ts";
export * from "./shellCommands.ts";
export * from "./shellReducer.ts";
+export * from "./shellPullRequests.ts";
export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";
export * from "./snapshots.ts";
diff --git a/packages/client-runtime/src/state/shellPullRequests.ts b/packages/client-runtime/src/state/shellPullRequests.ts
new file mode 100644
index 00000000000..aedc90d25d9
--- /dev/null
+++ b/packages/client-runtime/src/state/shellPullRequests.ts
@@ -0,0 +1,97 @@
+import {
+ OrchestrationV2ShellSnapshot,
+ type ThreadId,
+ ThreadPullRequestLink,
+} from "@t3tools/contracts";
+import * as Effect from "effect/Effect";
+import * as Predicate from "effect/Predicate";
+import * as Schema from "effect/Schema";
+
+/**
+ * A shell snapshot whose threads may arrive before their pull request links are decoded. Those
+ * links are most of a large shell's decode cost and only feed PR badges, so the thread list
+ * can paint first. `loadPullRequests` then decodes the links by thread id; until it runs,
+ * those threads carry no `pullRequests`.
+ */
+export interface DeferredShellSnapshot extends OrchestrationV2ShellSnapshot {
+ readonly loadPullRequests?: Effect.Effect<
+ ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>
+ >;
+}
+
+// A zero sleep is a microtask yield, which on React Native runs before the next frame.
+// A 1ms sleep takes a host timer, so the rows can render before the deferred decode.
+const yieldToHost = Effect.sleep("1 millis");
+
+const decodeThreadLinks = Schema.decodeUnknownEffect(
+ Schema.UndefinedOr(Schema.toCodecJson(Schema.Array(ThreadPullRequestLink))),
+);
+// Bounds each uninterrupted stretch of decoding, so taps and frames run between batches.
+const LINKS_PER_BATCH = 400;
+
+/**
+ * Removes each parsed thread row's pull request links from `snapshot` in place and returns
+ * them in row order, for `deferPullRequests` once the rows are decoded.
+ */
+export function detachPullRequests(snapshot: unknown): ReadonlyArray<unknown> {
+ if (!Predicate.isObject(snapshot)) return [];
+ const rows: unknown = snapshot.threads;
+ if (!Array.isArray(rows)) return [];
+ return rows.map((row: unknown) => {
+ if (!Predicate.isObject(row)) return undefined;
+ const links = row.pullRequests;
+ delete row.pullRequests;
+ return links;
+ });
+}
+
+/**
+ * Attaches a `loadPullRequests` that decodes the detached links after yielding to the host.
+ * A thread whose links cannot be read gets none; its row stays usable.
+ */
+export function deferPullRequests<S extends OrchestrationV2ShellSnapshot>(
+ snapshot: S,
+ rawLinks: ReadonlyArray<unknown>,
+): S & Required<Pick<DeferredShellSnapshot, "loadPullRequests">> {
+ const threadIds = snapshot.threads.map((thread) => thread.id);
+ // Schema decoding runs when called, so each thread's decode is built after a yield.
+ const loadPullRequests = Effect.gen(function* () {
+ const linksByThreadId = new Map<ThreadId, ReadonlyArray<ThreadPullRequestLink>>();
+ let batchSize = LINKS_PER_BATCH;
+ for (const [index, threadId] of threadIds.entries()) {
+ const raw = rawLinks[index];
+ if (raw === undefined) continue;
+ const size = Array.isArray(raw) ? raw.length : 1;
+ if (batchSize + size > LINKS_PER_BATCH) {
+ yield* yieldToHost;
+ batchSize = 0;
+ }
+ batchSize += size;
+ // An unreadable thread keeps no links; the others still fill in.
+ const links = yield* decodeThreadLinks(raw).pipe(
+ Effect.catch((cause) =>
+ Effect.logWarning("Discarding unreadable shell pull request links.", {
+ threadId,
+ cause: String(cause),
+ }).pipe(Effect.as(undefined)),
+ ),
+ );
+ if (links !== undefined) linksByThreadId.set(threadId, links);
+ }
+ return linksByThreadId as ReadonlyMap<ThreadId, ReadonlyArray<ThreadPullRequestLink>>;
+ });
+ return { ...snapshot, loadPullRequests };
+}
+
+const decodeShellSnapshotJson = Schema.decodeUnknownEffect(
+ Schema.toCodecJson(OrchestrationV2ShellSnapshot),
+);
+
+/** Decodes a JSON shell snapshot with its threads' pull request links deferred. */
+export const decodeShellSnapshotDeferringPullRequests = Effect.fnUntraced(function* (
+ json: unknown,
+) {
+ const rawLinks = detachPullRequests(json);
+ const snapshot = yield* decodeShellSnapshotJson(json);
+ return deferPullRequests(snapshot, rawLinks);
+});
diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts
index 7a3bd4c7525..b7a69b2a515 100644
--- a/packages/client-runtime/src/state/shellReducer.test.ts
+++ b/packages/client-runtime/src/state/shellReducer.test.ts
@@ -1,8 +1,12 @@
-import { ProjectId, ThreadId } from "@t3tools/contracts";
+import { ProjectId, ThreadId, type ThreadPullRequestLink } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
-import { applyShellStreamEvent, mergeShellSnapshotProjects } from "./shellReducer.ts";
+import {
+ applyShellStreamEvent,
+ mergeShellSnapshotProjects,
+ reuseUnchangedThreadShells,
+} from "./shellReducer.ts";
const repositoryIdentity = {
canonicalKey: "github.com/example/repo",
@@ -463,3 +467,39 @@ describe("applyShellStreamEvent", () => {
expect(next).toBe(v2ShellSnapshot);
});
});
+
+describe("reuseUnchangedThreadShells", () => {
+ const link: ThreadPullRequestLink = {
+ host: "github.com",
+ repository: "pingdotgg/t3code",
+ number: 3,
+ url: "https://github.com/pingdotgg/t3code/pull/3",
+ source: "agent",
+ linkedAt: "2026-06-20T00:00:00.000Z",
+ snapshot: null,
+ stack: null,
+ };
+ const linked = { ...v2ThreadShell, pullRequests: [link] };
+ const other = { ...v2ThreadShell, id: ThreadId.make("thread-other"), title: "Other" };
+
+ it("keeps the previous object for an unchanged row, even without its deferred links", () => {
+ const previous = { ...v2ShellSnapshot, threads: [linked, other] };
+ const { pullRequests: _links, ...withoutLinks } = linked;
+ const next = reuseUnchangedThreadShells(previous, {
+ ...v2ShellSnapshot,
+ snapshotSequence: 5,
+ threads: [withoutLinks, { ...other, title: "Renamed" }],
+ });
+ expect(next.snapshotSequence).toBe(5);
+ expect(next.threads[0]).toBe(linked);
+ expect(next.threads[1]).not.toBe(other);
+ expect(next.threads[1]?.title).toBe("Renamed");
+ });
+
+ it("returns the incoming snapshot when no row is unchanged", () => {
+ const incoming = { ...v2ShellSnapshot, threads: [{ ...other, title: "Renamed" }] };
+ expect(reuseUnchangedThreadShells({ ...v2ShellSnapshot, threads: [other] }, incoming)).toBe(
+ incoming,
+ );
+ });
+});
diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts
index 331b271d6eb..f99f5e7681a 100644
--- a/packages/client-runtime/src/state/shellReducer.ts
+++ b/packages/client-runtime/src/state/shellReducer.ts
@@ -1,5 +1,6 @@
import {
OrchestrationV2ThreadShell,
+ ThreadPullRequestLink,
type OrchestrationProjectShell,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ShellStreamItem,
@@ -7,6 +8,41 @@ import {
import * as Schema from "effect/Schema";
const sameThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell);
+const sameLinks = Schema.toEquivalence(Schema.UndefinedOr(Schema.Array(ThreadPullRequestLink)));
+
+/** Whether two rows' pull request links are equal, including both absent. */
+export function sameThreadPullRequests(
+ left: OrchestrationV2ThreadShell["pullRequests"],
+ right: OrchestrationV2ThreadShell["pullRequests"],
+): boolean {
+ return left === right || sameLinks(left, right);
+}
+
+/**
+ * Keep the previous object for each row a full snapshot left unchanged, so the list only
+ * re-renders rows that changed. Links are compared apart from the rest of the row because a
+ * deferred snapshot arrives without them; such a row keeps its links until they fill in.
+ */
+export function reuseUnchangedThreadShells(
+ previous: OrchestrationV2ShellSnapshot | null,
+ next: OrchestrationV2ShellSnapshot,
+): OrchestrationV2ShellSnapshot {
+ if (previous === null || previous.threads.length === 0) return next;
+ const previousById = new Map(previous.threads.map((thread) => [thread.id, thread] as const));
+ let reused = 0;
+ const threads = next.threads.map((thread) => {
+ const prior = previousById.get(thread.id);
+ if (prior === undefined) return thread;
+ const candidate =
+ thread.pullRequests === undefined && prior.pullRequests !== undefined
+ ? { ...thread, pullRequests: prior.pullRequests }
+ : thread;
+ if (!sameThreadShell(prior, candidate)) return thread;
+ reused += 1;
+ return prior;
+ });
+ return reused === 0 ? next : { ...next, threads };
+}
function upsertById<T extends { readonly id: unknown }>(
items: ReadonlyArray<T>,
diff --git a/packages/client-runtime/src/state/shellSnapshotHttp.ts b/packages/client-runtime/src/state/shellSnapshotHttp.ts
index c4154e009c7..14e57be1fa6 100644
--- a/packages/client-runtime/src/state/shellSnapshotHttp.ts
+++ b/packages/client-runtime/src/state/shellSnapshotHttp.ts
@@ -1,10 +1,11 @@
-import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
+import { EnvironmentHttpCommonError } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
-import { HttpClient } from "effect/http";
+import * as Schema from "effect/Schema";
+import { HttpClient, HttpClientError, type HttpClientResponse } from "effect/http";
import * as RemoteEnvironmentAuthorization from "../authorization/service.ts";
import type { PreparedConnection } from "../connection/model.ts";
@@ -14,6 +15,10 @@ import {
executeAuthenticatedEnvironmentHttpRequest,
withOrchestrationProtocolHeader,
} from "./environmentHttpAuth.ts";
+import {
+ decodeShellSnapshotDeferringPullRequests,
+ type DeferredShellSnapshot,
+} from "./shellPullRequests.ts";
// Long enough for a slow but alive server to finish. On timeout the socket asks
// the same server for the same full snapshot, so a short deadline only throws
@@ -45,11 +50,45 @@ export const fetchEnvironmentShellSnapshot = Effect.fn(
method: "GET",
url: (httpBaseUrl) => environmentEndpointUrl(httpBaseUrl, "/api/orchestration/shell"),
timeoutMs: input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,
+ // The body is decoded here so each thread's pull request links can decode after its
+ // rows. Every declared error is an `EnvironmentHttpCommonError`, so decoding one keeps
+ // the error the credential retry checks for.
request: ({ client, headers }) =>
- client.shellSnapshot({ headers: withOrchestrationProtocolHeader(headers) }),
+ client
+ .shellSnapshot({
+ headers: withOrchestrationProtocolHeader(headers),
+ responseMode: "response-only",
+ })
+ .pipe(Effect.flatMap(decodeShellSnapshotResponse)),
});
});
+const decodeEnvironmentHttpCommonError = Schema.decodeUnknownEffect(
+ Schema.toCodecJson(EnvironmentHttpCommonError),
+);
+
+const decodeShellSnapshotResponse = (
+ response: HttpClientResponse.HttpClientResponse,
+): Effect.Effect<
+ DeferredShellSnapshot,
+ HttpClientError.HttpClientError | Schema.SchemaError | EnvironmentHttpCommonError
+> => {
+ if (response.status === 200) {
+ return response.json.pipe(Effect.flatMap(decodeShellSnapshotDeferringPullRequests));
+ }
+ // A body that is not a declared error keeps its status, as the generated decoder reported.
+ const statusError = new HttpClientError.HttpClientError({
+ reason: new HttpClientError.StatusCodeError({ request: response.request, response }),
+ });
+ return response.json.pipe(
+ Effect.flatMap(decodeEnvironmentHttpCommonError),
+ Effect.matchEffect({
+ onFailure: () => Effect.fail(statusError),
+ onSuccess: Effect.fail,
+ }),
+ );
+};
+
/**
* Loads the environment shell snapshot over HTTP, returning `Option.none()` when
* it cannot be loaded (so the caller falls back to the socket-embedded snapshot).
@@ -61,7 +100,7 @@ export class ShellSnapshotLoader extends Context.Service<
{
readonly load: (
prepared: PreparedConnection,
- ) => Effect.Effect<Option.Option<OrchestrationV2ShellSnapshot>>;
+ ) => Effect.Effect<Option.Option<DeferredShellSnapshot>>;
}
>()("@t3tools/client-runtime/state/shellSnapshotHttp/ShellSnapshotLoader") {}
@@ -78,14 +117,14 @@ export const layer: Layer.Layer<ShellSnapshotLoader, never, HttpClient.HttpClien
return ShellSnapshotLoader.of({
load: (prepared: PreparedConnection) =>
fetchEnvironmentShellSnapshot({ prepared, signer, remoteAuthorization }).pipe(
- Effect.map(Option.some<OrchestrationV2ShellSnapshot>),
+ Effect.map(Option.some<DeferredShellSnapshot>),
Effect.provideService(HttpClient.HttpClient, httpClient),
Effect.catchCause((cause) =>
Effect.logWarning(
"Could not load the environment shell snapshot over HTTP; using the socket snapshot instead.",
).pipe(
Effect.annotateLogs({ cause: Cause.pretty(cause) }),
- Effect.as(Option.none<OrchestrationV2ShellSnapshot>()),
+ Effect.as(Option.none<DeferredShellSnapshot>()),
),
),
),