Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 29 additions & 12 deletions src/renderer/state/slices/runtimeEventSlice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ describe("runtimeEventSlice.applyRuntimeEvent", () => {
store.getState().applyRuntimeEvent(threadId, event);
}

function applyBatch(threadId: string, events: RuntimeEvent[]) {
store.getState().applyRuntimeEvents(threadId, events);
}

it("appends a new item on item.started", () => {
apply("t1", {
type: "item.started",
Expand Down Expand Up @@ -190,29 +194,42 @@ describe("runtimeEventSlice.applyRuntimeEvent", () => {
});
});

it("deduplicates overlapping streamed chunks", () => {
apply("t1", {
type: "item.started",
// Streams are append-only: a delta boundary that lands on a repeated
// character (e.g. "aws s" + "so login") must not be deduplicated. Both the
// per-event reducer and the batch coalescer must preserve it.
const repeatedCharChunks: RuntimeEvent[] = [
{ type: "item.started", threadId: "t1", itemId: "i1", itemType: "assistant_message" },
{
type: "content.delta",
threadId: "t1",
itemId: "i1",
itemType: "assistant_message",
});
apply("t1", {
stream: "assistant_text",
delta: "aws s",
},
{
type: "content.delta",
threadId: "t1",
itemId: "i1",
stream: "assistant_text",
delta: "WorkingWorking through through tasks tasks.",
});
apply("t1", {
delta: "so login --profile DataScience-Team-228",
},
{
type: "content.delta",
threadId: "t1",
itemId: "i1",
stream: "assistant_text",
delta: " tasks tasks. What What do do you you need need done done??",
});
delta: "889582725",
},
];
const repeatedCharResult = "aws sso login --profile DataScience-Team-228889582725";

it.each([
["applied one at a time", (events: RuntimeEvent[]) => events.forEach((e) => apply("t1", e))],
["coalesced as a batch", (events: RuntimeEvent[]) => applyBatch("t1", events)],
])("preserves repeated characters across streamed chunk boundaries (%s)", (_label, deliver) => {
deliver(repeatedCharChunks);
expect(store.getState().runtimeItemsByIdByThread["t1"]?.["i1"]?.streams.assistant_text).toBe(
"WorkingWorking through through tasks tasks. What What do do you you need need done done??",
repeatedCharResult,
);
});

Expand Down
40 changes: 2 additions & 38 deletions src/renderer/state/slices/runtimeEventSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ function applyRuntimeEventToRuntimeState(
const next: RuntimeChatItem = {
...prev,
state: prev.state === "completed" ? "completed" : "updated",
streams: { ...prev.streams, [event.stream]: mergeStreamChunk(prevStream, event.delta) },
streams: { ...prev.streams, [event.stream]: prevStream + event.delta },
};
items[event.itemId] = next;
return {
Expand Down Expand Up @@ -817,7 +817,7 @@ function coalesceRuntimeEvents(events: RuntimeEvent[]): RuntimeEvent[] {
) {
pendingDelta = {
...pendingDelta,
delta: mergeStreamChunk(pendingDelta.delta, event.delta),
delta: pendingDelta.delta + event.delta,
};
continue;
}
Expand Down Expand Up @@ -920,39 +920,3 @@ function mergePayload(prev: unknown, next: unknown): unknown {
if (!next || typeof next !== "object") return next;
return { ...(prev as Record<string, unknown>), ...(next as Record<string, unknown>) };
}

/**
* Some providers emit overlapping text chunks (next chunk starts with the tail
* of the previous chunk) rather than strict append-only deltas. Merge the
* largest shared suffix/prefix so streamed text stays stable.
*
* Append-only is by far the common case (Codex/Copilot ACP, OpenCode, Claude),
* so the algorithm is biased to bail out cheaply when no overlap is possible:
* we use `indexOf` to find candidate suffix-start positions in O(N) total
* rather than iterating overlap sizes from `maxOverlap` down to 1 (each step
* doing an O(K) `endsWith` check, which was O(N²) for long messages).
*/
function mergeStreamChunk(existing: string, incoming: string): string {
if (!incoming) return existing;
if (!existing) return incoming;
if (existing.endsWith(incoming)) return existing;
if (incoming.startsWith(existing)) return incoming;

const maxOverlap = Math.min(existing.length, incoming.length);
const firstChar = incoming[0]!;
// Scan existing's tail (length up to maxOverlap) for positions where the
// first character of `incoming` appears. The leftmost match yields the
// largest possible overlap, so we accept the first one whose suffix matches
// and short-circuit. When `firstChar` doesn't appear in the tail at all
// (the typical append-only case), `indexOf` returns -1 and we skip the
// body entirely — O(N) at worst, O(1) in the fast path.
let candidate = existing.indexOf(firstChar, existing.length - maxOverlap);
while (candidate !== -1) {
const overlap = existing.length - candidate;
if (existing.slice(candidate) === incoming.slice(0, overlap)) {
return existing + incoming.slice(overlap);
}
candidate = existing.indexOf(firstChar, candidate + 1);
}
return existing + incoming;
}