Skip to content
TypeScript

perf(acp): coalesce streamed text snapshots (#19626)

Wout Stiens0e40614ad502
diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
index 35c271ac0f0..ce997f64828 100644
--- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
@@ -1944,6 +1944,144 @@ describe("AcpAdapterV2", () => {
}).pipe(Effect.provide(layerTest), Effect.scoped),
);
+ it.effect("coalesces streamed ACP text into bounded snapshots without delaying its start", () =>
+ Effect.gen(function* () {
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const path = yield* Path.Path;
+ const selfInvocation = yield* resolveSelfInvocation();
+ const mockAgentPath = yield* path.fromFileUrl(
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
+ );
+ type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"];
+ let sessionUpdateHandler: Parameters<RuntimeService["handleSessionUpdate"]>[0] | undefined;
+ const protocolEvents = yield* Queue.unbounded<EffectAcpProtocol.AcpProtocolLogEvent>();
+ const instanceId = ProviderInstanceId.make("acp-test-text-coalescing");
+ const adapter = yield* makeAcpAdapterV2({
+ instanceId,
+ flavor: {
+ driver: ACP_TEST_DRIVER,
+ capabilities: AcpProviderCapabilitiesV2,
+ makeRuntime: makeMockRuntime({
+ childProcessSpawner,
+ mockAgentPath,
+ environment: { T3_ACP_HANG_PROMPT_FOREVER: "1" },
+ protocolEvents,
+ wrapRuntime: (runtime) => ({
+ ...runtime,
+ handleSessionUpdate: (handler) =>
+ Effect.sync(() => {
+ sessionUpdateHandler = handler;
+ }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))),
+ }),
+ }),
+ },
+ selfInvocation,
+ });
+ const threadId = ThreadId.make("thread-acp-text-coalescing");
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ cwd: process.cwd(),
+ });
+ const modelSelection = { instanceId, model: "default" } as const;
+ const runtime = yield* adapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make("provider-session-acp-text-coalescing"),
+ modelSelection,
+ runtimePolicy,
+ });
+ const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event>();
+ yield* runtime.events.pipe(
+ Stream.runForEach((event) => Queue.offer(events, event)),
+ Effect.forkScoped,
+ );
+ const providerThread = yield* runtime.ensureThread({
+ threadId,
+ modelSelection,
+ runtimePolicy,
+ });
+ const now = yield* DateTime.now;
+ yield* runtime.startTurn(
+ makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
+ );
+ yield* Stream.fromQueue(protocolEvents).pipe(
+ Stream.filter(
+ (event) =>
+ event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt",
+ ),
+ Stream.runHead,
+ );
+ assert.isDefined(sessionUpdateHandler);
+ const sendUpdate = (update: EffectAcpSchema.SessionNotification["update"]) =>
+ sessionUpdateHandler!({ sessionId: "mock-session-1", update });
+ const chunk = "tok0 word ";
+
+ for (let index = 0; index < 1_000; index += 1) {
+ yield* sendUpdate({
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: chunk },
+ });
+ }
+ yield* TestClock.adjust("50 millis");
+ yield* sendUpdate({
+ sessionUpdate: "agent_message_chunk",
+ content: { type: "text", text: "end" },
+ });
+ // Another item closes the assistant segment while its next flush is pending.
+ yield* sendUpdate({
+ sessionUpdate: "agent_thought_chunk",
+ content: { type: "text", text: "next" },
+ });
+ yield* TestClock.adjust("50 millis");
+ yield* sendUpdate({
+ sessionUpdate: "plan_update",
+ plan: {
+ type: "items",
+ planId: "plan-sentinel",
+ entries: [{ content: "Continue", priority: "medium", status: "in_progress" }],
+ },
+ });
+ const streamed: Array<ProviderAdapter.ProviderAdapterV2Event> = [];
+ while (streamed.at(-1)?.type !== "plan.updated") {
+ streamed.push(yield* Queue.take(events));
+ }
+
+ const reply = chunk.repeat(1_000);
+ assert.deepEqual(
+ streamed.flatMap((event) =>
+ event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
+ ? [[event.turnItem.status, event.turnItem.text]]
+ : [],
+ ),
+ [
+ ["running", chunk],
+ ["running", reply],
+ ["completed", `${reply}end`],
+ ],
+ );
+ assert.deepEqual(
+ streamed.flatMap((event) =>
+ event.type === "message.updated" && event.message.role === "assistant"
+ ? [[event.message.streaming, event.message.text]]
+ : [],
+ ),
+ [
+ [true, chunk],
+ [true, reply],
+ [false, `${reply}end`],
+ ],
+ );
+ assert.deepEqual(
+ streamed.flatMap((event) =>
+ event.type === "node.updated" && event.node.kind === "assistant_message"
+ ? [event.node.status]
+ : [],
+ ),
+ ["running", "completed"],
+ );
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
+ );
+
it.live(
"loads the persisted ACP session during startup without creating a throwaway session",
() =>
diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts
index c23f2b99a91..633775402f6 100644
--- a/packages/provider-acp/src/server/adapter.ts
+++ b/packages/provider-acp/src/server/adapter.ts
@@ -128,6 +128,15 @@ export const ACP_PROTOCOL = "acp.ndjson-jsonrpc" as const;
*/
const ACP_DEFERRED_FINALIZE_DEBOUNCE: Duration.Input = "3000 millis";
+/**
+ * Coalescing window for streamed text. A text segment's first chunk and its
+ * close emit at once; a later chunk schedules one full-text snapshot this long
+ * after it, and the chunks inside the window share it instead of each emitting
+ * the whole reply, which grew with the square of the reply length. The flush
+ * is scheduled, not a hard deadline, so it can land later under host load.
+ */
+const ACP_TEXT_FLUSH_INTERVAL: Duration.Input = "50 millis";
+
export interface AcpAdapterV2RuntimeInput {
readonly cwd: string;
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
@@ -957,6 +966,10 @@ interface ActiveTextSegment {
readonly startedAt: DateTime.Utc;
sourceMessageId: string | null;
text: string;
+ // The running node and first text have been emitted.
+ emitted: boolean;
+ // Text changed since the last emission; a delayed flush is scheduled.
+ dirty: boolean;
}
interface ActiveTextStream {
@@ -2168,14 +2181,32 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
? context.assistant
: context.reasoning;
+ const textEmissionPermit = yield* Semaphore.make(1);
+ /**
+ * Emits the stream's current segment. A `flushOf` call is a delayed
+ * flush: it emits only while that segment is still current and has
+ * unsent text. The permit keeps a flush from landing after the
+ * segment's completed snapshot.
+ */
const emitTextSegment = Effect.fnUntraced(function* (
context: ActiveAcpTurn,
kind: "user" | "assistant" | "reasoning",
completed: boolean,
+ flushOf?: ActiveTextSegment,
) {
const stream = textStreamFor(context, kind);
const segment = stream.current;
if (segment === null) return;
+ if (flushOf !== undefined && (segment !== flushOf || !segment.dirty)) return;
+ // The node carries no text, so it changes only when the segment
+ // opens and when it completes.
+ const emitsNode = completed || !segment.emitted;
+ segment.emitted = true;
+ segment.dirty = false;
+ // Read the text in the same step that clears `dirty`. Chunks keep
+ // appending while this emission yields; each one marks the segment
+ // dirty again and reaches the next flush or the close.
+ const text = segment.text;
const now = yield* DateTime.now;
const ordinal = yield* resolveItemOrdinal(context, segment.nativeItemId);
const nodeId = providerNodeId(segment.nativeItemId);
@@ -2185,7 +2216,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
nativeId: segment.nativeItemId,
strength: "weak" as const,
};
- if (kind !== "user") {
+ if (kind !== "user" && emitsNode) {
yield* emitProviderEvent({
type: "node.updated",
driver,
@@ -2219,7 +2250,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
runId: context.input.runId,
nodeId: messageNodeId,
role: kind,
- text: segment.text,
+ text,
attachments: [],
streaming: !completed,
createdAt: segment.startedAt,
@@ -2251,7 +2282,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
type: "user_message",
messageId,
inputIntent: "turn_start",
- text: segment.text,
+ text,
attachments: [],
},
}
@@ -2275,7 +2306,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
updatedAt: now,
type: "assistant_message",
messageId,
- text: segment.text,
+ text,
streaming: !completed,
},
},
@@ -2302,10 +2333,31 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
completedAt: completed ? now : null,
updatedAt: now,
type: "reasoning",
- text: segment.text,
+ text,
streaming: !completed,
},
});
+ }, textEmissionPermit.withPermit);
+
+ /**
+ * Publishes a text change. A segment's first text emits at once so
+ * live output starts immediately; later changes coalesce into one
+ * snapshot per ACP_TEXT_FLUSH_INTERVAL. Closing the segment emits its
+ * final text and makes a pending flush a no-op.
+ */
+ const publishTextSegment = Effect.fnUntraced(function* (
+ context: ActiveAcpTurn,
+ kind: "user" | "assistant" | "reasoning",
+ ) {
+ const segment = textStreamFor(context, kind).current;
+ if (segment === null) return;
+ if (!segment.emitted) return yield* emitTextSegment(context, kind, false);
+ if (segment.dirty) return;
+ segment.dirty = true;
+ yield* emitTextSegment(context, kind, false, segment).pipe(
+ Effect.delay(ACP_TEXT_FLUSH_INTERVAL),
+ Effect.forkIn(sessionScope),
+ );
});
const closeTextStream = Effect.fnUntraced(function* (
@@ -2354,6 +2406,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
startedAt: now,
sourceMessageId,
text: "",
+ emitted: false,
+ dirty: false,
};
stream.nextSegment += 1;
} else if (stream.current.sourceMessageId === null && sourceMessageId !== null) {
@@ -2362,7 +2416,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
stream.current.sourceMessageId = sourceMessageId;
}
stream.current.text += text;
- yield* emitTextSegment(context, kind, false);
+ yield* publishTextSegment(context, kind);
});
const replaceText = Effect.fnUntraced(function* (
@@ -2383,12 +2437,14 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
startedAt: now,
sourceMessageId: messageId,
text,
+ emitted: false,
+ dirty: false,
};
stream.nextSegment += 1;
} else {
stream.current.text = text;
}
- yield* emitTextSegment(context, kind, false);
+ yield* publishTextSegment(context, kind);
});
const emitSubagentAssistant = Effect.fnUntraced(function* (