Skip to content

perf: coalesce streamed deltas and render streamed replies incrementally - #329

Merged
sambitcreate merged 15 commits into
mainfrom
perf/streaming-render
Oct 4, 2026
Merged

sambitcreate merged 15 commits into
mainfrom
perf/streaming-render

Conversation

@sambitcreate

@sambitcreate sambitcreate commented Oct 4, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Batched streaming (MAIN-30, MAIN-31): streamed deltas are coalesced per renderer document in a new generation-delta-coalescer.ts. Terminal output is batched too, with history capping deferred.
  • Incremental reveal (UI-11/12): streamed replies are parsed incrementally (813 → 27 ms), and open code fences are highlighted later.
  • Fewer re-renders:
    • Settled transcript rows are memoized and the ScrollArea observer is stable (UI-10/13).
    • Split-view and workspace context values are memoized (UI-21).
  • Partial:
    • One frozen runtime event envelope is shared (MAIN-35).
    • Local voice PCM is decoded with one bulk copy (MAIN-34).
    • Serialized tool sizes are reused (MAIN-18).

Test plan

  • The coalescer, terminal, reveal-parse and transcript suites.
  • Type-check and lint.

Flaky tests

Part of the October optimization pass. Finding IDs refer to docs/performance/optimization-audit-2026-10-03.md (#320). The branch's .memory/ note has per-finding rationale.

🤖 Generated with Claude Code

sambitcreate and others added 9 commits October 3, 2026 16:08
Text and reasoning deltas for renderer-document owners are merged per
stream over a 16 ms window (or 16K chars) and flushed before any other
notification for the stream, so tool, timeline, status and terminal
events keep their order. Resets and paired-device/headless owners are
unchanged, and the run journal still records every delta.

Terminal sync skips the 1 MB slice while the projection is under its cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Pty chunks within 8 ms (or 64K chars) reach the renderer as one
terminal:data message with a monotonic sequence; snapshot and exit flush
pending output first so replay and live data never overlap or reorder.
The replay tail and persisted history are appended in amortized O(1)
and trimmed only when they double, on read, or on the debounced write.
Local-server detection skips the regex scan unless a URL scheme is near.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rea observer (UI-10, UI-13)

Settled rows render through a memoized SettledMessageRow so a streaming
frame no longer re-renders every prior message. ScrollArea's measuring
effect depends on whether a toolbar or footer exists rather than on the
JSX elements, so the ResizeObserver is no longer torn down every render.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…nce highlighting (UI-11, UI-12)

Blocks before the last top-level blank line can no longer change, so the
reveal parser keeps them and reparses only the open tail. A still-open
code fence renders as plain code and is highlighted once it closes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… queue (MAIN-35)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…MAIN-18)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

Closing a streamed code fence now drops keyboard focus from its Copy code button. One confirmed regression is detailed inline.

Reviewed changes Reviewed all 24 changed files, streaming lifecycle call paths, and the iOS/Android delta consumers.

  • Delta delivery: Local renderer text/reasoning deltas are coalesced while journal recording and remote/headless delivery remain per-delta.
  • Terminal output: PTY output is batched with snapshot/exit flushing, deferred replay/history capping, and a browser URL-scan fast path.
  • Transcript rendering: Settled rows and contexts are memoized, ScrollArea observers are stabilized, parsing becomes incremental, and open-fence highlighting is deferred.
  • Main-process hot paths: PCM decoding uses a bulk copy, runtime observers share a frozen queued envelope, and static context estimates reuse serialized tool sizes.
  • Validation: All 323 focused tests, npm run type-check, and npm run lint passed. A mounted Chromium check reproduced the focus regression; native builds and full Electron E2E were not run on this Linux runner.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

Comment on lines +146 to +150
{unit.openCode ? (
// Highlight once the fence closes instead of on every streamed line.
<CodeBlock code={unit.openCode.code} lang={unit.openCode.lang} plain />
) : (
<MarkdownContent content={unit.text} richLinks={richLinks} />

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve the code-block control when its fence closes

If a keyboard user focuses Copy code while a fence is streaming, the closing-fence delta switches this subtree from CodeBlock to MarkdownContent, unmounting the focused button and dropping focus to document.body. The previous always-MarkdownContent path preserved that button, so normal generation now interrupts keyboard copying/navigation even though the equivalent control remains visible.

Technical details
# Open-to-closed code fences lose control identity

## Affected sites
- `renderer/components/streaming-markdown-reveal.tsx:146-150` replaces the root component type when `openCode` disappears.
- `renderer/lib/streaming-reveal.ts:309-330` removes `openCode` once the closing fence becomes stable.
- `renderer/components/code-block.tsx:41-45` owns the focused Copy code button inside the replaced subtree.

## Reproduction
1. Mount `StreamingMarkdownReveal` with reduced motion enabled and content "```ts\nconst answer = 1;\n".
2. Focus its Copy code button.
3. Append another code line: the original button stays connected and focused.
4. Append "```\n": the original button disconnects and `document.activeElement` becomes `document.body`; a replacement Copy code button exists.

A mounted Chromium harness confirmed this. Updating the prior `MarkdownContent` path with the same canonical fenced-code source preserves its original focused button.

## Required outcome
- Keep the same code-block/control subtree mounted across fence closure while enabling highlighting, or otherwise preserve the focused control without stealing outside focus.
- Extend mounted behavioral coverage to verify that keyboard focus survives open-fence growth and closure.

## Suggested approach
- Keep one rendering path for a code fence and toggle its highlighting behavior instead of replacing `CodeBlock` with a different component root.

sambitcreate and others added 2 commits October 4, 2026 03:57
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@very-hermes-bot

very-hermes-bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

Hermes Review Bot

Confidence: 5

Engine: agy/gemini-3.8-flash-high
Review mode: full
Head: 61357326fbcb2c3e43eb82678e25d3ff61d81697
Generated: 2026-10-04T15:23:46+00:00
Reviews: 1

Summary

Coalesces streamed LLM text and reasoning deltas within a 16 ms / 16 KB window per renderer document, batches PTY output in 8 ms / 64 KB windows, and shifts terminal scrollback and history capping to a lazy threshold. In the renderer, incremental reveal parsing skips reparsing settled blocks prior to the last closed top-level blank line, unclosed code fences render as unhighlighted plain text until closed, settled transcript rows are memoized in MessageList, and layout observer dependencies are stabilized. A frozen runtime event envelope is shared across observer drains, voice PCM Float32 decoding uses an aligned buffer copy, and serialized tool sizes are cached via a WeakMap. Maintainers should double-check the merge conflict resolution in scripts/ci-test-registry.json, where duplicated build prerequisites cause redundant native compilation in every CI run.

Confidence Score: 5/5

Every changed implementation and test file across the main process, renderer, and build scripts was traced end-to-end against origin/main and verified against IPC and CI execution contracts.

📁 Important Files Changed
  • main/services/generation-delta-coalescer.ts & .test.ts: Buffers and coalesces consecutive chat:delta and chat:reasoning-delta notifications for local renderer documents.
  • main/services/llm-client.ts: Routes local renderer stream deltas through the coalescer, flushing before non-delta events or upon termination while bypassing remote/headless clients.
  • main/services/terminal.ts & terminal-history.ts: Batches PTY output into 8 ms / 64 KB terminal:data messages with monotonic sequence numbers and defers history line/char capping until read or disk persist.
  • renderer/lib/streaming-reveal.ts & streaming-reveal.test.ts: Implements StreamingRevealParser to incrementally reparse only the uncommitted tail after the last top-level closed blank line and extracts openCode for open code fences.
  • renderer/components/streaming-markdown-reveal.tsx & code-block.tsx: Uses the incremental parser and renders open code fences as plain unhighlighted code blocks until closed.
  • renderer/components/message-list.tsx: Memoizes settled transcript rows in SettledMessageRow and avoids querying DOM elements during streaming renders when subagent chip focus is unbroken.
  • renderer/components/ui.tsx: Stabilizes ResizeObserver dependency arrays in ScrollArea and memoizes SplitContext.
  • main/handlers/voice-codec.ts: Optimizes pcmToFloat32 via aligned ArrayBuffer.slice bulk copy on little-endian architectures.
  • main/services/pi-runtime-events.ts: Applies deepFreeze to runtime event envelopes so the drain queue and caller can share instances without extra cloning.
  • main/services/generation-context.ts: Caches serialized tool schema sizes in a WeakMap.
  • scripts/ci-test-registry.json: Registers generation-delta-coalescer.test.ts into lane core-git, but inadvertently includes duplicated prerequisite and preserved blocks from a merge commit.

Findings

  • [P2 · logic] scripts/ci-test-registry.json:808 — Duplicate merge conflict blocks in scripts/ci-test-registry.json duplicate CI build prerequisites → commented inline
📊 Sequence Diagram
sequenceDiagram
    participant Provider as Provider / Agent
    participant LLMClient as LLMClient (sendGeneration)
    participant Coalescer as GenerationDeltaCoalescer
    participant Window as Renderer WebContents

    Provider->>LLMClient: token delta ("Hello ")
    LLMClient->>Coalescer: push("s1", "chat:delta", "Hello ")
    Note over Coalescer: Starts 16ms window timer
    Provider->>LLMClient: token delta ("world!")
    LLMClient->>Coalescer: push("s1", "chat:delta", "world!")
    Note over Coalescer: Appends delta to current batch

    alt Timer expires (16ms)
        Coalescer->>Window: send("chat:delta", { streamId: "s1", delta: "Hello world!" })
    else Non-delta event arrives (e.g. chat:tool or chat:done)
        Provider->>LLMClient: tool_execution_start or done
        LLMClient->>Coalescer: flush("s1")
        Coalescer->>Window: send("chat:delta", { streamId: "s1", delta: "Hello world!" })
        LLMClient->>Window: send("chat:tool", ...) or send("chat:done", ...)
    end
Loading

Machine-Readable Findings

[
  {
    "file": "scripts/ci-test-registry.json",
    "start_line": 808,
    "end_line": 964,
    "severity": "P2",
    "comment_type": "logic",
    "confidence": 0.95,
    "title": "Duplicate merge conflict blocks in scripts/ci-test-registry.json duplicate CI build prerequisites",
    "mechanism": "Merge conflict resolution accidentally retained duplicate blocks for 13 build prerequisites and 8 preserved commands, causing run-ci-tests.mjs to execute all native build prerequisites twice sequentially during CI.",
    "repair": "Remove the duplicate prerequisite and preserved entries in scripts/ci-test-registry.json.",
    "id": "6c3987e0995aad14"
  }
]

Last reviewed commit: 61357326fbcb
Reviews (1) · Comment /hermes review to trigger a new review · /hermes review full for full re-review

sambitcreate and others added 3 commits October 4, 2026 05:58
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	package.json
#	renderer/components/code-block.tsx
#	scripts/ci-test-registry.json

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The latest merge duplicates CI build prerequisites, causing native helpers and the VCC worker to be built twice before tests.

Reviewed changes Reviewed the latest merge against the previously reviewed state, with the full PR diff as context.

  • Integrated lazy highlighting: Preserved the streaming plain guard alongside main's lazy grammar loading and grammar-version updates.
  • Preserved test registration: Kept the coalescer test and incorporated main's six additional serial-suite tests without dropping existing commands.
  • Merged CI registry definitions: Inspected the prerequisite and preserved-command conflict resolution and reproduced duplicate prerequisite entries in the actual execution plans.
  • Validated the integration: Passed all 54 focused CI registry/runner, highlighting, Markdown math, and streaming parser tests, plus npm run type-check.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

"reason": "Native file-I/O fault-injection regression helper."
},
{
"id": "worktree-remover-build",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Remove duplicate prerequisite definitions from the merge

This merge inserts a second copy of the build prerequisites, and buildPlan retains both entries for each selected ID rather than deduplicating them. The actual core-git plan now runs 8 prerequisite commands instead of 4, and runtime-subagents runs 22 instead of 11, recompiling the same native helpers and rebundling VCC twice before tests.

Technical details
# Duplicate registry definitions repeat build work

## Affected sites
- `scripts/ci-test-registry.json:806-962` duplicates prerequisite definitions already present elsewhere in the same array, including `worktree-remover-build`, the subagent helper builds, `vcc-build`, and the worktree file-I/O builds.
- `scripts/ci-test-registry.json:1073-1184` also duplicates preserved-command definitions; those happen to be deduplicated by the runner's Map.
- `scripts/run-ci-tests.mjs:183-186` selects prerequisites with an array filter, so both definitions survive.
- `scripts/run-ci-tests.mjs:295-308` executes each selected prerequisite serially.
- `scripts/native-c-build-core.mjs:98-112` invokes the compiler on every call, without a freshness check.

## Verification
Calling the real `buildPlan(readRegistry(), parseArguments(["--lane", lane]))` returns 8 prerequisites for `core-git` (4 unique IDs), 22 for `runtime-subagents` (11 unique IDs), and 2 for `renderer-other` (1 unique ID). All 29 existing CI policy/registry/runner tests still pass because registry ID validation uses Sets and does not reject duplicate definitions.

## Required outcome
- Retain exactly one definition per prerequisite and preserved-command ID while preserving the coalescer test's lane registration.
- Extend behavioral registry/runner coverage so a duplicate definition cannot silently schedule the same build twice.

@very-hermes-bot very-hermes-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inline review — 1 finding(s) anchored to the diff. See the pinned summary comment for the overview.

Comment on lines +806 to +815
{
"id": "worktree-file-io-test-build",
"command": [
"node",
"scripts/build-worktree-file-io.mjs",
"--test"
],
"reason": "Native file-I/O fault-injection regression helper."
},
{

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2 · logic] Merge conflict resolution duplicated prerequisites and preserved suites in CI registry
Confidence: 0.95

Commit b8dfedc resolved a merge conflict in scripts/ci-test-registry.json by concatenating conflicting hunks. This added 270 redundant lines duplicating all 13 build prerequisites and 8 preserved suites. When run-ci-tests.mjs filters registry.prerequisites, duplicate entries in the array cause every prerequisite native build step to run twice in CI.

Repair: Remove the duplicated prerequisite block (lines 806 to 965) and duplicated preserved entries (lines 1073 to 1185) from scripts/ci-test-registry.json so each prerequisite and preserved task is declared exactly once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues found in this merge delta. Existing review threads remain unresolved, so this is not an approval.

Reviewed changes Reviewed the changes from b8dfedc to 6135732, with the complete PR diff as context.

  • Integrated durability coverage: Added main's durable-fs.test.ts to the serial and coverage commands without dropping existing tests.
  • Preserved coalescer registration: Retained the coalescer test in the serial command and confirmed both tests are assigned to the core-git CI lane.
  • Validated the integration: Passed all 43 focused CI policy, registry, runner, durability, and coalescer tests. Full application, native, Electron E2E, type-check, and lint suites were not rerun for this test-registration-only delta.

Pullfrog  | Fix it ➔ | View workflow run | Using gpt-6.1-sol | 𝕏

@very-hermes-bot very-hermes-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inline review — 1 finding(s) anchored to the diff. See the pinned summary comment for the overview.

Comment on lines +808 to +964
{
"id": "worktree-file-io-test-build",
"command": [
"node",
"scripts/build-worktree-file-io.mjs",
"--test"
],
"reason": "Native file-I/O fault-injection regression helper."
},
{
"id": "worktree-remover-build",
"for": [
"core-git",
"runtime-subagents",
"renderer-other",
"worktree-remover-native"
],
"command": [
"npm",
"run",
"build:worktree-remover"
],
"reason": "Root pretest builds the managed-worktree helper once per job."
},
{
"id": "worktree-remover-test-build",
"for": [
"worktree-remover-native"
],
"command": [
"node",
"scripts/build-worktree-remover.mjs",
"--test"
],
"reason": "Native worktree remover test binary."
},
{
"id": "bot-inbox-writer-build",
"for": [
"runtime-subagents"
],
"command": [
"npm",
"run",
"build:bot-inbox-writer"
],
"reason": "pretest:bots production helper build."
},
{
"id": "bot-inbox-writer-test-build",
"for": [
"runtime-subagents"
],
"command": [
"node",
"scripts/build-bot-inbox-writer.mjs",
"--test"
],
"reason": "pretest:bots test helper build."
},
{
"id": "subagent-run-store-build",
"for": [
"runtime-subagents",
"subagent-file-mutator-native"
],
"command": [
"npm",
"run",
"build:subagent-run-store"
],
"reason": "pretest:subagents production helper build."
},
{
"id": "subagent-run-store-test-build",
"for": [
"runtime-subagents",
"subagent-file-mutator-native"
],
"command": [
"node",
"scripts/build-subagent-run-store.mjs",
"--test"
],
"reason": "pretest:subagents test helper build."
},
{
"id": "subagent-file-mutator-build",
"for": [
"runtime-subagents",
"subagent-file-mutator-native"
],
"command": [
"npm",
"run",
"build:subagent-file-mutator"
],
"reason": "pretest:subagents production helper build."
},
{
"id": "subagent-file-mutator-test-build",
"for": [
"runtime-subagents",
"subagent-file-mutator-native"
],
"command": [
"node",
"scripts/build-subagent-file-mutator.mjs",
"--test"
],
"reason": "pretest:subagents test helper build."
},
{
"id": "subagent-shell-runner-build",
"for": [
"runtime-subagents"
],
"command": [
"npm",
"run",
"build:subagent-shell-runner"
],
"reason": "pretest:subagents production helper build."
},
{
"id": "subagent-shell-runner-test-build",
"for": [
"runtime-subagents"
],
"command": [
"node",
"scripts/build-subagent-shell-runner.mjs",
"--test"
],
"reason": "pretest:subagents test helper build."
},
{
"id": "vcc-build",
"for": [
"core-git"
],
"command": [
"npm",
"run",
"build:vcc"
],
"reason": "pretest:vcc builds the VCC worker before its tests."
},
{
"id": "worktree-file-io-build",
"command": [
"npm",
"run",
"build:worktree-file-io"
],
"reason": "Managed worktree lifecycle tests require the confined native file-I/O helper."
},

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2 · logic] Duplicate merge conflict blocks in scripts/ci-test-registry.json duplicate CI build prerequisites
Confidence: 0.95

Merge conflict resolution accidentally retained duplicate blocks for 13 build prerequisites and 8 preserved commands, causing run-ci-tests.mjs to execute all native build prerequisites twice sequentially during CI.

Repair: Remove the duplicate prerequisite and preserved entries in scripts/ci-test-registry.json.

@sambitcreate
sambitcreate merged commit 8367b0a into main Oct 4, 2026
25 checks passed
@sambitcreate
sambitcreate deleted the perf/streaming-render branch October 4, 2026 15:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants