Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

perf(ws): scope preview frames and drop repeated shell payloads (#298)

Leo0632aa50fcad
diff --git a/.changeset/perf-ws-payloads.md b/.changeset/perf-ws-payloads.md
new file mode 100644
index 000000000..6dab136e1
--- /dev/null
+++ b/.changeset/perf-ws-payloads.md
@@ -0,0 +1,5 @@
+---
+"akeru-bot": patch
+---
+
+Less bandwidth on remote connections: bot browser preview frames now go only to the chat that owns them, unchanged thread updates are no longer re-sent, and opening Settings no longer re-probes every provider.
diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.ts b/apps/server/src/orchestration/ActivityPayloadProjection.ts
index 590d24574..fed3a7dc8 100644
--- a/apps/server/src/orchestration/ActivityPayloadProjection.ts
+++ b/apps/server/src/orchestration/ActivityPayloadProjection.ts
@@ -631,15 +631,28 @@ export function projectThreadDetailSnapshot(
};
}
+// Published events are immutable and shared by every live subscriber. Project
+// each one once so subscribers share the projected object, which also lets the
+// live stream budget reuse its serialized-size measurement.
+const projectedActivityEvents = new WeakMap<OrchestrationEvent, OrchestrationEvent>();
+
export function projectActivityEvent(event: OrchestrationEvent): OrchestrationEvent {
if (event.type !== "thread.activity-appended") {
return event;
}
- return {
+ const cached = projectedActivityEvents.get(event);
+ if (cached !== undefined) {
+ return cached;
+ }
+ const projected: OrchestrationEvent = {
...event,
payload: {
...event.payload,
activity: projectActivityPayload(event.payload.activity),
},
};
+ projectedActivityEvents.set(event, projected);
+ // Mark the result as already projected so a repeat call returns it unchanged.
+ projectedActivityEvents.set(projected, projected);
+ return projected;
}
diff --git a/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts b/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts
index c7f2155b4..05f217510 100644
--- a/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts
+++ b/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts
@@ -130,7 +130,7 @@ export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoales
pendingUpdates,
coalesceLiveToolUpdatedEvents(pendingUpdates.map((item) => item.value)).map((event) => ({
kind: "event" as const,
- event: projectActivityEvent(event),
+ event,
})),
(item) => item.event,
);
@@ -167,7 +167,9 @@ export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoales
Effect.gen(function* () {
yield* budget.check;
if (input.kind === "event") {
- yield* budget.retain(input.event).pipe(
+ // Charge the budget for what the client receives. A large raw
+ // tool result would otherwise count at its full stored size.
+ yield* budget.retain(projectActivityEvent(input.event)).pipe(
Effect.tap((item) => Effect.sync(() => pendingUpdates.push(item))),
Effect.uninterruptible,
);
diff --git a/apps/server/src/preview/Manager.test.ts b/apps/server/src/preview/Manager.test.ts
index 8b3dabfa3..d49f743bd 100644
--- a/apps/server/src/preview/Manager.test.ts
+++ b/apps/server/src/preview/Manager.test.ts
@@ -1,7 +1,7 @@
import { it } from "@effect/vitest";
import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
import { PreviewUrlNormalizationError } from "@t3tools/shared/preview";
-import { Effect, PubSub } from "effect";
+import { Effect, Fiber, PubSub, Stream } from "effect";
import { expect } from "vite-plus/test";
import * as PreviewManager from "./Manager.ts";
@@ -384,4 +384,44 @@ it.layer(PreviewManager.layer)("PreviewManager", (it) => {
expect(bEvents.map((e) => e.type)).toEqual(["opened", "opened"]);
}),
);
+
+ it.effect("scopes streamed events and frames to the subscribed chat", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const threadA = freshThreadId();
+ const threadB = freshThreadId();
+ const manager = yield* PreviewManager.PreviewManager;
+ // startImmediately runs each consumer up to its PubSub subscription
+ // before anything below publishes.
+ const scopedFiber = yield* manager
+ .streamEvents({ threadId: threadA })
+ .pipe(Stream.take(3), Stream.runCollect, Effect.forkScoped({ startImmediately: true }));
+ const unscopedFiber = yield* manager
+ .streamEvents({})
+ .pipe(Stream.take(5), Stream.runCollect, Effect.forkScoped({ startImmediately: true }));
+
+ const tabA = yield* manager.open({ threadId: threadA });
+ const tabB = yield* manager.open({ threadId: threadB });
+ const frame = { mimeType: "image/png" as const, data: "AAAA", width: 1, height: 1 };
+ yield* manager.reportFrame({ threadId: threadB, tabId: tabB.tabId, frame });
+ yield* manager.reportFrame({ threadId: threadA, tabId: tabA.tabId, frame });
+ yield* manager.close({ threadId: threadA });
+
+ const scoped = yield* Fiber.join(scopedFiber);
+ expect(scoped.map((event) => [event.threadId, event.type])).toEqual([
+ [threadA, "opened"],
+ [threadA, "frame"],
+ [threadA, "closed"],
+ ]);
+ const unscoped = yield* Fiber.join(unscopedFiber);
+ expect(unscoped.map((event) => event.threadId)).toEqual([
+ threadA,
+ threadB,
+ threadB,
+ threadA,
+ threadA,
+ ]);
+ }),
+ ),
+ );
});
diff --git a/apps/server/src/preview/Manager.ts b/apps/server/src/preview/Manager.ts
index dc4905636..2f51801b9 100644
--- a/apps/server/src/preview/Manager.ts
+++ b/apps/server/src/preview/Manager.ts
@@ -12,6 +12,7 @@
import {
type PreviewCloseInput,
type PreviewEvent,
+ type PreviewEventsSubscribeInput,
type PreviewError,
type PreviewFrame,
PreviewInvalidUrlError,
@@ -61,11 +62,21 @@ export class PreviewManager extends Context.Service<
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
- readonly events: Stream.Stream<PreviewEvent>;
+ /** Live events, filtered to one chat when the subscriber names it. */
+ readonly streamEvents: (input: PreviewEventsSubscribeInput) => Stream.Stream<PreviewEvent>;
readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
}
>()("akeru-bot/preview/Manager/PreviewManager") {}
+/**
+ * Frame events carry a full-viewport PNG, so a subscriber scoped to one chat
+ * must never receive another chat's frames. Filter before RPC serialization.
+ */
+export const previewEventMatchesSubscription =
+ (input: PreviewEventsSubscribeInput) =>
+ (event: PreviewEvent): boolean =>
+ input.threadId === undefined || event.threadId === input.threadId;
+
interface PreviewSessionState {
readonly threadId: string;
readonly tabId: string;
@@ -158,11 +169,13 @@ const buildIdleSnapshot = (input: {
export const make = Effect.gen(function* PreviewManagerMake() {
const serverEpoch = NodeCrypto.randomUUID();
const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
- // Unbounded PubSub is fine here — events are tiny and we don't want to
- // block publishers if a subscriber is slow. WS clients backpressure on
- // their own queues downstream.
+ // Unbounded so a slow subscriber never blocks publishers or loses a
+ // lifecycle event. Frame events are not tiny (base64 PNGs): a subscriber
+ // that stops pulling retains every event published in the meantime, and
+ // its chat filter runs only as it pulls.
const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
- const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
+ const streamEvents: PreviewManager["Service"]["streamEvents"] = (input) =>
+ Stream.fromPubSub(eventsPubSub).pipe(Stream.filter(previewEventMatchesSubscription(input)));
/**
* Atomic read-modify-write over the session for `(threadId, tabId)`. The
@@ -464,7 +477,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
refresh,
close,
list,
- events,
+ streamEvents,
subscribeEvents: PubSub.subscribe(eventsPubSub),
});
}).pipe(Effect.withSpan("PreviewManager.make"));
diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts
index eee537090..541337a0e 100644
--- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts
+++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
+import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
@@ -563,6 +564,29 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
});
+ it("ignores checkedAt when deciding whether providers changed", () => {
+ const provider = {
+ instanceId: ProviderInstanceId.make("claudeAgent"),
+ driver: ProviderDriverKind.make("claudeAgent"),
+ status: "ready",
+ enabled: true,
+ installed: true,
+ auth: { status: "authenticated" },
+ checkedAt: "2026-03-25T00:00:00.000Z",
+ version: "1.0.0",
+ models: [],
+ slashCommands: [],
+ skills: [],
+ } as const satisfies ServerProvider;
+ const rechecked = { ...provider, checkedAt: "2026-03-25T00:05:00.000Z" };
+
+ assert.strictEqual(haveProvidersChanged([provider], [rechecked]), false);
+ assert.strictEqual(
+ haveProvidersChanged([provider], [{ ...rechecked, status: "warning" }]),
+ true,
+ );
+ });
+
it("preserves previously discovered provider models when a refresh returns none", () => {
const previousProvider = {
instanceId: ProviderInstanceId.make("cursor"),
@@ -1025,6 +1049,107 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
}),
);
+ it.effect("publishes a completed probe that only moved checkedAt", () =>
+ Effect.gen(function* () {
+ const claudeDriver = ProviderDriverKind.make("claudeAgent");
+ const claudeInstanceId = ProviderInstanceId.make("claudeAgent");
+ const initialProvider = {
+ instanceId: claudeInstanceId,
+ driver: claudeDriver,
+ status: "ready",
+ enabled: true,
+ installed: true,
+ auth: { status: "authenticated" },
+ checkedAt: "2026-04-14T00:00:00.000Z",
+ version: "1.0.0",
+ models: [],
+ slashCommands: [],
+ skills: [],
+ } as const satisfies ServerProvider;
+ const reprobedProvider = {
+ ...initialProvider,
+ checkedAt: "2026-04-14T00:05:00.000Z",
+ } satisfies ServerProvider;
+ const changes = yield* PubSub.unbounded<ServerProvider>();
+ const instance = {
+ instanceId: claudeInstanceId,
+ driverKind: claudeDriver,
+ continuationIdentity: {
+ driverKind: claudeDriver,
+ continuationKey: "claudeAgent:instance:claudeAgent",
+ },
+ displayName: undefined,
+ enabled: true,
+ snapshot: {
+ maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
+ provider: claudeDriver,
+ packageName: null,
+ }),
+ getSnapshot: Effect.succeed(initialProvider),
+ refresh: Effect.succeed(reprobedProvider),
+ streamChanges: Stream.fromPubSub(changes),
+ },
+ adapter: {} as ProviderInstance["adapter"],
+ textGeneration: {} as ProviderInstance["textGeneration"],
+ } satisfies ProviderInstance;
+ const instanceRegistryLayer = Layer.succeed(
+ ProviderInstanceRegistry.ProviderInstanceRegistry,
+ {
+ getInstance: (instanceId) =>
+ Effect.succeed(instanceId === claudeInstanceId ? instance : undefined),
+ dispatchIfEnabled: (instanceId, dispatch) =>
+ Effect.sync(() =>
+ instanceId === claudeInstanceId
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
+ listInstances: Effect.succeed([instance]),
+ listUnavailable: Effect.succeed([]),
+ streamChanges: Stream.empty,
+ subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
+ PubSub.subscribe(pubsub),
+ ),
+ },
+ );
+ const scope = yield* Scope.make();
+ yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
+ const runtimeServices = yield* Layer.build(
+ ProviderRegistryLive.pipe(
+ Layer.provideMerge(instanceRegistryLayer),
+ Layer.provideMerge(
+ ServerConfig.layerTest(process.cwd(), {
+ prefix: "t3-provider-registry-checked-at-publish-",
+ }),
+ ),
+ Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
+ Layer.provideMerge(NodeServices.layer),
+ ),
+ ).pipe(Scope.provide(scope));
+
+ yield* Effect.gen(function* () {
+ const registry = yield* ProviderRegistry.ProviderRegistry;
+ const published = yield* registry.streamChanges.pipe(
+ Stream.take(1),
+ Stream.runCollect,
+ Effect.forkScoped({ startImmediately: true }),
+ );
+
+ // The status change is always published, so the first broadcast
+ // shows whether the checkedAt-only probe went out before it.
+ yield* PubSub.publish(changes, reprobedProvider);
+ yield* PubSub.publish(changes, {
+ ...reprobedProvider,
+ checkedAt: "2026-04-14T00:10:00.000Z",
+ status: "warning",
+ });
+
+ const [providers] = yield* Fiber.join(published);
+ assert.strictEqual(providers?.[0]?.checkedAt, reprobedProvider.checkedAt);
+ assert.strictEqual(providers?.[0]?.status, "ready");
+ }).pipe(Effect.provide(runtimeServices), Effect.scoped);
+ }),
+ );
+
it.effect(
"persists authoritative OpenCode removals without resurrecting them on a failed live refresh",
() =>
@@ -1253,6 +1378,154 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
}),
);
+ it.effect("keeps the newest provider result across refreshes and the change stream", () =>
+ Effect.gen(function* () {
+ const codexDriver = ProviderDriverKind.make("codex");
+ const codexInstanceId = ProviderInstanceId.make("codex");
+ yield* TestClock.setTime(Date.parse("2026-04-29T11:00:00.000Z"));
+ const makeProvider = (checkedAt: string, version: string): ServerProvider =>
+ ({
+ instanceId: codexInstanceId,
+ driver: codexDriver,
+ status: "ready",
+ enabled: true,
+ installed: true,
+ auth: { status: "authenticated" },
+ checkedAt,
+ version,
+ models: [],
+ slashCommands: [],
+ skills: [],
+ }) as const satisfies ServerProvider;
+ const cachedProvider = makeProvider("2026-04-29T10:00:00.000Z", "1.0.0");
+ const olderProvider = makeProvider("2026-04-29T10:01:00.000Z", "1.0.1");
+ const newerProvider = makeProvider("2026-04-29T10:02:00.000Z", "1.0.2");
+ const probes = [
+ {
+ started: yield* Deferred.make<void>(),
+ release: yield* Deferred.make<void>(),
+ result: olderProvider,
+ },
+ {
+ started: yield* Deferred.make<void>(),
+ release: yield* Deferred.make<void>(),
+ result: newerProvider,
+ },
+ ] as const;
+ const probeCount = yield* Ref.make(0);
+ const changes = yield* PubSub.unbounded<ServerProvider>();
+ const instance = {
+ instanceId: codexInstanceId,
+ driverKind: codexDriver,
+ continuationIdentity: {
+ driverKind: codexDriver,
+ continuationKey: "codex:instance:codex",
+ },
+ displayName: undefined,
+ enabled: true,
+ snapshot: {
+ maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
+ provider: codexDriver,
+ packageName: null,
+ }),
+ getSnapshot: Effect.succeed(cachedProvider),
+ refresh: Effect.gen(function* () {
+ const probe = probes[yield* Ref.getAndUpdate(probeCount, (count) => count + 1)]!;
+ yield* Deferred.succeed(probe.started, undefined);
+ yield* Deferred.await(probe.release);
+ return probe.result;
+ }),
+ streamChanges: Stream.fromPubSub(changes),
+ },
+ adapter: {} as ProviderInstance["adapter"],
+ textGeneration: {} as ProviderInstance["textGeneration"],
+ } satisfies ProviderInstance;
+ const instanceRegistryLayer = Layer.succeed(
+ ProviderInstanceRegistry.ProviderInstanceRegistry,
+ {
+ getInstance: (instanceId) =>
+ Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
+ dispatchIfEnabled: (instanceId, dispatch) =>
+ Effect.sync(() =>
+ instanceId === codexInstanceId
+ ? ({ _tag: "Dispatched", value: dispatch() } as const)
+ : ({ _tag: "Missing" } as const),
+ ),
+ listInstances: Effect.succeed([instance]),
+ listUnavailable: Effect.succeed([]),
+ streamChanges: Stream.empty,
+ subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), (pubsub) =>
+ PubSub.subscribe(pubsub),
+ ),
+ },
+ );
+ const scope = yield* Scope.make();
+ yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
+ const runtimeServices = yield* Layer.build(
+ ProviderRegistryLive.pipe(
+ Layer.provideMerge(instanceRegistryLayer),
+ Layer.provideMerge(
+ ServerConfig.layerTest(process.cwd(), {
+ prefix: "t3-provider-registry-probe-order-",
+ }),
+ ),
+ Layer.provideMerge(BackgroundPolicyAlwaysRunLayer),
+ Layer.provideMerge(NodeServices.layer),
+ ),
+ ).pipe(Scope.provide(scope));
+
+ yield* Effect.gen(function* () {
+ const registry = yield* ProviderRegistry.ProviderRegistry;
+
+ // The background probe starts first, then the explicit refresh.
+ const olderProbe = yield* registry
+ .refreshInstance(codexInstanceId)
+ .pipe(Effect.forkScoped);
+ yield* Deferred.await(probes[0].started);
+ const newerProbe = yield* registry
+ .refreshInstance(codexInstanceId)
+ .pipe(Effect.forkScoped);
+ yield* Deferred.await(probes[1].started);
+
+ yield* Deferred.succeed(probes[1].release, undefined);
+ assert.deepStrictEqual(yield* Fiber.join(newerProbe), [newerProvider]);
+
+ yield* Deferred.succeed(probes[0].release, undefined);
+ assert.deepStrictEqual(yield* Fiber.join(olderProbe), [newerProvider]);
+ assert.deepStrictEqual(yield* registry.getProviders, [newerProvider]);
+
+ // A stale result delivered late on the change stream is dropped,
+ // while a newer status change still lands. Stream items apply in
+ // order, so the first broadcast shows whether the stale one landed.
+ const signedOutProvider: ServerProvider = {
+ ...newerProvider,
+ checkedAt: "2026-04-29T10:03:00.000Z",
+ status: "warning",
+ auth: { status: "unauthenticated" },
+ };
+ const afterSignOut = yield* registry.streamChanges.pipe(
+ Stream.take(1),
+ Stream.runCollect,
+ Effect.forkScoped({ startImmediately: true }),
+ );
+ yield* PubSub.publish(changes, olderProvider);
+ yield* PubSub.publish(changes, signedOutProvider);
+ assert.deepStrictEqual(yield* Fiber.join(afterSignOut), [[signedOutProvider]]);
+
+ // If the clock moved back, a stored result from the "future" does
+ // not block new results.
+ yield* TestClock.setTime(Date.parse("2026-04-29T09:00:00.000Z"));
+ const afterClockReset = yield* registry.streamChanges.pipe(
+ Stream.take(1),
+ Stream.runCollect,
+ Effect.forkScoped({ startImmediately: true }),
+ );
+ yield* PubSub.publish(changes, olderProvider);
+ assert.deepStrictEqual(yield* Fiber.join(afterClockReset), [[olderProvider]]);
+ }).pipe(Effect.provide(runtimeServices), Effect.scoped);
+ }),
+ );
+
it.effect("keeps consuming registry changes after one sync fails", () =>
Effect.gen(function* () {
const codexDriver = ProviderDriverKind.make("codex");
diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts
index 760c8e1c5..ae44e85c9 100644
--- a/apps/server/src/provider/Layers/ProviderRegistry.ts
+++ b/apps/server/src/provider/Layers/ProviderRegistry.ts
@@ -30,6 +30,7 @@ import {
type ServerProviderUpdateState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
+import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
import * as FileSystem from "effect/FileSystem";
@@ -158,10 +159,20 @@ export const selectProvidersByKind = (
): ReadonlyArray<ServerProvider> =>
providers.filter((provider) => providerKinds.has(provider.driver));
+const withoutCheckedAt = (providers: ReadonlyArray<ServerProvider>) =>
+ providers.map(({ checkedAt: _checkedAt, ...provider }) => provider);
+
+/**
+ * Every probe stamps a fresh `checkedAt`, so comparing it would make each
+ * background re-probe look like a change. Only the remaining fields decide
+ * whether clients need a new provider list.
+ */
export const haveProvidersChanged = (
previousProviders: ReadonlyArray<ServerProvider>,
nextProviders: ReadonlyArray<ServerProvider>,
-): boolean => !Equal.equals(previousProviders, nextProviders);
+): boolean =>
+ previousProviders.length !== nextProviders.length ||
+ !Equal.equals(withoutCheckedAt(previousProviders), withoutCheckedAt(nextProviders));
const correlateSnapshotWithSource = (
source: ProviderSnapshotSource,
@@ -350,6 +361,15 @@ export const ProviderRegistryLive = Layer.effect(
readonly publish?: boolean;
readonly persist?: boolean;
readonly replace?: boolean;
+ /** Treat a moved `checkedAt` as a change. Set for completed probes. */
+ readonly publishCheckedAt?: boolean;
+ /**
+ * Skip a snapshot whose `checkedAt` is older than the stored one. Set
+ * for probe results, which can arrive out of order through an
+ * explicit refresh and the instance's change stream. A stored
+ * `checkedAt` in the future (the clock moved back) never blocks.
+ */
+ readonly keepNewer?: boolean;
},
) {
const nextProvidersWithUpdateState = yield* Effect.forEach(
@@ -359,6 +379,7 @@ export const ProviderRegistryLive = Layer.effect(
concurrency: "unbounded",
},
);
+ const nowMs = options?.keepNewer === true ? yield* Clock.currentTimeMillis : 0;
const [previousProviders, providers, providersToPersist] = yield* Ref.modify(
providersRef,
(previousProviders) => {
@@ -369,12 +390,22 @@ export const ProviderRegistryLive = Layer.effect(
for (const provider of nextProvidersWithUpdateState) {
const key = snapshotInstanceKey(provider);
+ const previousProvider = mergedProviders.get(key);
+ if (options?.keepNewer === true && previousProvider !== undefined) {
+ const previousCheckedAtMs = Date.parse(previousProvider.checkedAt);
+ if (
+ previousCheckedAtMs <= nowMs &&
+ previousCheckedAtMs > Date.parse(provider.checkedAt)
+ ) {
+ continue;
+ }
+ }
updatedKeys.add(key);
mergedProviders.set(
key,
options?.replace === true
? provider
- : mergeProviderSnapshot(mergedProviders.get(key), provider),
+ : mergeProviderSnapshot(previousProvider, provider),
);
}
@@ -386,16 +417,23 @@ export const ProviderRegistryLive = Layer.effect(
},
);
- if (haveProvidersChanged(previousProviders, providers)) {
- if (options?.persist !== false) {
- yield* Effect.forEach(providersToPersist, persistProvider, {
- concurrency: "unbounded",
- discard: true,
- });
- }
- if (options?.publish !== false) {
- yield* PubSub.publish(changesPubSub, providers);
- }
+ // Persist a fresh `checkedAt` so a restart does not treat the cache as
+ // stale. Broadcast it only when a probe actually completed, so Settings
+ // shows the real last-check time while snapshot re-syncs stay quiet.
+ const changedIncludingCheckedAt = !Equal.equals(previousProviders, providers);
+ if (changedIncludingCheckedAt && options?.persist !== false) {
+ yield* Effect.forEach(providersToPersist, persistProvider, {
+ concurrency: "unbounded",
+ discard: true,
+ });
+ }
+ if (
+ options?.publish !== false &&
+ (options?.publishCheckedAt === true
+ ? changedIncludingCheckedAt
+ : haveProvidersChanged(previousProviders, providers))
+ ) {
+ yield* PubSub.publish(changesPubSub, providers);
}
return providers;
@@ -405,6 +443,8 @@ export const ProviderRegistryLive = Layer.effect(
provider: ServerProvider,
options?: {
readonly publish?: boolean;
+ readonly publishCheckedAt?: boolean;
+ readonly keepNewer?: boolean;
},
) {
return yield* upsertProviders([provider], options);
@@ -449,16 +489,21 @@ export const ProviderRegistryLive = Layer.effect(
},
);
+ // Probes of one instance may overlap (a background TTL probe and an
+ // explicit refresh), and each result also arrives on the instance's
+ // change stream. The newest `checkedAt` wins, so a result that lands late
+ // cannot overwrite fresher status.
+ const applyProbeResult = (provider: ServerProvider) =>
+ // A completed probe publishes even when only `checkedAt` moved, so
+ // clients can show when the provider was last checked.
+ syncProvider(provider, { publishCheckedAt: true, keepNewer: true });
+
const refreshOneSource = Effect.fn("refreshOneSource")(function* (
providerSource: ProviderSnapshotSource,
) {
- return yield* providerSource.refresh.pipe(
- Effect.flatMap((nextProvider) =>
- correlateSnapshotWithSource(providerSource, nextProvider).pipe(
- Effect.flatMap(syncProvider),
- ),
- ),
- );
+ const nextProvider = yield* providerSource.refresh;
+ const provider = yield* correlateSnapshotWithSource(providerSource, nextProvider);
+ return yield* applyProbeResult(provider);
});
const refreshAll = Effect.fn("refreshAll")(function* () {
@@ -569,8 +614,10 @@ export const ProviderRegistryLive = Layer.effect(
// the current read or the active subscriber observes the result.
for (const [, instance] of newlyAdded) {
const source = buildSnapshotSource(instance);
+ // Change-stream items are completed probes (periodic, explicit, or
+ // enrichment), so they follow the same newest-wins rule.
yield* Stream.runForEach(source.streamChanges, (provider) =>
- correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
+ correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(applyProbeResult)),
).pipe(Effect.forkScoped);
}
yield* Effect.yieldNow;
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index d8f8951a2..d5c09cfa4 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -45,6 +45,7 @@ import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
import * as Clock from "effect/Clock";
import * as Config from "effect/Config";
import * as Deferred from "effect/Deferred";
+import * as Exit from "effect/Exit";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -478,6 +479,7 @@ const buildAppUnderTest = (options?: {
ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]
>;
terminalManager?: Partial<TerminalManager.TerminalManager["Service"]>;
+ previewManager?: Partial<PreviewManager.PreviewManager["Service"]>;
orchestrationEngine?: Partial<OrchestrationEngine.OrchestrationEngineService["Service"]>;
threadDeletionReactor?: Partial<ThreadDeletionReactor["Service"]>;
routineRepository?: Partial<RoutineRepositoryShape>;
@@ -840,10 +842,11 @@ const buildAppUnderTest = (options?: {
refresh: () => Effect.void,
close: () => Effect.void,
list: () => Effect.succeed({ sessions: [], serverEpoch: "test-server", revision: 0 }),
- events: Stream.empty,
+ streamEvents: () => Stream.empty,
subscribeEvents: Effect.flatMap(PubSub.unbounded<PreviewEvent>(), (pubsub) =>
PubSub.subscribe(pubsub),
),
+ ...options?.layers?.previewManager,
}),
Layer.mock(PortScanner.PortDiscovery)({
scan: () => Effect.succeed([]),
@@ -3820,6 +3823,111 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+ it.effect("subscribePreviewEvents forwards the chat scope to the preview manager", () =>
+ Effect.gen(function* () {
+ const previewEvent = (threadId: string, tabId: string): PreviewEvent =>
+ ({
+ type: "closed",
+ threadId,
+ tabId,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ serverEpoch: "test-server",
+ revision: 1,
+ }) as PreviewEvent;
+ const published = [
+ previewEvent("thread-preview-b", "tab-1"),
+ previewEvent("thread-preview-a", "tab-2"),
+ previewEvent("thread-preview-a", "tab-3"),
+ ];
+ const requestedScopes: Array<string | undefined> = [];
+
+ yield* buildAppUnderTest({
+ layers: {
+ previewManager: {
+ streamEvents: (input) => {
+ requestedScopes.push(input.threadId);
+ return Stream.fromIterable(published).pipe(
+ Stream.filter(PreviewManager.previewEventMatchesSubscription(input)),
+ );
+ },
+ },
+ },
+ });
+
+ const wsUrl = yield* getWsServerUrl("/ws");
+ const events = yield* Effect.scoped(
+ withWsRpcClient(wsUrl, (client) =>
+ client[WS_METHODS.subscribePreviewEvents]({ threadId: "thread-preview-a" }).pipe(
+ Stream.take(2),
+ Stream.runCollect,
+ ),
+ ),
+ );
+
+ assert.deepEqual(requestedScopes, ["thread-preview-a"]);
+ assert.deepEqual(
+ Array.from(events, (event) => `${event.threadId}:${event.tabId}`),
+ ["thread-preview-a:tab-2", "thread-preview-a:tab-3"],
+ );
+ }).pipe(Effect.provide(NodeHttpServer.layerTest)),
+ );
+
+ it.effect("subscribeServerConfig probes a stale available provider once across clients", () =>
+ Effect.gen(function* () {
+ const instanceId = ProviderInstanceId.make("codex");
+ const staleProvider = {
+ instanceId,
+ driver: ProviderDriverKind.make("codex"),
+ enabled: true,
+ installed: true,
+ version: "1.0.0",
+ status: "ready" as const,
+ auth: { status: "authenticated" as const },
+ checkedAt: "2020-01-01T00:00:00.000Z",
+ models: [],
+ slashCommands: [],
+ skills: [],
+ };
+ // An instance whose driver is missing has nothing to probe.
+ const unavailableProvider = {
+ ...staleProvider,
+ instanceId: ProviderInstanceId.make("missing_driver"),
+ availability: "unavailable" as const,
+ };
+ const releaseProbe = yield* Deferred.make<void>();
+ const probeSucceeded = yield* Deferred.make<boolean>();
+ const probedInstanceIds: Array<string> = [];
+
+ yield* buildAppUnderTest({
+ layers: {
+ providerRegistry: {
+ getProviders: Effect.succeed([staleProvider, unavailableProvider]),
+ refreshInstance: (id) =>
+ Effect.sync(() => probedInstanceIds.push(id)).pipe(
+ Effect.andThen(Deferred.await(releaseProbe)),
+ Effect.as([staleProvider]),
+ Effect.onExit((exit) => Deferred.succeed(probeSucceeded, Exit.isSuccess(exit))),
+ ),
+ },
+ },
+ });
+
+ const wsUrl = yield* getWsServerUrl("/ws");
+ const takeSnapshot = withWsRpcClient(wsUrl, (client) =>
+ client[WS_METHODS.subscribeServerConfig]({}).pipe(Stream.take(1), Stream.runCollect),
+ );
+ // Each snapshot is sent after that subscription decided whether to
+ // probe, and the first probe stays blocked until both have arrived.
+ yield* Effect.scoped(Effect.all([takeSnapshot, takeSnapshot], { concurrency: "unbounded" }));
+ // Both clients have disconnected. The shared probe keeps running, so a
+ // later client still skips it and the probe completes.
+ yield* Effect.scoped(takeSnapshot);
+ assert.deepEqual(probedInstanceIds, [instanceId]);
+ yield* Deferred.succeed(releaseProbe, undefined);
+ assert.isTrue(yield* Deferred.await(probeSucceeded));
+ }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
+ );
+
it.effect(
"routes websocket rpc subscribeServerLifecycle replays snapshot and streams updates",
() =>
@@ -6618,6 +6726,105 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
);
+ it.effect("subscribeShell skips a thread upsert whose shell did not change", () =>
+ Effect.gen(function* () {
+ const quietThreadId = ThreadId.make("thread-dedupe-quiet");
+ const otherThreadId = ThreadId.make("thread-dedupe-other");
+ const now = "2026-01-01T00:00:00.000Z";
+ const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();
+ const received = yield* Queue.unbounded<OrchestrationShellStreamItem>();
+ const shellFetches: Array<string> = [];
+ let quietTitle = "Quiet";
+
+ const threadEvent = (sequence: number, threadId: ThreadId): OrchestrationEvent =>
+ ({
+ sequence,
+ eventId: EventId.make(`event-dedupe-${sequence}`),
+ aggregateKind: "thread",
+ aggregateId: threadId,
+ occurredAt: now,
+ commandId: null,
+ causationEventId: null,
+ correlationId: null,
+ metadata: {},
+ type: "thread.turn-diff-completed",
+ payload: {} as never,
+ }) satisfies OrchestrationEvent;
+
+ yield* buildAppUnderTest({
+ layers: {
+ orchestrationEngine: {
+ streamDomainEvents: Stream.fromPubSub(liveEvents),
+ subscribeDomainEvents: Effect.succeed(Stream.fromPubSub(liveEvents)),
+ },
+ projectionSnapshotQuery: {
+ getThreadShellById: (threadId) =>
+ Effect.sync(() => {
+ shellFetches.push(threadId);
+ return Option.some(
+ makeDefaultOrchestrationThreadShell({
+ id: threadId,
+ title: threadId === quietThreadId ? quietTitle : "Other",
+ }),
+ );
+ }),
+ getThreadRuntimeContext: () => Effect.die("unused"),
+ getTurnStartMessage: () => Effect.die("unused"),
+ },
+ },
+ });
+
+ const wsUrl = yield* getWsServerUrl("/ws");
+ const upsertedIds = yield* Effect.scoped(
+ Effect.gen(function* () {
+ yield* withWsRpcClient(wsUrl, (client) =>
+ client[ORCHESTRATION_WS_METHODS.subscribeShell]({
+ requestCompletionMarker: true,
+ }).pipe(Stream.runForEach((item) => Queue.offer(received, item))),
+ ).pipe(Effect.forkScoped);
+
+ const takeUpsert = Effect.gen(function* () {
+ while (true) {
+ const item = yield* Queue.take(received);
+ if (item.kind === "thread-upserted") {
+ return `${item.thread.id}:${item.thread.title}@${item.sequence}`;
+ }
+ }
+ });
+ const waitForSynchronized = Effect.gen(function* () {
+ while ((yield* Queue.take(received)).kind !== "synchronized") {}
+ });
+
+ yield* waitForSynchronized;
+ yield* PubSub.publish(liveEvents, threadEvent(1, quietThreadId));
+ const first = yield* takeUpsert;
+ // Same shell again: refetched, then dropped. The other thread's
+ // upsert must be the next item the client sees.
+ yield* PubSub.publish(liveEvents, threadEvent(2, quietThreadId));
+ yield* PubSub.publish(liveEvents, threadEvent(3, otherThreadId));
+ const second = yield* takeUpsert;
+ // A real change is still sent.
+ quietTitle = "Quiet renamed";
+ yield* PubSub.publish(liveEvents, threadEvent(4, quietThreadId));
+ const third = yield* takeUpsert;
+ // An unchanged shell is re-sent once the client's cursor would lag
+ // 500 events behind, so reconnects stay inside the replay window.
+ yield* PubSub.publish(liveEvents, threadEvent(504, quietThreadId));
+ const fourth = yield* takeUpsert;
+ return [first, second, third, fourth];
+ }),
+ );
+
+ assert.deepEqual(upsertedIds, [
+ `${quietThreadId}:Quiet@1`,
+ `${otherThreadId}:Other@3`,
+ `${quietThreadId}:Quiet renamed@4`,
+ `${quietThreadId}:Quiet renamed@504`,
+ ]);
+ assert.equal(shellFetches.filter((id) => id === quietThreadId).length, 4);
+ }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),
+ );
+
it.effect("subscribeShell coalescing still emits a removal for a deleted thread", () =>
Effect.gen(function* () {
const goneThreadId = ThreadId.make("thread-gone");
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index fcfbcf8aa..1a9041252 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -1,4 +1,5 @@
import * as Cause from "effect/Cause";
+import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
@@ -9,6 +10,7 @@ import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
+import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import {
AkeruBotUsageReadError,
@@ -65,6 +67,7 @@ import {
type ServerProvider,
type FilesystemBrowseFailure,
FilesystemBrowseError,
+ isProviderAvailable,
AssetWorkspaceContextNotFoundError,
AssetWorkspaceContextResolutionError,
RpcClientId,
@@ -428,6 +431,99 @@ export function isThreadDetailEvent(event: OrchestrationEvent): event is Extract
}
const PROVIDER_STATUS_DEBOUNCE_MS = 200;
+// A server-config subscription re-probes providers only when their cached
+// status is at least this old. Background health checks cover the rest.
+const PROVIDER_SUBSCRIBE_REFRESH_TTL_MS = 60_000;
+
+/**
+ * Subscription-triggered provider probes, shared by every connection so a
+ * reconnect burst probes each stale instance once instead of once per client.
+ * The probes run in the server's scope: a client that disconnects must not
+ * cancel a probe other clients skipped theirs for.
+ */
+interface ProviderSubscribeRefreshes {
+ /** Provider instance ids with a probe in flight. */
+ readonly inFlight: Set<string>;
+ readonly scope: Scope.Scope;
+}
+
+const THREAD_SHELL_REFETCH = "thread.shell-refetch";
+
+/**
+ * A live shell input that only asks for the thread's current shell. It keeps
+ * the coalescing key and sequence of the event it replaces without holding the
+ * event body.
+ */
+interface ThreadShellRefetch {
+ readonly type: typeof THREAD_SHELL_REFETCH;
+ readonly aggregateKind: "thread";
+ readonly aggregateId: ThreadId;
+ readonly threadId: ThreadId;
+ readonly sequence: number;
+}
+
+type ShellSourceEvent = OrchestrationEvent | ThreadShellRefetch;
+
+/** Thread events whose shell item reads the event payload instead of the projection. */
+const THREAD_SHELL_PAYLOAD_EVENT_TYPES: ReadonlySet<OrchestrationEvent["type"]> = new Set([
+ "thread.deleted",
+ "thread.archived",
+ "thread.unarchived",
+]);
+
+/** Reduce a thread event that the shell only refetches to its thread id and sequence. */
+const toShellSourceEvent = (event: OrchestrationEvent): ShellSourceEvent => {
+ if (event.aggregateKind !== "thread" || THREAD_SHELL_PAYLOAD_EVENT_TYPES.has(event.type)) {
+ return event;
+ }
+ const threadId = ThreadId.make(event.aggregateId);
+ return {
+ type: THREAD_SHELL_REFETCH,
+ aggregateKind: "thread",
+ aggregateId: threadId,
+ threadId,
+ sequence: event.sequence,
+ };
+};
+
+/** What one shell subscription has already sent to its client. */
+interface SentThreadShells {
+ /** Serialized thread shells last sent, keyed by thread id. */
+ readonly threads: Map<string, string>;
+ /** Sequence of the last item sent, which is the client's resume cursor. */
+ lastSentSequence: number;
+}
+
+const makeSentThreadShells = (): SentThreadShells => ({ threads: new Map(), lastSentSequence: 0 });
+
+/**
+ * Record a shell item for one subscription and report whether it repeats the
+ * thread shell already sent. A removal clears the entry so a restored thread
+ * is always sent again. An unchanged shell is still sent once the client's
+ * cursor would fall `SHELL_CURSOR_REFRESH_GAP` events behind, so a long run of
+ * unchanged events cannot push a reconnect past the replay window.
+ */
+const isUnchangedThreadShell = (
+ sent: SentThreadShells,
+ item: OrchestrationShellStreamEvent,
+): boolean => {
+ if (
+ item.kind === "thread-upserted" &&
+ item.sequence - sent.lastSentSequence < SHELL_CURSOR_REFRESH_GAP
+ ) {
+ const serialized = JSON.stringify(item.thread);
+ if (sent.threads.get(item.thread.id) === serialized) {
+ return true;
+ }
+ sent.threads.set(item.thread.id, serialized);
+ } else if (item.kind === "thread-upserted") {
+ sent.threads.set(item.thread.id, JSON.stringify(item.thread));
+ } else if (item.kind === "thread-removed") {
+ sent.threads.delete(item.threadId);
+ }
+ sent.lastSentSequence = Math.max(sent.lastSentSequence, item.sequence);
+ return false;
+};
// When a resuming client's cursor is more than this many events behind the
// current head, skip the per-event catch-up replay and send a fresh shell
@@ -435,6 +531,9 @@ const PROVIDER_STATUS_DEBOUNCE_MS = 200;
// past this gap a single O(active-threads) snapshot is cheaper and bounded.
// Matches the event store's default page size (DEFAULT_READ_FROM_SEQUENCE_LIMIT).
const SHELL_RESUME_MAX_GAP = 1_000;
+// A shell subscription re-sends an unchanged thread shell once its client's
+// cursor lags this far, keeping reconnects well inside the replay window.
+const SHELL_CURSOR_REFRESH_GAP = SHELL_RESUME_MAX_GAP / 2;
// Thread replay counts only this thread's rows. Busy or pruned unrelated
// streams must not force a full thread snapshot.
@@ -512,6 +611,7 @@ const makeWsRpcLayer = (
clientOrigin: OrchestrationClientOrigin,
previewAutomationBroker: PreviewAutomationBroker.PreviewAutomationBroker["Service"],
voiceCalls: VoiceCallManager.VoiceCallManager["Service"],
+ providerRefreshes: ProviderSubscribeRefreshes,
) =>
WsRpcGroup.toLayer(
Effect.gen(function* () {
@@ -929,8 +1029,12 @@ const makeWsRpcLayer = (
};
const toShellStreamEvent = (
- event: OrchestrationEvent,
+ source: ShellSourceEvent,
): Effect.Effect<Option.Option<OrchestrationShellStreamEvent>, never, never> => {
+ if (source.type === THREAD_SHELL_REFETCH) {
+ return threadUpsertOrRemove(source.threadId, source.sequence);
+ }
+ const event = source;
switch (event.type) {
case "project.created":
case "project.meta-updated":
@@ -1225,15 +1329,21 @@ const makeWsRpcLayer = (
// the client — which applies shell items strictly by increasing sequence
// and drops any `sequence <= snapshotSequence` — never skips a coalesced
// item. The refetch runs with bounded concurrency (order-preserving).
+ //
+ // `sentThreads` holds the last thread shell sent on this subscription, so
+ // a refetch that returns an identical shell (for example after a turn
+ // diff or checkpoint that changes no sidebar field) is not re-sent unless
+ // the client's resume cursor has fallen too far behind.
const SHELL_REFETCH_CONCURRENCY = 8;
const coalesceShellEvents = (
- events: ReadonlyArray<OrchestrationEvent>,
+ events: ReadonlyArray<ShellSourceEvent>,
+ sentThreads: SentThreadShells,
): Effect.Effect<ReadonlyArray<OrchestrationShellStreamEvent>, never, never> =>
Effect.gen(function* () {
if (events.length === 0) {
return [];
}
- const latestByAggregate = new Map<string, OrchestrationEvent>();
+ const latestByAggregate = new Map<string, ShellSourceEvent>();
for (const event of events) {
latestByAggregate.set(`${event.aggregateKind}:${event.aggregateId}`, event);
}
@@ -1243,7 +1353,11 @@ const makeWsRpcLayer = (
const shellEvents = yield* Effect.forEach(survivors, toShellStreamEvent, {
concurrency: SHELL_REFETCH_CONCURRENCY,
});
- return shellEvents.flatMap((option) => (Option.isSome(option) ? [option.value] : []));
+ return shellEvents.flatMap((option) =>
+ Option.isSome(option) && !isUnchangedThreadShell(sentThreads, option.value)
+ ? [option.value]
+ : [],
+ );
});
// Small time/size window over which to coalesce shell events. The window
@@ -1254,15 +1368,16 @@ const makeWsRpcLayer = (
const SHELL_COALESCE_MAX_CHUNK = 512;
const coalesceShellStream = <E, R>(
stream: Stream.Stream<OrchestrationEvent, E, R>,
+ sentThreads: SentThreadShells,
): Stream.Stream<OrchestrationShellStreamEvent, E, R> =>
stream.pipe(
Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),
- Stream.mapEffect(coalesceShellEvents),
+ Stream.mapEffect((events) => coalesceShellEvents(events, sentThreads)),
Stream.flatMap((items) => Stream.fromIterable(items)),
);
type ShellLiveInput =
- | { readonly kind: "event"; readonly event: OrchestrationEvent }
+ | { readonly kind: "event"; readonly event: ShellSourceEvent }
| { readonly kind: "synchronized" };
// A completion marker is queued alongside raw live events so it cannot
@@ -1270,10 +1385,11 @@ const makeWsRpcLayer = (
// batch at markers and coalesce only the event segments on either side.
const coalesceShellLiveInputs = (
inputs: ReadonlyArray<ShellLiveInput>,
+ sentThreads: SentThreadShells,
): Effect.Effect<ReadonlyArray<OrchestrationShellStreamItem>, never, never> =>
Effect.gen(function* () {
const output: Array<OrchestrationShellStreamItem> = [];
- let pendingEvents: Array<OrchestrationEvent> = [];
+ let pendingEvents: Array<ShellSourceEvent> = [];
for (const input of inputs) {
if (input.kind === "event") {
@@ -1281,12 +1397,12 @@ const makeWsRpcLayer = (
continue;
}
- output.push(...(yield* coalesceShellEvents(pendingEvents)));
+ output.push(...(yield* coalesceShellEvents(pendingEvents, sentThreads)));
pendingEvents = [];
output.push({ kind: "synchronized" });
}
- output.push(...(yield* coalesceShellEvents(pendingEvents)));
+ output.push(...(yield* coalesceShellEvents(pendingEvents, sentThreads)));
return output;
});
@@ -1896,6 +2012,7 @@ const makeWsRpcLayer = (
// path below emits from this same buffered live tail. Overlapping
// events are deduped by sequence on the client.
const liveBudget = yield* makeLiveStreamBudget();
+ const sentThreads = makeSentThreadShells();
const liveBuffer = yield* Queue.unbounded<
RetainedLiveItem<ShellLiveInput>,
OrchestrationGetSnapshotError
@@ -1921,10 +2038,15 @@ const makeWsRpcLayer = (
yield* Effect.forkScoped(
orchestrationEngine.streamDomainEvents.pipe(
Stream.runForEach((event) =>
- liveBudget.retain({ kind: "event" as const, event }, event).pipe(
- Effect.flatMap((item) => Queue.offer(liveBuffer, item)),
- Effect.uninterruptible,
- ),
+ // Retain only what the shell reads. A thread refetch needs
+ // the thread id and sequence, not a large message or tool
+ // payload, so the budget charges the small reference.
+ liveBudget
+ .retain({ kind: "event" as const, event: toShellSourceEvent(event) })
+ .pipe(
+ Effect.flatMap((item) => Queue.offer(liveBuffer, item)),
+ Effect.uninterruptible,
+ ),
),
// Stop the PubSub consumer even if RPC delivery is waiting
// for an ACK and never pulls the failed buffer again.
@@ -1936,9 +2058,10 @@ const makeWsRpcLayer = (
const coalesceRetainedInputs = (
items: ReadonlyArray<RetainedLiveItem<ShellLiveInput>>,
) =>
- coalesceShellLiveInputs(items.map((item) => item.value)).pipe(
- Effect.flatMap((output) => liveBudget.replace(items, output)),
- );
+ coalesceShellLiveInputs(
+ items.map((item) => item.value),
+ sentThreads,
+ ).pipe(Effect.flatMap((output) => liveBudget.replace(items, output)));
const bufferedLiveStream = Stream.fromQueue(liveBuffer).pipe(
Stream.groupedWithin(SHELL_COALESCE_MAX_CHUNK, SHELL_COALESCE_WINDOW),
Stream.mapEffect(coalesceRetainedInputs),
@@ -2032,6 +2155,7 @@ const makeWsRpcLayer = (
// cannot chase a moving event-store head or grow the live
// buffer indefinitely while waiting for an empty page.
orchestrationEngine.readEvents(afterSequence, replayGap, headSequence),
+ sentThreads,
).pipe(
Stream.mapError(
(cause) =>
@@ -3428,8 +3552,8 @@ const makeWsRpcLayer = (
previewAutomationBroker.focusHost(input),
{ "rpc.aggregate": "preview-automation" },
),
- [WS_METHODS.subscribePreviewEvents]: (_input) =>
- observeRpcStream(WS_METHODS.subscribePreviewEvents, previewManager.events, {
+ [WS_METHODS.subscribePreviewEvents]: (input) =>
+ observeRpcStream(WS_METHODS.subscribePreviewEvents, previewManager.streamEvents(input), {
"rpc.aggregate": "preview",
}),
[WS_METHODS.subscribeDiscoveredLocalServers]: (input) =>
@@ -3493,9 +3617,36 @@ const makeWsRpcLayer = (
})),
);
- yield* providerRegistry
- .refresh()
- .pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
+ // Serve the cached provider list. Re-probe only instances whose
+ // last check is older than the TTL and that no other
+ // subscription is already probing, so reconnect bursts and
+ // additional clients do not spawn repeated CLI version checks.
+ // Unavailable instances have no driver to probe, so their
+ // `checkedAt` never moves and they are skipped.
+ const nowMs = yield* Clock.currentTimeMillis;
+ const staleProviders = (yield* providerRegistry.getProviders).filter(
+ (provider) =>
+ isProviderAvailable(provider) &&
+ !providerRefreshes.inFlight.has(provider.instanceId) &&
+ nowMs - Date.parse(provider.checkedAt) >= PROVIDER_SUBSCRIBE_REFRESH_TTL_MS,
+ );
+ for (const provider of staleProviders) {
+ providerRefreshes.inFlight.add(provider.instanceId);
+ }
+ if (staleProviders.length > 0) {
+ yield* Effect.forEach(
+ staleProviders,
+ (provider) =>
+ providerRegistry
+ .refreshInstance(provider.instanceId)
+ .pipe(
+ Effect.ensuring(
+ Effect.sync(() => providerRefreshes.inFlight.delete(provider.instanceId)),
+ ),
+ ),
+ { concurrency: "unbounded", discard: true },
+ ).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(providerRefreshes.scope));
+ }
const liveUpdates = Stream.merge(
keybindingsUpdates,
@@ -3589,6 +3740,10 @@ export const websocketRpcRouteLayer = Layer.unwrap(
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const voiceCalls = yield* VoiceCallManager.VoiceCallManager;
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
+ const providerRefreshes: ProviderSubscribeRefreshes = {
+ inFlight: new Set(),
+ scope: yield* Effect.scope,
+ };
return HttpRouter.add(
"GET",
"/ws",
@@ -3610,7 +3765,13 @@ export const websocketRpcRouteLayer = Layer.unwrap(
disableTracing: true,
}).pipe(
Effect.provide(
- makeWsRpcLayer(session, clientOrigin, previewAutomationBroker, voiceCalls).pipe(
+ makeWsRpcLayer(
+ session,
+ clientOrigin,
+ previewAutomationBroker,
+ voiceCalls,
+ providerRefreshes,
+ ).pipe(
Layer.provideMerge(RpcSerialization.layerJson),
Layer.provide(ProviderMaintenanceRunner.layer),
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
diff --git a/apps/web/src/components/preview/usePreviewSession.ts b/apps/web/src/components/preview/usePreviewSession.ts
index 7f1a997f2..303d1e97f 100644
--- a/apps/web/src/components/preview/usePreviewSession.ts
+++ b/apps/web/src/components/preview/usePreviewSession.ts
@@ -34,7 +34,7 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
});
const eventsAtom = previewEnvironment.events({
environmentId: threadRef.environmentId,
- input: {},
+ input: { threadId: threadRef.threadId },
});
return Atom.make((get) => {
diff --git a/packages/contracts/src/preview.ts b/packages/contracts/src/preview.ts
index b1def6eb2..4f8d06202 100644
--- a/packages/contracts/src/preview.ts
+++ b/packages/contracts/src/preview.ts
@@ -302,6 +302,16 @@ export const PreviewEvent = Schema.Union([
]);
export type PreviewEvent = typeof PreviewEvent.Type;
+/**
+ * Scopes a preview event subscription. Frame events carry full-viewport PNGs,
+ * so clients should subscribe per chat. Omitting `threadId` streams every
+ * chat's events, which older clients rely on.
+ */
+export const PreviewEventsSubscribeInput = Schema.Struct({
+ threadId: Schema.optional(TrimmedNonEmptyString),
+});
+export type PreviewEventsSubscribeInput = typeof PreviewEventsSubscribeInput.Type;
+
/**
* A localhost server detected by the port scanner. Used to populate the
* "Local" recommendations in the empty-state of the preview panel.
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index ee3d83158..7e3bd64b2 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -133,6 +133,7 @@ import {
PreviewCloseInput,
PreviewError,
PreviewEvent,
+ PreviewEventsSubscribeInput,
PreviewListInput,
PreviewListResult,
PreviewNavigateInput,
@@ -962,7 +963,7 @@ export const WsPreviewAutomationFocusHostRpc = Rpc.make(WS_METHODS.previewAutoma
});
export const WsSubscribePreviewEventsRpc = Rpc.make(WS_METHODS.subscribePreviewEvents, {
- payload: Schema.Struct({}),
+ payload: PreviewEventsSubscribeInput,
success: PreviewEvent,
error: EnvironmentAuthorizationError,
stream: true,