TypeScript
perf(server): cut chatty tool-update frames by 90% (#8368)
Adamulek1237e4ce3bbb16c
diff --git a/apps/server/src/orchestration/ActivityPayloadProjection.ts b/apps/server/src/orchestration/ActivityPayloadProjection.tsindex 7d2ba79ce4a..0b1cb15d3db 100644--- a/apps/server/src/orchestration/ActivityPayloadProjection.ts+++ b/apps/server/src/orchestration/ActivityPayloadProjection.ts@@ -495,9 +495,6 @@ function toolLifecycleIdentity(activity: OrchestrationThreadActivity): string |* update within the turn — a later update belongs to a subsequent call that* reuses the same identity and is still in flight. Rows without a lifecycle* identity pass through, matching the clients, which never collapse them.- * Live `thread.activity-appended` events are untouched: updates still stream- * in real time and the completion supersedes them on the client as before.- ** Deliberate divergence from client collapse: clients fold only *adjacent** lifecycle rows, so a superseded update separated from its completion by an* interleaved parallel call renders as its own row today, and this drop@@ -524,7 +521,7 @@ function dropSupersededToolUpdatedActivities(if (!identity) {continue;}- const key = `${activity.turnId ?? ""} ${identity}`;+ const key = `${activity.turnId ?? ""}\u0000${identity}`;const indices = completionIndicesByKey.get(key);if (indices) {indices.push(index);@@ -544,7 +541,7 @@ function dropSupersededToolUpdatedActivities(if (!identity) {return true;}- const indices = completionIndicesByKey.get(`${activity.turnId ?? ""} ${identity}`);+ const indices = completionIndicesByKey.get(`${activity.turnId ?? ""}\u0000${identity}`);return !indices?.some((completionIndex) => completionIndex > index);});}diff --git a/apps/server/src/orchestration/ThreadLiveEventCoalescer.test.ts b/apps/server/src/orchestration/ThreadLiveEventCoalescer.test.tsnew file mode 100644index 00000000000..0a9915294d0--- /dev/null+++ b/apps/server/src/orchestration/ThreadLiveEventCoalescer.test.ts@@ -0,0 +1,171 @@+import {+ EventId,+ MessageId,+ ThreadId,+ TurnId,+ type OrchestrationEvent,+ type OrchestrationThreadActivity,+} from "@t3tools/contracts";+import { it } from "@effect/vitest";+import * as Clock from "effect/Clock";+import * as Effect from "effect/Effect";+import * as TestClock from "effect/testing/TestClock";+import { describe, expect } from "vite-plus/test";++import {+ coalesceLiveToolUpdatedEvents,+ makeThreadLiveEventCoalescer,+} from "./ThreadLiveEventCoalescer.ts";++const threadId = ThreadId.make("thread-coalescer-test");+const turnId = TurnId.make("turn-coalescer-test");++function makeToolActivity(+ sequence: number,+ options: {+ readonly kind?: "tool.updated" | "tool.completed";+ readonly toolCallId?: string;+ readonly turnId?: TurnId;+ } = {},+): OrchestrationEvent {+ const {+ kind = "tool.updated",+ toolCallId = "call-edit",+ turnId: activityTurnId = turnId,+ } = options;+ const activity: OrchestrationThreadActivity = {+ id: EventId.make(`activity-${sequence}`),+ tone: "tool",+ kind,+ summary: "Editing app.ts",+ payload: {+ itemType: "file_change",+ title: "Editing app.ts",+ data: toolCallId ? { toolCallId } : {},+ },+ turnId: activityTurnId,+ createdAt: "2026-01-01T00:00:01.000Z",+ };+ return {+ sequence,+ eventId: EventId.make(`event-${sequence}`),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: "2026-01-01T00:00:01.000Z",+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ type: "thread.activity-appended",+ payload: { threadId, activity },+ };+}++function makeMessage(sequence: number): OrchestrationEvent {+ return {+ sequence,+ eventId: EventId.make(`event-${sequence}`),+ aggregateKind: "thread",+ aggregateId: threadId,+ occurredAt: "2026-01-01T00:00:02.000Z",+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ type: "thread.message-sent",+ payload: {+ threadId,+ messageId: MessageId.make(`message-${sequence}`),+ role: "assistant",+ text: "Still working",+ turnId,+ streaming: false,+ createdAt: "2026-01-01T00:00:02.000Z",+ updatedAt: "2026-01-01T00:00:02.000Z",+ },+ };+}++describe("ThreadLiveEventCoalescer", () => {+ it("coalesces only calls with a stable toolCallId", () => {+ const events = [+ makeToolActivity(1, { toolCallId: "call-a" }),+ makeToolActivity(2, { toolCallId: "call-b" }),+ makeToolActivity(3, { toolCallId: "call-a" }),+ ];++ expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([2, 3]);+ });++ it("preserves parallel same-label calls without a stable toolCallId", () => {+ const events = [+ makeToolActivity(1, { toolCallId: "" }),+ makeToolActivity(2, { toolCallId: "" }),+ makeToolActivity(3, { kind: "tool.completed", toolCallId: "" }),+ ];++ expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([1, 2, 3]);+ });++ it("does not coalesce stable tool calls across turns", () => {+ const events = [+ makeToolActivity(1, { turnId: TurnId.make("turn-old") }),+ makeToolActivity(2, { turnId: TurnId.make("turn-new") }),+ ];++ expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([1, 2]);+ });++ it("flushes a stable update run before a completion boundary", () => {+ const events = [+ makeToolActivity(1),+ makeToolActivity(2),+ makeToolActivity(3, { kind: "tool.completed" }),+ makeToolActivity(4),+ ];++ expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([2, 3, 4]);+ });++ it.effect("flushes pending tool updates as soon as an unrelated event arrives", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const coalescer = yield* makeThreadLiveEventCoalescer({ coalesceWindow: "500 millis" });+ const startedAt = yield* Clock.currentTimeMillis;+ yield* Effect.forEach(+ Array.from({ length: 10 }, (_, index) => index + 2),+ (sequence) =>+ coalescer.offerAndWait({ kind: "event", event: makeToolActivity(sequence) }),+ { discard: true },+ );+ yield* coalescer.offerAndWait({ kind: "event", event: makeMessage(12) });++ expect(yield* Clock.currentTimeMillis).toBe(startedAt);+ expect(+ Array.from(yield* coalescer.takeAll).map((item) =>+ item.kind === "event" ? item.event.sequence : item.kind,+ ),+ ).toEqual([11, 12]);+ }),+ ).pipe(Effect.provide(TestClock.layer())),+ );++ it.effect("flushes pending tool updates as soon as a synchronization marker arrives", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const coalescer = yield* makeThreadLiveEventCoalescer({ coalesceWindow: "500 millis" });+ const startedAt = yield* Clock.currentTimeMillis;+ yield* coalescer.offerAndWait({ kind: "event", event: makeToolActivity(2) });+ yield* coalescer.offerAndWait({ kind: "event", event: makeToolActivity(3) });+ yield* coalescer.offerAndWait({ kind: "synchronized" });++ expect(yield* Clock.currentTimeMillis).toBe(startedAt);+ expect(+ Array.from(yield* coalescer.takeAll).map((item) =>+ item.kind === "event" ? item.event.sequence : item.kind,+ ),+ ).toEqual([3, "synchronized"]);+ }),+ ).pipe(Effect.provide(TestClock.layer())),+ );+});diff --git a/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts b/apps/server/src/orchestration/ThreadLiveEventCoalescer.tsnew file mode 100644index 00000000000..8271f6a550f--- /dev/null+++ b/apps/server/src/orchestration/ThreadLiveEventCoalescer.ts@@ -0,0 +1,207 @@+import type { OrchestrationEvent, OrchestrationThreadStreamItem } from "@t3tools/contracts";+import * as Deferred from "effect/Deferred";+import * as Duration from "effect/Duration";+import * as Effect from "effect/Effect";+import * as Fiber from "effect/Fiber";+import * as Predicate from "effect/Predicate";+import * as Queue from "effect/Queue";+import * as Semaphore from "effect/Semaphore";+import * as Stream from "effect/Stream";++import { projectActivityEvent } from "./ActivityPayloadProjection.ts";++const COALESCE_WINDOW = Duration.millis(50);+const MAX_PENDING_UPDATES = 512;++export type ThreadLiveInput =+ | { readonly kind: "event"; readonly event: OrchestrationEvent }+ | { readonly kind: "synchronized" };++function isToolUpdated(event: OrchestrationEvent): boolean {+ return (+ event.type === "thread.activity-appended" && event.payload.activity.kind === "tool.updated"+ );+}++function asTrimmedString(value: unknown): string | null {+ if (!Predicate.isString(value)) {+ return null;+ }+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : null;+}++function stableToolCallIdentity(event: OrchestrationEvent): string | null {+ if (event.type !== "thread.activity-appended") {+ return null;+ }+ const payload = event.payload.activity.payload;+ if (!Predicate.isObject(payload)) {+ return null;+ }+ const data = Predicate.isObject(payload.data) ? payload.data : null;+ return asTrimmedString(payload.toolCallId) ?? asTrimmedString(data?.toolCallId);+}++/**+ * Retain only the latest in-flight update for each stable tool-call id in a+ * live run. Anonymous calls pass through because labels are not unique when+ * tools execute in parallel. Survivors remain in sequence order.+ */+export function coalesceLiveToolUpdatedEvents(+ events: ReadonlyArray<OrchestrationEvent>,+): ReadonlyArray<OrchestrationEvent> {+ const survivors: Array<OrchestrationEvent> = [];+ let pendingUpdates: Array<OrchestrationEvent> = [];++ const flushUpdates = () => {+ const seen = new Set<string>();+ const latestUpdates: Array<OrchestrationEvent> = [];+ for (let index = pendingUpdates.length - 1; index >= 0; index -= 1) {+ const event = pendingUpdates[index]!;+ const identity = stableToolCallIdentity(event);+ const activity =+ event.type === "thread.activity-appended" ? event.payload.activity : undefined;+ const key = identity ? `${activity?.turnId ?? ""}\u0000${identity}` : null;+ if (key && seen.has(key)) {+ continue;+ }+ if (key) {+ seen.add(key);+ }+ latestUpdates.push(event);+ }+ latestUpdates.reverse();+ survivors.push(...latestUpdates);+ pendingUpdates = [];+ };++ for (const event of events) {+ if (isToolUpdated(event)) {+ pendingUpdates.push(event);+ continue;+ }+ flushUpdates();+ survivors.push(event);+ }+ flushUpdates();+ return survivors;+}++export const makeThreadLiveEventCoalescer = Effect.fn("makeThreadLiveEventCoalescer")(+ function* (options?: { readonly coalesceWindow?: Duration.Input }) {+ const output = yield* Queue.unbounded<OrchestrationThreadStreamItem>();+ const input = yield* Queue.unbounded<{+ readonly value: ThreadLiveInput;+ readonly processed?: Deferred.Deferred<void>;+ }>();+ const mutex = yield* Semaphore.make(1);+ const coalesceWindow = options?.coalesceWindow ?? COALESCE_WINDOW;+ let pendingUpdates: Array<OrchestrationEvent> = [];+ let windowGeneration = 0;+ let windowFiber: Fiber.Fiber<void, never> | null = null;++ const cancelWindow = Effect.fn("ThreadLiveEventCoalescer.cancelWindow")(function* () {+ const fiber = windowFiber;+ if (!fiber) {+ return;+ }+ windowFiber = null;+ yield* Fiber.interrupt(fiber);+ });++ const flushPending = Effect.fn("ThreadLiveEventCoalescer.flushPending")(function* (+ boundary?: OrchestrationEvent,+ ) {+ const events = boundary ? [...pendingUpdates, boundary] : pendingUpdates;+ pendingUpdates = [];+ if (events.length === 0) {+ return;+ }+ yield* Queue.offerAll(+ output,+ coalesceLiveToolUpdatedEvents(events).map((event) => ({+ kind: "event" as const,+ event: projectActivityEvent(event),+ })),+ );+ });++ const flushWindow = (generation: number) =>+ Effect.sleep(coalesceWindow).pipe(+ Effect.andThen(+ mutex.withPermits(1)(+ Effect.suspend(() => (generation === windowGeneration ? flushPending() : Effect.void)),+ ),+ ),+ Effect.ensuring(+ Effect.sync(() => {+ if (generation === windowGeneration) {+ windowFiber = null;+ }+ }),+ ),+ );++ const process = Effect.fn("ThreadLiveEventCoalescer.process")(function* (+ input: ThreadLiveInput,+ ) {+ yield* mutex.withPermits(1)(+ Effect.gen(function* () {+ if (input.kind === "event" && isToolUpdated(input.event)) {+ pendingUpdates.push(input.event);+ if (pendingUpdates.length === 1) {+ const generation = ++windowGeneration;+ windowFiber = yield* Effect.forkScoped(flushWindow(generation));+ }+ if (pendingUpdates.length >= MAX_PENDING_UPDATES) {+ yield* cancelWindow();+ windowGeneration += 1;+ yield* flushPending();+ }+ return;+ }++ yield* cancelWindow();+ windowGeneration += 1;+ // A non-update event closes the run immediately. The coalescer keeps+ // that boundary after the final update from the run.+ if (input.kind === "event") {+ yield* flushPending(input.event);+ } else {+ yield* flushPending();+ yield* Queue.offer(output, { kind: "synchronized" });+ }+ }),+ );+ });++ yield* Stream.fromQueue(input).pipe(+ Stream.runForEach(({ value, processed }) =>+ process(value).pipe(+ Effect.andThen(processed ? Deferred.succeed(processed, undefined) : Effect.void),+ ),+ ),+ Effect.forkScoped,+ );++ const offer = (value: ThreadLiveInput) => Queue.offer(input, { value }).pipe(Effect.asVoid);++ // Synchronization callers wait for their marker to pass through the same+ // ordered input queue before draining output produced ahead of it.+ const offerAndWait = Effect.fn("ThreadLiveEventCoalescer.offerAndWait")(function* (+ value: ThreadLiveInput,+ ) {+ const processed = yield* Deferred.make<void>();+ yield* Queue.offer(input, { value, processed });+ yield* Deferred.await(processed);+ });++ return {+ offer,+ offerAndWait,+ stream: Stream.fromQueue(output),+ takeAll: Queue.takeAll(output),+ } as const;+ },+);diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.tsindex 0780af4d1b4..93a3977ddd0 100644--- a/apps/server/src/server.test.ts+++ b/apps/server/src/server.test.ts@@ -19,6 +19,7 @@ import {ExternalLauncherCommandNotFoundError,OrchestrationThreadDetailSnapshot,type OrchestrationThreadStreamItem,+ type OrchestrationThreadActivity,type OrchestrationThreadShell,TerminalNotRunningError,type OrchestrationCommand,@@ -30,6 +31,7 @@ import {ProviderInstanceId,ResolvedKeybindingRule,ThreadId,+ TurnId,WS_METHODS,WsRpcGroup,EditorId,@@ -197,6 +199,44 @@ const defaultModelSelection = {instanceId: ProviderInstanceId.make("codex"),model: "gpt-5-codex",} as const;++const makeLiveToolActivityEvent = (+ sequence: number,+ kind: "tool.updated" | "tool.completed" = "tool.updated",+ options: {+ readonly toolCallId?: string;+ readonly title?: string;+ readonly path?: string;+ } = {},+): Extract<OrchestrationEvent, { type: "thread.activity-appended" }> => {+ const { toolCallId = "call-edit", title = "Editing app.ts", path = "src/app.ts" } = options;+ const activity: OrchestrationThreadActivity = {+ id: EventId.make(`activity-${sequence}`),+ tone: "tool",+ kind,+ summary: title,+ payload: {+ itemType: "file_change",+ title,+ data: { toolCallId, path },+ },+ turnId: TurnId.make("turn-edit"),+ createdAt: "2026-01-01T00:00:01.000Z",+ };+ return {+ sequence,+ eventId: EventId.make(`event-tool-${sequence}`),+ aggregateKind: "thread",+ aggregateId: defaultThreadId,+ occurredAt: "2026-01-01T00:00:01.000Z",+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ type: "thread.activity-appended",+ payload: { threadId: defaultThreadId, activity },+ };+};const testEnvironmentDescriptor = {environmentId: EnvironmentId.make("environment-test"),label: "Test environment",@@ -6918,6 +6958,206 @@ it.layer(NodeServices.layer)("server router seam", (it) => {}).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),);+ it.effect("coalesces buffered live tool updates to the latest state", () =>+ Effect.gen(function* () {+ const thread = makeDefaultOrchestrationReadModel().threads[0]!;+ const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();++ yield* buildAppUnderTest({+ layers: {+ orchestrationEngine: {+ streamDomainEvents: Stream.fromPubSub(liveEvents),+ },+ projectionSnapshotQuery: {+ getThreadDetailSnapshot: () =>+ Effect.gen(function* () {+ yield* Effect.sleep("25 millis");+ yield* PubSub.publishAll(liveEvents, [+ makeLiveToolActivityEvent(2),+ makeLiveToolActivityEvent(3),+ makeLiveToolActivityEvent(4),+ ]);+ return Option.some({ snapshotSequence: 1, thread });+ }),+ },+ },+ });++ const wsUrl = yield* getWsServerUrl("/ws");+ const items = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[ORCHESTRATION_WS_METHODS.subscribeThread]({+ threadId: defaultThreadId,+ }).pipe(Stream.take(2), Stream.runCollect),+ ),+ ).pipe(Effect.timeout("2 seconds"));++ assert.equal(items[0]?.kind, "snapshot");+ assert.equal(items[1]?.kind, "event");+ assert.equal(items[1]?.kind === "event" ? items[1].event.sequence : null, 4);+ }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),+ );++ it.effect("flushes more than one tool chunk before the synchronization marker", () =>+ Effect.gen(function* () {+ const thread = makeDefaultOrchestrationReadModel().threads[0]!;+ const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();++ yield* buildAppUnderTest({+ layers: {+ orchestrationEngine: {+ streamDomainEvents: Stream.fromPubSub(liveEvents),+ },+ projectionSnapshotQuery: {+ getThreadDetailSnapshot: () =>+ Effect.gen(function* () {+ yield* Effect.sleep("25 millis");+ yield* PubSub.publishAll(liveEvents, [+ ...Array.from({ length: 512 }, (_, index) =>+ makeLiveToolActivityEvent(index + 2),+ ),+ makeLiveToolActivityEvent(514, "tool.updated", {+ toolCallId: "call-read",+ title: "Reading server.test.ts",+ path: "apps/server/src/server.test.ts",+ }),+ ]);+ return Option.some({ snapshotSequence: 1, thread });+ }),+ },+ },+ });++ const wsUrl = yield* getWsServerUrl("/ws");+ const items = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[ORCHESTRATION_WS_METHODS.subscribeThread]({+ threadId: defaultThreadId,+ requestCompletionMarker: true,+ }).pipe(Stream.take(4), Stream.runCollect),+ ),+ ).pipe(Effect.timeout("2 seconds"));++ assert.equal(items[0]?.kind, "snapshot");+ assert.deepEqual(+ items.slice(1, 3).map((item) => {+ assert.equal(item?.kind, "event");+ if (item?.kind !== "event" || item.event.type !== "thread.activity-appended") {+ return null;+ }+ return {+ sequence: item.event.sequence,+ summary: item.event.payload.activity.summary,+ payload: item.event.payload.activity.payload,+ };+ }),+ [+ {+ sequence: 513,+ summary: "Editing app.ts",+ payload: {+ itemType: "file_change",+ title: "Editing app.ts",+ data: {+ files: [{ path: "src/app.ts" }],+ toolCallId: "call-edit",+ },+ },+ },+ {+ sequence: 514,+ summary: "Reading server.test.ts",+ payload: {+ itemType: "file_change",+ title: "Reading server.test.ts",+ data: {+ files: [{ path: "apps/server/src/server.test.ts" }],+ toolCallId: "call-read",+ },+ },+ },+ ],+ );+ assert.deepEqual(items[3], { kind: "synchronized" });+ }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),+ );++ it.effect("flushes a tool update before an interleaved message", () =>+ Effect.gen(function* () {+ const thread = makeDefaultOrchestrationReadModel().threads[0]!;+ const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();+ const messageEvent = {+ sequence: 3,+ eventId: EventId.make("event-interleaved-message"),+ aggregateKind: "thread",+ aggregateId: defaultThreadId,+ occurredAt: "2026-01-01T00:00:02.000Z",+ commandId: null,+ causationEventId: null,+ correlationId: null,+ metadata: {},+ type: "thread.message-sent",+ payload: {+ threadId: defaultThreadId,+ messageId: MessageId.make("message-interleaved"),+ role: "assistant",+ text: "Still working",+ turnId: TurnId.make("turn-edit"),+ streaming: false,+ createdAt: "2026-01-01T00:00:02.000Z",+ updatedAt: "2026-01-01T00:00:02.000Z",+ },+ } satisfies Extract<OrchestrationEvent, { type: "thread.message-sent" }>;++ yield* buildAppUnderTest({+ layers: {+ orchestrationEngine: {+ streamDomainEvents: Stream.fromPubSub(liveEvents),+ },+ projectionSnapshotQuery: {+ getThreadDetailSnapshot: () =>+ Effect.gen(function* () {+ yield* Effect.sleep("25 millis");+ yield* PubSub.publishAll(liveEvents, [+ makeLiveToolActivityEvent(2),+ messageEvent,+ makeLiveToolActivityEvent(4, "tool.completed"),+ ]);+ return Option.some({ snapshotSequence: 1, thread });+ }),+ },+ },+ });++ const wsUrl = yield* getWsServerUrl("/ws");+ const items = yield* Effect.scoped(+ withWsRpcClient(wsUrl, (client) =>+ client[ORCHESTRATION_WS_METHODS.subscribeThread]({+ threadId: defaultThreadId,+ }).pipe(Stream.take(4), Stream.runCollect),+ ),+ ).pipe(Effect.timeout("2 seconds"));++ assert.equal(items[0]?.kind, "snapshot");+ assert.deepEqual(+ items+ .slice(1)+ .map((item) => (item.kind === "event" ? [item.event.sequence, item.event.type] : null)),+ [+ [2, "thread.activity-appended"],+ [3, "thread.message-sent"],+ [4, "thread.activity-appended"],+ ],+ );+ assert.equal(+ items[3]?.kind === "event" && items[3].event.type === "thread.activity-appended"+ ? items[3].event.payload.activity.kind+ : null,+ "tool.completed",+ );+ }).pipe(Effect.provide(NodeHttpServer.layerTest), TestClock.withLive),+ );+it.effect("subscribeThread sends a fresh snapshot instead of replaying a large gap", () =>Effect.gen(function* () {let readEventsCalls = 0;diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 9983de224f2..4da8420799e 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -80,6 +80,7 @@ import {projectActivityEvent,projectThreadDetailSnapshot,} from "./orchestration/ActivityPayloadProjection.ts";+import { makeThreadLiveEventCoalescer } from "./orchestration/ThreadLiveEventCoalescer.ts";import {cleanupFailedUploadedAttachments,normalizeDispatchCommand,@@ -1501,17 +1502,15 @@ const makeWsRpcLayer = (Stream.filter(isThisThreadDetailEvent),Stream.map((event) => ({kind: "event" as const,- event: projectActivityEvent(event),+ event,})),);// Attach live delivery before reading either replay or snapshot state.// Otherwise an event published while the snapshot is loading is lost.- const liveBuffer = yield* Queue.unbounded<OrchestrationThreadStreamItem>();- yield* Effect.forkScoped(- liveStream.pipe(Stream.runForEach((item) => Queue.offer(liveBuffer, item))),- );- const bufferedLiveStream = Stream.fromQueue(liveBuffer);+ const liveBuffer = yield* makeThreadLiveEventCoalescer();+ yield* Effect.forkScoped(liveStream.pipe(Stream.runForEach(liveBuffer.offer)));+ const bufferedLiveStream = liveBuffer.stream;// When the client already loaded the snapshot over HTTP it passes// that snapshot's sequence, and we resume the live subscription by@@ -1560,8 +1559,10 @@ const makeWsRpcLayer = (input.requestCompletionMarker === true? Stream.concat(Stream.fromEffect(- Queue.offer(liveBuffer, { kind: "synchronized" as const }),- ).pipe(Stream.drain),+ liveBuffer+ .offerAndWait({ kind: "synchronized" as const })+ .pipe(Effect.andThen(liveBuffer.takeAll)),+ ).pipe(Stream.flatMap((items) => Stream.fromIterable(items))),bufferedLiveStream,): bufferedLiveStream;@@ -1602,8 +1603,10 @@ const makeWsRpcLayer = (input.requestCompletionMarker === true? Stream.concat(Stream.fromEffect(- Queue.offer(liveBuffer, { kind: "synchronized" as const }),- ).pipe(Stream.drain),+ liveBuffer+ .offerAndWait({ kind: "synchronized" as const })+ .pipe(Effect.andThen(liveBuffer.takeAll)),+ ).pipe(Stream.flatMap((items) => Stream.fromIterable(items))),bufferedLiveStream,): bufferedLiveStream;