TypeScript
perf(client): skip unchanged shell and config cache writes (#24266)
Julius Marminge17dc1afa1598
diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.tsindex 931884a92c1..09b28c539d3 100644--- a/packages/client-runtime/src/state/server.test.ts+++ b/packages/client-runtime/src/state/server.test.ts@@ -1,5 +1,8 @@import {EnvironmentId,+ ServerObservability,+ EnvironmentThemeId,+ UsageLimitSourceId,type ServerConfig,type ServerConfigStreamEvent,type ServerLifecycleWelcomePayload,@@ -15,8 +18,10 @@ import * as Fiber from "effect/Fiber";import * as Option from "effect/Option";import * as Queue from "effect/Queue";import * as Ref from "effect/Ref";+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 { RpcClientError } from "effect/rpc";import * as Socket from "effect/socket/Socket";@@ -207,7 +212,260 @@ describe("update restart reconnect nudges", () => {);});+const makeConfigPersistenceHarness = Effect.fn("test.makeConfigPersistenceHarness")(function* (+ saveServerConfig: Persistence.EnvironmentCacheStore["Service"]["saveServerConfig"],+) {+ const events = yield* Queue.unbounded<ServerConfigStreamEvent>();+ const client = {+ [WS_METHODS.subscribeServerConfig]: () => 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.none<PreparedConnection>()),+ connect: Effect.void,+ disconnect: Effect.void,+ retryNow: Effect.void,+ });+ const cache = Persistence.EnvironmentCacheStore.of({+ loadShell: () => Effect.succeedNone,+ saveShell: () => Effect.void,+ loadThread: () => Effect.succeedNone,+ saveThread: () => Effect.void,+ removeThread: () => Effect.void,+ loadServerConfig: () => Effect.succeedSome(CONFIG),+ saveServerConfig,+ loadVcsRefs: () => Effect.succeedNone,+ saveVcsRefs: () => Effect.void,+ removeVcsRefs: () => Effect.void,+ clearVcsRefs: () => Effect.void,+ clear: () => Effect.void,+ });+ const state = yield* makeEnvironmentServerConfigState({+ environmentThemes: true,+ usageLimitSources: true,+ }).pipe(+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),+ );+ const send = Effect.fn("test.sendConfigEvent")(function* (event: ServerConfigStreamEvent) {+ yield* Queue.offer(events, event);+ return yield* SubscriptionRef.changes(state).pipe(+ Stream.filter(Option.isSome),+ Stream.map((value) => value.value),+ Stream.filter((projection) => projection.latestEvent === event),+ Stream.runHead,+ Effect.map(Option.getOrThrow),+ );+ });+ return { send };+});+describe("server state projection", () => {+ it.effect("skips duplicate keybinding saves but persists changed keybindings", () =>+ Effect.gen(function* () {+ const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);+ const keybindingsEvent = (key: string): ServerConfigStreamEvent => ({+ version: 1,+ type: "keybindingsUpdated",+ payload: {+ keybindings: [+ {+ command: "terminal.toggle",+ shortcut: {+ key,+ metaKey: false,+ ctrlKey: false,+ shiftKey: false,+ altKey: false,+ modKey: true,+ },+ },+ ],+ issues: [],+ },+ });+ yield* Effect.scoped(+ Effect.gen(function* () {+ const h = yield* makeConfigPersistenceHarness((_id, config) =>+ Ref.update(saved, (values) => [...values, config]),+ );+ const first = yield* h.send(keybindingsEvent("p"));+ yield* TestClock.adjust("500 millis");+ expect(yield* Ref.get(saved)).toEqual([first.config]);++ yield* h.send(keybindingsEvent("p"));+ yield* TestClock.adjust("10 seconds");+ expect(yield* Ref.get(saved)).toEqual([first.config]);++ const changed = yield* h.send(keybindingsEvent("q"));+ yield* TestClock.adjust("10 seconds");+ expect(yield* Ref.get(saved)).toEqual([first.config, changed.config]);+ }),+ );+ }),+ );++ it.effect(+ "compares nested durable values independently of key order and omitted undefined fields",+ () =>+ Effect.gen(function* () {+ const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);+ const observability = {+ logsDirectoryPath: "/synthetic/logs",+ localTracingEnabled: false,+ otlpTracesEnabled: false,+ otlpMetricsEnabled: false,+ otlpLogsEnabled: false,+ };+ yield* Effect.scoped(+ Effect.gen(function* () {+ const h = yield* makeConfigPersistenceHarness((_id, config) =>+ Ref.update(saved, (values) => [...values, config]),+ );+ const first = yield* h.send(snapshotEvent({ ...CONFIG, observability }));+ yield* TestClock.adjust("500 millis");+ const reordered = Object.fromEntries(+ Object.entries(observability).toReversed(),+ ) as typeof observability;+ for (const next of [+ { ...CONFIG, observability: reordered },+ { ...CONFIG, observability: { ...reordered, otlpTracesUrl: undefined } },+ { ...CONFIG, observability: { ...observability } },+ ]) {+ const encode = Schema.encodeEffect(Schema.fromJsonString(ServerObservability));+ expect(JSON.parse(yield* encode(next.observability))).toEqual(+ JSON.parse(yield* encode(observability)),+ );+ const projection = yield* h.send(snapshotEvent(next));+ expect(projection.config.observability).toEqual(next.observability);+ yield* TestClock.adjust("10 seconds");+ expect.soft(yield* Ref.get(saved)).toEqual([first.config]);+ }+ const writesBeforeChange = (yield* Ref.get(saved)).length;+ const changed = yield* h.send(+ snapshotEvent({+ ...CONFIG,+ observability: { ...observability, otlpTracesUrl: "https://traces.example.test" },+ }),+ );+ yield* TestClock.adjust("10 seconds");+ expect((yield* Ref.get(saved)).length).toBe(writesBeforeChange + 1);+ expect((yield* Ref.get(saved)).at(-1)).toEqual(changed.config);+ }),+ );+ }),+ );++ it.effect("saves once across transient themes, usage sources and stall updates", () =>+ Effect.gen(function* () {+ const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);+ yield* Effect.scoped(+ Effect.gen(function* () {+ const h = yield* makeConfigPersistenceHarness((_id, config) =>+ Ref.update(saved, (values) => [...values, config]),+ );+ yield* h.send(snapshotEvent(CONFIG));+ yield* TestClock.adjust("500 millis");+ expect((yield* Ref.get(saved)).length).toBe(1);+ for (const event of [+ {+ version: 1,+ type: "environmentThemesUpdated",+ payload: {+ themes: [+ {+ id: EnvironmentThemeId.make("theme-test"),+ name: "Test theme",+ appearance: "dark",+ },+ ],+ },+ },+ {+ version: 1,+ type: "usageLimitSourcesUpdated",+ payload: {+ sources: [+ {+ id: UsageLimitSourceId.make("source-test"),+ kind: "cliproxy",+ label: "Test source",+ checkedAt: "2026-10-20T07:50:37.633Z",+ accounts: [],+ },+ ],+ },+ },+ snapshotEvent({+ ...CONFIG,+ lastEventLoopStall: {+ detectedAt: "2026-10-20T07:50:37.633Z",+ durationMs: 1000,+ loadAverage: 1,+ cpuCount: 8,+ },+ }),+ ] satisfies ReadonlyArray<ServerConfigStreamEvent>) {+ const projection = yield* h.send(event);+ expect(projection.latestEvent).toBe(event);+ if (event.type === "environmentThemesUpdated")+ expect(projection.config.environmentThemes).toEqual(event.payload.themes);+ if (event.type === "usageLimitSourcesUpdated")+ expect(projection.config.usageLimitSources).toEqual(event.payload.sources);+ yield* TestClock.adjust("10 seconds");+ }+ }),+ );+ expect(yield* Ref.get(saved)).toEqual([CONFIG]);+ }),+ );++ it.effect("flushes pending durable changes after a transient event", () =>+ Effect.gen(function* () {+ const saved = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);+ const changed = { ...CONFIG, keybindingsConfigPath: "/changed/keybindings.json" };+ yield* Effect.scoped(+ Effect.gen(function* () {+ const h = yield* makeConfigPersistenceHarness((_id, config) =>+ Ref.update(saved, (values) => [...values, config]),+ );+ yield* h.send(snapshotEvent(CONFIG));+ yield* TestClock.adjust("500 millis");+ yield* h.send(snapshotEvent(changed));+ yield* h.send({ version: 1, type: "environmentThemesUpdated", payload: { themes: [] } });+ }),+ );+ expect(yield* Ref.get(saved)).toEqual([CONFIG, changed]);+ }),+ );++ it.effect("retries a failed durable save on a transient event", () =>+ Effect.gen(function* () {+ const attempts = yield* Ref.make<ReadonlyArray<ServerConfig>>([]);+ yield* Effect.scoped(+ Effect.gen(function* () {+ const h = yield* makeConfigPersistenceHarness((_id, config) =>+ Effect.gen(function* () {+ const values = yield* Ref.updateAndGet(attempts, (values) => [...values, config]);+ if (values.length === 1)+ return yield* new Persistence.ConnectionPersistenceError({+ operation: "save-server-config",+ message: "test failure",+ });+ }),+ );+ yield* h.send(snapshotEvent(CONFIG));+ yield* TestClock.adjust("500 millis");+ yield* h.send({ version: 1, type: "usageLimitSourcesUpdated", payload: { sources: [] } });+ yield* TestClock.adjust("10 seconds");+ }),+ );+ expect(yield* Ref.get(attempts)).toEqual([CONFIG, CONFIG]);+ }),+ );+it("only treats a legacy transport interruption as an unacknowledged handoff", () => {expect(isLegacyUpdateHandoffLoss(Cause.interrupt(1))).toBe(true);expect(diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex 77c5beb61a4..7913f8fe84e 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -358,6 +358,41 @@ export interface ServerConfigSubscriptionOptions {readonly usageLimitsCommand?: boolean;}+// Configs are JSON-shaped. Missing and undefined object fields persist identically.+function sameCacheValue(previous: unknown, next: unknown): boolean {+ if (previous === next) return true;+ if (+ previous === null ||+ next === null ||+ typeof previous !== "object" ||+ typeof next !== "object"+ ) {+ return false;+ }+ if (Array.isArray(previous) || Array.isArray(next)) {+ if (!Array.isArray(previous) || !Array.isArray(next) || previous.length !== next.length) {+ return false;+ }+ for (let index = 0; index < previous.length; index += 1) {+ if (!sameCacheValue(previous[index], next[index])) return false;+ }+ return true;+ }+ if (+ Object.getPrototypeOf(previous) !== Object.prototype ||+ Object.getPrototypeOf(next) !== Object.prototype+ ) {+ return false;+ }+ const before = previous as Record<string, unknown>;+ const after = next as Record<string, unknown>;+ return (+ Object.keys(before).every((key) =>+ sameCacheValue(before[key], Object.hasOwn(after, key) ? after[key] : undefined),+ ) && Object.keys(after).every((key) => Object.hasOwn(before, key) || after[key] === undefined)+ );+}+export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConfigState.make")(function* (subscription: ServerConfigSubscriptionOptions) {const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;@@ -383,13 +418,22 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf);const persistence = yield* Queue.sliding<ServerConfig>(1);const pendingPersistence = yield* Ref.make<Option.Option<ServerConfig>>(Option.none());+ let lastPersisted: ServerConfig | undefined;const persist = Effect.fn("EnvironmentServerConfigState.persist")(function* (config: ServerConfig,) {// A cached stall would read as a fresh freeze on the next launch.- const { lastEventLoopStall: _stall, ...cacheable } = withoutEnvironmentThemes(config);- return yield* cache.saveServerConfig(environmentId, cacheable).pipe(+ const {+ environmentThemes: _themes,+ usageLimitSources: _sources,+ lastEventLoopStall: _stall,+ ...cacheable+ } = config;+ if (lastPersisted !== undefined && sameCacheValue(lastPersisted, cacheable)) {+ return true;+ }+ const saved = yield* cache.saveServerConfig(environmentId, cacheable).pipe(Effect.as(true),Effect.catch((error) =>Effect.logWarning("Could not persist cached server configuration.").pipe(@@ -401,6 +445,8 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf),),);+ if (saved) lastPersisted = cacheable;+ return saved;});const persistPending = Effect.fn("EnvironmentServerConfigState.persistPending")(function* (diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.tsindex 0e76e321bf3..56476f580b4 100644--- a/packages/client-runtime/src/state/shell-sync.test.ts+++ b/packages/client-runtime/src/state/shell-sync.test.ts@@ -17,6 +17,7 @@ import * as Ref from "effect/Ref";import * as Scope from "effect/Scope";import * as Stream from "effect/Stream";import * as SubscriptionRef from "effect/SubscriptionRef";+import * as TestClock from "effect/testing/TestClock";import {AVAILABLE_CONNECTION_STATE,@@ -63,7 +64,156 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession {};}+const makePersistenceHarness = Effect.fn("test.makeShellPersistenceHarness")(function* (+ saveShell: Persistence.EnvironmentCacheStore["Service"]["saveShell"],+) {+ 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,+ });+ const cache = Persistence.EnvironmentCacheStore.of({+ loadShell: () => Effect.succeedNone,+ saveShell,+ 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 state = yield* makeEnvironmentShellState().pipe(+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),+ Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, {+ load: () => Effect.succeedNone,+ }),+ );+ const send = Effect.fn("test.sendShellItem")(function* (+ item: OrchestrationV2ShellStreamItem,+ ready: (snapshot: OrchestrationV2ShellSnapshot) => boolean,+ ) {+ const previous = yield* SubscriptionRef.get(state);+ yield* Queue.offer(events, item);+ return yield* SubscriptionRef.changes(state).pipe(+ Stream.filter((value) => value !== previous),+ Stream.map((value) => value.snapshot),+ Stream.filter(Option.isSome),+ Stream.map((value) => value.value),+ Stream.filter(ready),+ Stream.runHead,+ Effect.map(Option.getOrThrow),+ );+ });+ yield* send({ kind: "snapshot", snapshot: LIVE_SHELL_SNAPSHOT }, () => true);+ return { state, send };+});+describe("environment shell synchronization", () => {+ it.effect("skips unchanged shell writes, persists resets and flushes changed rows", () =>+ Effect.gen(function* () {+ const saved = yield* Ref.make<ReadonlyArray<OrchestrationV2ShellSnapshot>>([]);+ yield* Effect.scoped(+ Effect.gen(function* () {+ const h = yield* makePersistenceHarness((_id, snapshot) =>+ Ref.update(saved, (values) => [...values, snapshot]),+ );+ yield* TestClock.adjust("500 millis");+ yield* h.send(+ { kind: "thread.updated", sequence: 10, location: "active", thread: v2ThreadShell },+ (snapshot) => snapshot.snapshotSequence === 10,+ );+ yield* TestClock.adjust("10 seconds");+ expect((yield* Ref.get(saved)).map((snapshot) => snapshot.snapshotSequence)).toEqual([1]);+ const live = Option.getOrThrow((yield* SubscriptionRef.get(h.state)).snapshot);+ expect(live.snapshotSequence).toBe(10);+ const enriched = yield* h.send(+ {+ kind: "snapshot",+ snapshot: { ...live, projects: live.projects.map((project) => ({ ...project })) },+ resolvedRepositoryIdentityRoots: live.projects.map(+ (project) => project.workspaceRoot,+ ),+ },+ () => true,+ );+ expect(enriched.projects).toEqual(live.projects);+ expect(enriched.snapshotSequence).toBe(10);+ yield* TestClock.adjust("10 seconds");+ expect((yield* Ref.get(saved)).map((snapshot) => snapshot.snapshotSequence)).toEqual([1]);+ yield* h.send(+ { kind: "snapshot", snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 4 } },+ (snapshot) => snapshot.snapshotSequence === 4,+ );+ yield* TestClock.adjust("10 seconds");+ yield* h.send(+ {+ kind: "snapshot",+ snapshot: {+ ...LIVE_SHELL_SNAPSHOT,+ snapshotSequence: 4,+ projects: [{ ...v2Project, title: "Changed at same sequence" }],+ },+ },+ (snapshot) => snapshot.projects[0]?.title === "Changed at same sequence",+ );+ }),+ );+ expect(+ (yield* Ref.get(saved)).map((snapshot) => [+ snapshot.snapshotSequence,+ snapshot.projects[0]?.title,+ ]),+ ).toEqual([+ [1, v2Project.title],+ [4, v2Project.title],+ [4, "Changed at same sequence"],+ ]);+ }),+ );++ it.effect("retries a failed shell save after a cursor-only update", () =>+ Effect.gen(function* () {+ const attempts = yield* Ref.make<ReadonlyArray<number>>([]);+ yield* Effect.scoped(+ Effect.gen(function* () {+ const h = yield* makePersistenceHarness((_id, snapshot) =>+ Effect.gen(function* () {+ const values = yield* Ref.updateAndGet(attempts, (values) => [+ ...values,+ snapshot.snapshotSequence,+ ]);+ if (values.length === 1)+ return yield* new Persistence.ConnectionPersistenceError({+ operation: "save-shell",+ message: "test failure",+ });+ }),+ );+ yield* TestClock.adjust("500 millis");+ yield* h.send(+ { kind: "thread.updated", sequence: 2, location: "active", thread: v2ThreadShell },+ (snapshot) => snapshot.snapshotSequence === 2,+ );+ yield* TestClock.adjust("10 seconds");+ }),+ );+ expect(yield* Ref.get(attempts)).toEqual([1, 2]);+ }),+ );+it.effect("flushes the latest live snapshot without blocking connection state updates", () =>Effect.gen(function* () {const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.tsindex a01465d2dc7..2c51e3a1a31 100644--- a/packages/client-runtime/src/state/shell.ts+++ b/packages/client-runtime/src/state/shell.ts@@ -125,6 +125,19 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")if (Option.isNone(latest) || latest.value === lastPersisted) return;if (latest.value.threads.some((thread) => pendingLinkRows.has(thread))) return;const snapshot = latest.value;+ if (+ lastPersisted !== undefined &&+ snapshot.snapshotSequence >= lastPersisted.snapshotSequence &&+ snapshot.schemaVersion === lastPersisted.schemaVersion &&+ snapshot.projects === lastPersisted.projects &&+ snapshot.threads === lastPersisted.threads &&+ snapshot.archivedThreads === lastPersisted.archivedThreads+ ) {+ // Keep the live cursor without rewriting the rows. Remember it here too so a+ // later authoritative reset to a lower sequence still reaches the cache.+ lastPersisted = snapshot;+ return;+ }const saved = yield* cache.saveShell(environmentId, snapshot).pipe(Effect.as(true),Effect.catch((error) =>diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.tsindex eec7f6c949f..2d9647e85fc 100644--- a/packages/client-runtime/src/state/shellReducer.ts+++ b/packages/client-runtime/src/state/shellReducer.ts@@ -92,27 +92,27 @@ export function mergeShellSnapshotProjects(if (isEnrichment) {const nextById = new Map(next.projects.map((project) => [project.id, project] as const));- return {- ...previous,- projects: previous.projects.map((project) => {- const candidate = nextById.get(project.id);- if (candidate === undefined || candidate.workspaceRoot !== project.workspaceRoot) {+ const projects = previous.projects.map((project) => {+ const candidate = nextById.get(project.id);+ if (candidate === undefined || candidate.workspaceRoot !== project.workspaceRoot) {+ return project;+ }+ if (resolvedRootSet?.has(project.workspaceRoot) === true) {+ // Refreshes re-resolve every root; an unchanged identity keeps the project's identity+ // so every subscriber (each pull request row, the sidebar) skips re-rendering.+ if (sameRepositoryIdentity(project.repositoryIdentity, candidate.repositoryIdentity)) {return project;}- if (resolvedRootSet?.has(project.workspaceRoot) === true) {- // Refreshes re-resolve every root; an unchanged identity keeps the project's identity- // so every subscriber (each pull request row, the sidebar) skips re-rendering.- if (sameRepositoryIdentity(project.repositoryIdentity, candidate.repositoryIdentity)) {- return project;- }- return { ...project, repositoryIdentity: candidate.repositoryIdentity };- }- if (project.repositoryIdentity == null && candidate.repositoryIdentity != null) {- return { ...project, repositoryIdentity: candidate.repositoryIdentity };- }- return project;- }),- };+ return { ...project, repositoryIdentity: candidate.repositoryIdentity };+ }+ if (project.repositoryIdentity == null && candidate.repositoryIdentity != null) {+ return { ...project, repositoryIdentity: candidate.repositoryIdentity };+ }+ return project;+ });+ return projects.every((project, index) => project === previous.projects[index])+ ? previous+ : { ...previous, projects };}const previousById = new Map(previous.projects.map((project) => [project.id, project] as const));