Skip to content

Long chat replies no longer freeze while they stream - #35462

Merged
brennanb2025 merged 203 commits into
mainfrom
brennanb2025/nc-perf-text-cadence-2
Nov 25, 2026
Merged

brennanb2025 merged 203 commits into
mainfrom
brennanb2025/nc-perf-text-cadence-2

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Before: while Claude or Codex wrote a long reply in a chat, the reply often sat still for many seconds and then jumped ahead. The longer it got, the longer each wait, up to a minute. Typing in the message box could also lag while the reply streamed.

Now: the reply grows smoothly, a few words at a time, however long it gets. New words fade in briefly. Typing and scrolling stay responsive while it streams. If the agent pauses, the text written so far shows at once and survives a reload.

Files Added Deleted Net
Test 37 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3664 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​3664
Prod 142 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​5364 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1041 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​4323

What Changed

As the user sees it:

  • Claude replies and thinking, and Codex replies and reasoning, update on screen about every 60 ms while they stream, instead of waiting for the next save. Codex plans and command output update as they do today.
  • Opening or reconnecting to a chat mid-reply shows its text and keeps streaming.
  • Only the last few hundred milliseconds of new words fade in; older text is drawn plainly.

The mechanism:

  • Showing and saving are separate. The app already had a live-text path for provider timelines, and this uses it. Every 60 ms, the newest reply text is published as a live row at the position its last save put it. Nothing is written to disk for that.
  • When saves happen: on the first text, on the existing 12.5% growth rule, after a second of quiet, and when a reply or turn ends. A slow trickle of text can't cause a save per word.
  • Who gets live text:
    • It goes only to chats someone has open, and only to apps that can take just the new text. Phone apps from before text appends (older than v0.0.65) keep updating on saves, as today; later phone builds get the live text too, and redraw their transcript once per update.
    • The desktop now asks its own local host for appends, as remote desktops already did: a streaming reply arrives as its new text, and a command-output save carries only the new output. Command output still updates on its saves.
    • A remote desktop or a phone gets just the new text, not the whole reply again.
    • Saved frames carry the newer live text, so a save never makes visible text shrink.
  • On the client: a streamed update replaces its row in place, without rescanning the history.
  • Drawing the reply:
    • The reveal steps on the frame clock, at most every 60 ms. Every streaming reply in a window shares one clock and one time budget, and at most one reply steps per frame. A step waits while keyboard or pointer input is pending.
    • It slows down only by each step's own render time: a reply that is slow to draw (a long reply with footnotes is redrawn whole) takes at most 1/10 of the time between steps on desktop and half on a phone, leaving the rest to typing and scrolling. Unrelated work doesn't slow it.
    • Between steps it sleeps on a timer instead of waking every frame. Steps follow the display's measured frame rate, so 30 Hz and 50 Hz displays step as often as 60 Hz ones.
    • A minimized window or backgrounded phone holds streaming text until it is shown, then draws it at once without a fade.
    • The word fade runs on the compositor.
    • A selected equation stays selected when a streaming redraw replaces its element.
  • Compatibility: no schema or wire-format change. Older desktop and phone clients already treat a row with an equal revision as a replacement.

Why

Before, the screen updated only on saves, and saves are spaced by growth so long replies don't rewrite the database constantly. Tying the screen to saves made long replies freeze. Separating them keeps disk writes the same as before and lets the screen follow the text. The reveal backs off by how long its own steps take to draw, not at a fixed rate, so slow-to-draw replies can't starve input. Fixed rates either froze those replies or made typing lag.

Linked Issue

N/A: maintainer change, no pre-existing issue.

Visual Proof

(screenshot removed: contained real product data)

(screenshot removed: contained real product data)

Testing

  • I manually tested these changes locally (isolated QA copies on macOS and Windows, real Claude and Codex runs, and benchmark streams)
  • Automated tests added/updated: live text reaches only viewers, as its new text; a growing reply is not re-formed each window; a reloaded view starts from the newest streamed text; the fade covers only the newest words
  • Every added test fails without this change and avoids the test anti-patterns

Platforms: macOS (M4 MacBook Air) and Windows 11 (isolated QA copies). Linux is covered by CI only. Phones were checked through the shared reveal and the bounded live frames.

Measured on macOS, against main:

  • Disk writes are the same as main: same number of saves and the same bytes written for replies of 32–256 KiB.
  • Gaps between screen updates: main went up to 65 s with no update at 256 KiB; with this change every gap is 60 ms.
  • One long reply, newest text on screen:
    • app CPU is about halved, and GPU-process CPU is about a third of main's;
    • frames over 50 ms drop from about 330 to about 4;
    • typing p95 drops from 191 ms to 38 ms.
  • Long reply with footnotes (redrawn whole each step), median of 3 interleaved runs on this exact head against main:
    • typing p95 116 ms against 121 ms (the ranges overlap);
    • long tasks 9.1 s against 12.4 s;
    • the text moves in larger pieces: visible-update gap p95 2.85 s against 0.62 s; worst gap 3.7 s against 5.7 s.
  • Plain long reply: worst gap 0.42–0.46 s against main's 6.2 s freeze, with typing the same.
  • Chat with 21,000 saved rows while a long reply streams, 3 interleaved runs each against main:
    • long tasks 385 ms against 623 ms;
    • typing p95 21 ms against 35 ms;
    • frame times the same;
    • heap after a forced garbage collection 118 MB against 162 MB.
  • On Windows 11 (desktop, 3–4 interleaved runs each against main, real Claude for the live checks):
    • long reply with footnotes: pauses of 0.5 s or more drop from about 79% of the stream to about 2%; worst gap 1.1 s against 6.4–6.8 s; long tasks 1.8–2.0 s against 4.9–5.6 s;
    • typing p95 with one streaming pane is within noise of main (37–38 ms against 33–38 ms), and with several panes streaming at once it is about half of main's: 45–51 ms against 95–106 ms at 2 panes, 75–77 ms against 166–170 ms at 4;
    • a selected equation stays selected while its reply streams (3 of 3; main loses it in 3 of 3).
  • Minimized window: nothing renders while it is hidden. The first frame after it is shown has exactly the text received so far.

Known difference and follow-up

  • Long replies with footnotes, reference links or raw HTML update less often than on main (about every 2.9 s at p95 instead of 0.6 s). The whole reply is parsed again on each step, so the reveal spaces its steps out to keep typing and scrolling responsive. Typing and blocked time are still better than main on those replies. Plain replies are unaffected.
  • Follow-up: parse those replies off the main thread, so they can step as often as plain replies.
  • Reopening a thought or reply mid-stream: when a slow-to-draw reply has fallen back to showing only its saves, collapsing and reopening it while it still streams can show a newer, correct prefix of its text before its next save lands.
  • Reloading a window mid-reply: the reply can come back showing its last save, up to one save behind what was on screen, and catches up within about 0.3 s (seen with Codex on Windows in 2 of 3 tries). Main shows the last save on reload too.
  • Very long live text: a stream offers at most 1M characters of live text, so it always fits inside each viewer's 8 MB live-text cap. Replies past that update on their saves, as on main.

Performance

This adds work on a repeated trigger, bounded as follows:

  • Live text: about one publication every 60 ms per streaming reply, only while someone has that chat open, only to apps that can take just the new text, and at most 1M characters per stream (so it always fits each viewer's 8 MB live-text cap). Nothing is written to disk for it. Saves stay on the 12.5% growth rule, plus one quiet save and the end of the reply.
  • Per window on the host (512K-character reply, 3 viewers): about 0.24 ms at p50 and 1.1 ms at p95, and 344 bytes on the wire per viewer.
  • On screen: the reveal steps at most every 60 ms on the frame clock and spaces steps out by their own render time (at most 1/10 of the time between them on desktop, half on a phone), capped at 6 s. Projections over loaded history that read no reply text reuse their last result while a reply streams.
  • Measured against main on an M4 MacBook Air: see Testing. Long replies with footnotes are the known difference above.

Risk

Level: Medium.

  • Riskiest part: the live row and the saved row for the same reply have to agree. If they didn't, a reply could briefly show older text after a save, or a phone could miss a step until the next save.
  • Footnote replies: the text lands in larger pieces every few seconds (see Known difference).
  • Saved data: nothing changes on disk or on the wire.
  • Backing it out: a plain revert.

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Security: no change. Cross-platform: the frame clock, timers and CSS work the same on all platforms. Remote: remote desktops get only the new text. Mobile: phones use the same shared reveal and bounded live frames. Backwards compatible with older clients. Performance: see Testing.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@greptile-apps

greptile-apps Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 4/5

[High impact] The PR changes saved text cadence and durability across native-chat provider streams.

Fix the extra argument in the history test before merging.

Findings

  1. P1 Extra argument breaks type checking ▶

Summary

Streamed assistant and reasoning text now use a 400 ms elapsed-time gate instead of percentage growth.

  • Assistant and reasoning streams save full text snapshots on an elapsed-time cadence.
  • Codex saves pending text before stream limits can evict it.
  • Text-only assistant and reasoning revisions can use NORMAL journal durability.
  • Claude activity updates now come from its context facts component.

One new helper call blocks type checking. brennanb2025 acknowledged full-copy storage growth and deferred its fix to #36024 and #36053, with no interim shipping approved.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Provider text arrives] --> B[Keep full text]
  B --> C[60 ms window]
  C --> D{400 ms since accepted save?}
  D -->|Yes| E[Try save and publish]
  D -->|No| F[Keep tail until more text or a barrier]
  G[Stop, completion, or explicit flush] --> E
  E --> H[Append journal snapshot]
Loading

Reviews (10) · Last reviewed commit: "Merge main to include the CI test fix" · Reviewed by Greptile

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The changes add time-based admission for streamed text checkpoints across Claude, Codex, and provider timeline streams. Persistence callbacks report whether appends and publications were accepted. Codex stream state trimming now preserves buffered content when persistence is refused, and pending patches are capped. Journal writes track eligible assistant and reasoning text rows and can blank prior text while retaining the latest revision. Tests cover timed writes, refusal and retry behavior, journal reopening, and downstream projections.

Merge Risk: Minimal · previous review 82f18

Streamed text now saves on a fixed cadence. The final text is still preserved on Stop or completion, and the earlier concerns about leftover reasoning routes and skipped finalizers no longer apply. Normal CI and live-agent checks should still finish before merge.

Pre-merge checks: Passed 3 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description is detailed and covers the ELI5, what changed, why, testing, performance, and risk sections of the template. It has the required structure, but several required items are incomplete: t… 1. Link an actual issue in the Linked Issue section (replace 'Fixes #' and the N/A note), or confirm with maintainers that no issue is required. 2. Replace the removed screenshots in Visual Proof with working BEFORE and AFTER attachments (v…
Passed Passed checks: 3 passed

Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title states the main user-facing change: long chat replies no longer freeze while streaming. The raw summary and objectives show the change moves streamed text checkpointing to a 400 ms elapsed-t…
Full details: Title check

Explanation

The title states the main user-facing change: long chat replies no longer freeze while streaming. The raw summary and objectives show the change moves streamed text checkpointing to a 400 ms elapsed-time cadence and publishes live text every 60 ms, which addresses that freeze. The title is short, specific, and matches the changeset.

Full details: Description check

Explanation

The description is detailed and covers the ELI5, what changed, why, testing, performance, and risk sections of the template. It has the required structure, but several required items are incomplete: the Linked Issue section says N/A for a maintainer change, while the template says there should always be one; the Visual Proof section has only screenshot-removed placeholders and no BEFORE/AFTER visual proof, although the UI behavior changed; the Risk level is set to Medium, which is filled in; the AI Disclosure section is empty; the Review section is empty; and the Checklist items 'This PR is small and focused' and 'pnpm lint/typecheck/test/build pass' are unchecked. The Testing section does not explicitly state which tests were run beyond the author's report of 284 passing tests. The Performance section is substantive and does not use the one-line format, which is acceptable.

Resolution

  1. Link an actual issue in the Linked Issue section (replace 'Fixes #' and the N/A note), or confirm with maintainers that no issue is required. 2. Replace the removed screenshots in Visual Proof with working BEFORE and AFTER attachments (video preferred), since the change alters streaming UI behavior. 3. Fill in the AI Disclosure section, or state that it does not apply. 4. Fill in or remove the empty Review section. 5. Confirm that pnpm lint, typecheck, test, and build pass locally, and check the boxes accordingly, or note that CI will cover them. 6. Review the 'small and focused' checklist item. The PR touches about 40 files and 3,400+ production lines, so the item should be unchecked or the scope explained.
Finishing Touches

Resolve merge conflicts

  • Resolve merge conflict in branch brennanb2025/nc-perf-text-cadence-2
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 589054f8-f14d-4226-8caa-3f5624bb21ee
Commits

Reviewing files that changed from the base of the PR and between 79d6b68 and 82f1859.

Files selected for processing: 16

  • src/main/claude/claude-checkpoint-test-support.ts
  • src/main/claude/claude-context-facts.ts
  • src/main/claude/claude-streamed-text-checkpoints.test.ts
  • src/main/claude/claude-streamed-text-checkpoints.ts
  • src/main/claude/claude-streamed-thinking.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-structured-reasoning.test.ts
  • src/main/codex/codex-structured-item-stream-bounds.ts
  • src/main/codex/codex-structured-item-streams.ts
  • src/main/codex/codex-structured-journal-translation-streams.test.ts
  • src/main/codex/codex-text-cadence-pressure.test.ts
  • src/main/native-chat/agent-session-timeline/provider-timeline-assembler-refusal.test.ts
  • src/main/native-chat/agent-session-timeline/provider-timeline-assembler-streams.test.ts
  • src/main/native-chat/agent-session-timeline/provider-timeline-text-streams.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.ts
  • src/main/native-chat/agent-session-wire/agent-session-text-cadence.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5be73157-8d85-44d4-a632-6f2418c8f9dd
Commits

Reviewing files that changed from the base of the PR and between 552691f and d823e1d.

Files selected for processing: 19
  • src/main/claude/claude-streamed-text-checkpoints.test.ts
  • src/main/claude/claude-streamed-text-checkpoints.ts
  • src/main/claude/claude-streamed-thinking.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/codex/codex-structured-item-streams.ts
  • src/main/codex/codex-structured-journal-sink.ts
  • src/main/codex/codex-structured-journal-translation-settlement.test.ts
  • src/main/codex/codex-structured-journal-translation-streams.test.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.spec.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.ts
  • src/main/native-chat/agent-session-journal/journal-streamed-text-revision.test.ts
  • src/main/native-chat/agent-session-journal/journal-streamed-text-revision.ts
  • src/main/native-chat/agent-session-journal/journal-text-predecessors.ts
  • src/main/native-chat/agent-session-timeline/provider-timeline-assembler-streams.test.ts
  • src/main/native-chat/agent-session-timeline/provider-timeline-text-streams.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.ts
  • src/main/native-chat/agent-session-wire/agent-session-text-prefix.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-item-publication.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 2 remain after this review.

@coderabbitai coderabbitai 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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Minor · Gate predecessor blanking on structural equality. · journal-text-predecessors.ts:65-96

src/main/native-chat/agent-session-journal/journal-text-predecessors.ts:65-96
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Gate predecessor blanking on structural equality.

JournalRowWriter stages every inserted row. The structural comparison in isJournalStreamedTextRevision() only selects the fsync mode.

appendItem() can create a higher-revision row with text-only blocks and changed metadata such as ownerFence, executionOwner, turnScope, linkage, or body fields. JournalTextPredecessors.stage() checks only role and revision before updating the predecessor with blank text. This can erase the previous revision’s text for a non-text-equivalent revision.

Add a structural-equality gate to stage(). Reuse the normalized comparison used by isJournalStreamedTextRevision().


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d817adce-feba-4653-90e2-859dcb4631d3
Commits

Reviewing files that changed from the base of the PR and between d823e1d and b6271c4.

Files selected for processing: 15
  • src/main/claude/claude-journal-turn-scope.test.ts
  • src/main/claude/claude-open-turn.ts
  • src/main/claude/claude-streamed-text-checkpoints.test.ts
  • src/main/claude/claude-streamed-text-checkpoints.ts
  • src/main/claude/claude-streamed-thinking.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/codex/codex-structured-item-stream-bounds.ts
  • src/main/codex/codex-structured-item-streams.ts
  • src/main/codex/codex-structured-journal-translation-streams.test.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.spec.ts
  • src/main/native-chat/agent-session-journal/journal-text-predecessors.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-item-publication.test.ts
  • src/main/runtime/orchestration/structured-worker-journal-page.test.ts
Files skipped from review as they are similar to previous changes: 2
  • src/main/native-chat/agent-session-journal/journal-row-writer.spec.ts
  • src/main/native-chat/agent-session-journal/journal-text-predecessors.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5ea1b33f-ac2e-4e8f-99c5-ba1dc773d9ee
Commits

Reviewing files that changed from the base of the PR and between b6271c4 and 97b19c2.

Files selected for processing: 44
  • src/main/acp/acp-history-journal-overlay.ts
  • src/main/claude/claude-checkpoint-import.test.ts
  • src/main/claude/claude-checkpoint-input.ts
  • src/main/claude/claude-checkpoint-intent.ts
  • src/main/claude/claude-checkpoint-test-support.ts
  • src/main/claude/claude-context-facts.ts
  • src/main/claude/claude-context-usage-test-support.ts
  • src/main/claude/claude-final-output-coverage.ts
  • src/main/claude/claude-journal-translator-contract.ts
  • src/main/claude/claude-journal-turn-scope.test.ts
  • src/main/claude/claude-message-journaling.ts
  • src/main/claude/claude-provisional-row-corrections.ts
  • src/main/claude/claude-stream-json-connection-close.test.ts
  • src/main/claude/claude-stream-json-connection.ts
  • src/main/claude/claude-stream-json-output.ts
  • src/main/claude/claude-streamed-text-checkpoints.test.ts
  • src/main/claude/claude-streamed-text-checkpoints.ts
  • src/main/claude/claude-streamed-thinking.ts
  • src/main/claude/claude-structured-event-delivery.ts
  • src/main/claude/claude-structured-journal-translation-subagents.test.ts
  • src/main/claude/claude-structured-journal-translation.test.ts
  • src/main/claude/claude-structured-journal-translation.ts
  • src/main/claude/claude-structured-resume-point.ts
  • src/main/claude/claude-structured-session-close.test.ts
  • src/main/claude/claude-structured-session-close.ts
  • src/main/claude/claude-structured-session-exit-lifecycle.ts
  • src/main/claude/claude-structured-session-journal-control.ts
  • src/main/claude/claude-transcript-catch-up-test-support.ts
  • src/main/claude/claude-transcript-catch-up.ts
  • src/main/claude/claude-transcript-import-plan.ts
  • src/main/claude/claude-transcript-item-reader.ts
  • src/main/claude/structured/claude-structured-session-acquisition.ts
  • src/main/claude/structured/claude-structured-session-open.ts
  • src/main/native-chat/agent-session-journal/journal-step-writer.ts
  • src/main/native-chat/agent-session-timeline/provider-timeline-assembler-streams.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-child-exit.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-estimate.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-history-catch-up.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-output-drain.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-sink-operation.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-transition.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@coderabbitai coderabbitai 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.

Actionable comments posted: 1


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7cf60e25-fe00-42c1-9d64-336f81640c71
Commits

Reviewing files that changed from the base of the PR and between 97b19c2 and 79d6b68.

Files selected for processing: 10
  • src/main/claude/claude-checkpoint-input.ts
  • src/main/claude/claude-final-output-coverage.ts
  • src/main/claude/claude-streamed-text-checkpoints.ts
  • src/main/claude/claude-streamed-thinking.ts
  • src/main/codex/codex-structured-journal-streams-scaling.test.ts
  • src/main/native-chat/agent-session-timeline/provider-timeline-assembler-refusal.test.ts
  • src/main/native-chat/agent-session-timeline/provider-timeline-assembler-streams.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-work-test-support.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

@greptile-apps

greptile-apps Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Comments Outside Diff

These findings could not be posted inline.

  • P1 Returning blocks lose their prefixes src/main/claude/claude-streamed-text-checkpoints.ts:125 ▶

    After 256 unfinished Claude streams, the coalescer evicts the oldest snapshot. If another delta arrives for that block, append() starts a new snapshot from only that delta, even though latestText retains the prefix. The next save overwrites the journal item with only the suffix. Seed returning streams from their retained text, or prevent unfinished streams from being evicted.

  • P1 Refused Claude saves disappear src/main/claude/claude-streamed-text-checkpoints.ts:107 ▶

    When the journal queue refuses a save, persist still advances checkpointLengths and returns no result to the coalescer. The coalescer marks the text clean, and later flush() skips it. finish() also drops the block even when its terminal save is refused. Reasoning or an interrupted answer without a later full body can disappear from history. Retain refused work until the sink accepts it, and retry when the queue drains.

  • P1 Paused replies stay frozen src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.ts:120 ▶

    When text arrives within 400 ms of the previous save and the provider pauses, the scheduled flush skips or consumes the update without scheduling its deadline. Claude, Codex, and timeline text can then stay hidden until another delta or lifecycle event arrives. Keep the update pending and schedule a wake for the remaining delay.

@brennanb2025

brennanb2025 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Review loop finished on 451d4da: all required checks pass, both independent reviewers agree, no open findings. Brennan still has to rule on how often long chats save (see below).

The problem. While an agent wrote a long reply, the reply could sit still for several seconds and then jump, because saves waited for the text to grow by a fixed share of its length. This PR saves reply text at most every 400 ms instead. A follow-up in this round removed two pieces of hidden work found by the native chat perf scan: Claude re-read the whole growing reply on every 60 ms window even when it then skipped the save, and running command or file-change output re-read and hashed everything printed so far on each save, only to keep a 16 KiB preview.

What changed in this round.

  • Claude checks the 400 ms gate before touching the reply text. At 1,000 windows of a 128 KB reply, text joined goes from 64.1 MB to 9.2 MB and host time from 31.8 ms to 4.3 ms.
  • Running command and file-change rows are built from a running digest and the first 16 KiB. One command's running rows: 6.4 MiB of output 50.2 ms → 0.96 ms, 55 MB → 0.9 MB encoded. Saved rows are unchanged; a test checks the saved head, length and digest literally.
  • Seven main merges (main moved the Codex and session modules and kept deleting tests); work-count tests removed per main's AGENTS.md rule. The last two only follow main: one keeps main's deletion of rpc-capture-replay.test.ts, one moves the new delta digest/prefix modules beside the coalescer after refactor(main): group session lifecycle and journal modules by owner #38638 regrouped it; the newest keeps the PR's journal-page history test where main moved that file.

Verified. CI on 451d4da, all required checks. Locally: Node typecheck, changed-file lint and format, the PR's 22 test files (154 tests). Reviewers: Claude Opus (medium) and Codex (high) agreed on the plan, the implementation at 1dad5bd, and the first merge at bd2f716; Codex agreed on the test-only 1e9fe5a. The Claude reviewer fuzzed the new preview against the old whole-output form over 3,000 random streams (split emoji, multi-byte text, single chunks past 16 KiB, truncation): no differences. QA: the earlier real-run QA of Stop/restart and adopted Codex Plans carries from e3b680a; later shipped changes are performance-only and covered by tests and benchmarks.

Not fixed here (main behaviour, listed for follow-up).

  • A Codex command that completes without aggregatedOutput replaces its running preview with no output.
  • Whitespace-only reasoning re-joins its (whitespace) prefix each window.
  • Main's test-value audits deleted some tests this PR had added (event-sink failed-successor publish, row-writer native-failure retry, empty-start ordering, final-body replay).

For Brennan's review

  • Long chats: per saved reply revision the host spends 3 ms at 1,000 items, 64 ms at 10,000 and 249 ms at 55,000. This PR saves long replies about 4× more often than main, so on chats past ~10,000 items a streaming reply keeps the host busier (about 60% of the main thread at 55,000 items) until status reads stop scaling with chat length. Your call on shipping as is, holding, or stretching the save interval on slow chats is pending through the coordinator.
  • agent-session-delta-digest.ts: the running digest that keeps saved previews identical without re-reading output.
  • claude-streamed-text-checkpoints.ts: the gate moved ahead of the join.

@OrcaWin

OrcaWin commented Nov 8, 2026

Copy link
Copy Markdown
Collaborator

Closing: the streaming freezes on long replies are real, and the time-based checkpoint gate fixes them. But each checkpoint inserts a full-text row into journal_rows, and rows are removed only at epoch rollover, so stored size grows with the square of reply length, and a rate-capped version of the same design still writes about 80 times main's journal bytes for one long reply. Replay on session open pays for that too, including on remote hosts. The bundled changes (digest previews, Codex failure routing, reasoning durability, coalescer API) also need their own reviews. The fix needs a journal change first: streaming revisions replace the row in place, or streaming previews stay out of durable storage. A follow-up that changes the journal write path, with measured journal size and replay time, would be welcome.

@brennanb2025

brennanb2025 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Final independent performance review (Astra high), on the pushed head. This is a blocked verdict, not a waiver.

Two P1 performance findings block readiness. Linear retained SQLite data resolves the old journal-history problem, but does not resolve cumulative full-text rewrites or the downstream work newly exercised at 400 ms cadence.

Reviewed pinned 4939ff194f76c9f06c54373ec52a26d8840ae0d8..d5e0dc1bd505982ab2a346a22086000f76f996cf. I verified that benchmark candidate 99d6b664b8c3bd69a31e455857bc6067b6ed58f5 differs from final only by 76 deleted test lines. Its runtime measurements therefore apply to this production code.

  1. P1 — Fixed-cadence checkpoints amplify full-prefix processing and SQL rewrite volume quadratically with reply length.

    Introduced by unconditional text admission at codex-structured-item-streams.ts:117 and timed Claude persistence at claude-streamed-text-checkpoints.ts:95.

    Each admitted checkpoint joins the entire prefix, serializes it to estimate queue bytes, clones the body into the writer worker, and reads/rewrites the current item. The ordinary adapter route does not use the specialized text-snapshot write. See coalescer:102, sink estimate:9, and current-item persistence:113.

    Supplied raw evidence establishes:

    Reply Main saves Candidate saves Main logical UPDATE bytes Candidate logical UPDATE bytes
    32 KiB 46 207 419,182 3,764,549
    64 KiB 52 412 787,337 14,269,608
    128 KiB 58 822 1,522,443 55,507,383
    256 KiB 63 1,641 2,733,924 218,631,546

    These trigger-counter bytes measure cumulative logical row payload, not physical device writes. Nevertheless, doubling output approximately quadruples candidate rewrite bytes. At 256 KiB, saves increase 26× and logical UPDATE volume 80×.

    At the measured 400 B/s input rate, 100 simultaneous equivalent replies imply approximately 33.4 MB/s of logical UPDATE payload, versus 0.42 MB/s on base; 1,000 owners multiply those totals tenfold. Main-thread preparation and worker/database work are additional, separately unmeasured costs. The existing 16 MiB/stream cap does not make this repeated-prefix work proportional.

    Required proof after a remedy: preserve paused-tail durability and exact recovery while measuring cumulative preparation/write bytes across increasing lengths and concurrent owners. Merely showing bounded retained rows cannot close this finding.

  2. P1 — The faster save cadence amplifies history-wide renderer work and unrelated publication work.

    The introducing cadence changes above reach publishJournal:295. Each drained publication requests status projection, settlement checks, queue activity and journal observers.

    Desktop delivery reaches reducer:273, then history upsert:92: one changed reply scans and copies all H loaded items, followed by retention scanning. Snapshot equality occurs after this work.

    At 2.5 revisions/s, the upsert alone visits 2,500 / 25,000 / 137,500 rows/s for H=1k/10k/55k, per active read owner. One hundred active owners retaining 1k rows produce 250,000 visits/s; ten times that population produces 2.5 million. Larger H requires loaded/paged history: 55k database rows do not automatically mean 55k renderer rows. Hidden owners deactivate transport, so hidden chats should not be multiplied into this renderer count.

    Separately, ordinary publishJournal() defaults inputChanged=true; queue wiring:127 schedules queue admission even for a text-only checkpoint. Pending scheduling deduplicates concurrent requests, but not successive drained checkpoints. That permits 250 queue-drain admissions/s across 100 streaming owners despite unchanged input eligibility. Status projection also invalidates on the journal cursor before summary equality can suppress unchanged broadcasts.

    These mechanisms predate the PR; their amplified invocation rate is introduced by this PR. The measured host path also grows with corpus size:

    Items Main median ms/save Candidate median ms/save
    1,000 2.49 2.49
    10,000 8.79 8.84
    55,000 37.58 37.77

    Equal per-save cost does not absolve 26× more saves. Candidate cadence at 55k corresponds arithmetically to approximately 94 ms of measured-path elapsed time per second per streaming reply. This is neither main-thread CPU nor a concurrent-throughput measurement.

    Required proof after a remedy: exercise actual delivery at N/10N loaded history, verify localized updates avoid unrelated history/queue work, and measure the complete host publication path. Preserve ordering, queue freshness, status transitions and final flushes.

The storage harness faithfully reaches the production Codex translator, deferred sink, journal, and real SQLite writer/reader workers. Raw results confirm two retained items, no journal_rows writes, no legacy journal database, exact recovered text and correct turn placement. Candidate settled sizes are 724,992 → 864,256 → 1,138,688 → 1,695,744 bytes. This supports linear retained storage over the tested range. Five-trial candidate reopen medians remain approximately 124–126 ms.

The WAL result prevents an unconditional storage PASS.

  • Accelerated candidate WAL high-water is 18.16 → 43.21 → 113.65 → 135.07 MB. Live stored footprint grows superlinearly over the early sizes.
  • With 100 ms real pacing after each save, high-water is 4.17 → 4.22 → 4.28 → 4.43 MB.
  • The accelerated run compresses hundreds of simulated seconds into seconds of wall time. Draining the sink does not await asynchronous WAL checkpoint completion. Paced results demonstrate checkpoint recovery opportunity; they do not invalidate the accelerated observation.
  • The source gates subsequent writes around 32,768 WAL frames and coordinates truncation. journal_size_limit is not an instantaneous hard file-size ceiling; a transaction can cross the admission threshold.

Thus the old retained full-text history failure is not reproduced. However, under the unqualified “stored size” stop rule, the accelerated live DB/WAL result must remain BLOCKED. Narrowing that rule to settled database size would be an interpretation, not a measured universal pass. No multi-owner or blocked-reader storage run establishes the fleet behavior.

The host-cost harness verifies exact 1k/10k/55k item populations, with five runs and 200 measured revisions each. It mounts one AgentSessionSubscribers capture subscriber and one status-feed subscriber. It measures real elapsed time through save, worker acknowledgement, subscriber delivery and status publication.

It does not instantiate production StructuredAgentSessionClientDelivery. Consequently its subscriber lacks production work-frame/queue hooks; settlement, queue draining, completion consumers and journal observers are absent. Electron IPC, renderer reduction/rendering and mobile transport are absent too. Base samples span five replies versus two for candidate, so identical revision ordinals/text lengths are not paired. These are useful partial measurements, not the full requested downstream cost verdict. No main-thread CPU or event-loop profile was supplied.

The final-head listener census is:

Consumer/owner Selection and work Idle/load publication behavior
Desktop and remote/mobile chat subscribers Session-keyed; independent cursor capture and delivery. Capability-enabled transport can send suffixes; host preparation still handles full items. Zero settled text-timer frames; approximately 2.5 changed checkpoint frames/s/stream when caught up, plus lifecycle/activity traffic.
Desktop shared read owner Shared by session/target; visible activations own transport. Reducer updates loaded history before identity-based React notification. Finding 2. No measured renderer timings or complete frame census.
Status feed, renderer status stream and configured status sink Cursor/authority projection cache; summary equality suppresses unchanged broadcasts after projection. Up to checkpoint rate for genuinely changing summaries; zero unchanged-summary broadcasts. Raw harness totals include lifecycle/opening events, not classified steady-state rates.
Completion/prompt feed Reuses status projection; host attention delivery, host turn attention and RPC/renderer consumers compare request/prompt baselines. Ordinary text saves produce no completion edge. Omitted from benchmark.
Send-settlement waiters Session-scoped; capped at 64/session and 1,024 total; removed on completion, abort, timeout or close. Checks on publication while waiters exist; omitted from benchmark.
Queue drain Session-scoped scheduled-set deduplication and serialized admission. Text publications can schedule again after prior work drains; finding 2.
Journal observers Session-scoped registration and cleanup; publication invokes registered callbacks. Every publication hint; no direct in-tree registration found in the searched callers. Not mounted by benchmark.
ACP/Pi timeline live-text consumer Shared coalescer’s no-dueIn branch; reconstructs all live streams for publication. Shared approximately 16.7 Hz window restored; settled idle produces zero timer-origin frames. Full-live reconstruction predates this span.

Empty deltas now return before dirtying/scheduling. The earlier keyed-deadline scan and fragmented timeline-batching findings are repaired in final source. Forced barriers remain immediate; token-usage notifications no longer force Codex text saves, and thread barriers leave other threads’ deadlines intact. These are source-reviewed conclusions; I ran no tests.

All six scan questions were covered:

Question Disposition
Work before skip? Empty/growth/deadline gates precede joining; full-prefix preparation and downstream equality-after-work remain findings.
Ownership multiplies work? Provider-owned coalescers and shared renderer owners verified. Actual subscribers multiply delivery; queue/status work also runs without an open chat.
Which thread/storage layer pays? Joins, estimation and cloning on owning host; SQL in workers; reduction on renderer. CPU attribution remains unmeasured.
What grows/progresses? Quadratic cumulative prefix bytes and amplified H-row reduction block. Current-item retention and bounded event-tail pruning progress correctly in inspected source.
Execution host? Supplied measurements are M4Air/macOS Node development evidence. Remote routing inspected; Windows/WSL/Linux, slow storage and concurrent-host costs unmeasured.
Obsolete work stops? Forget, successful flush, mark-flushed and disposal cancel keyed timers; quiet streams settle. Refusals retain retry debt. Slow-subscriber backlog behavior remains unmeasured.

Touched regression classes: whole-message reprocessing/rewrites, history scans, repeated reads and publication fan-out are findings. Empty-input no-op publication and fragmented timers are repaired. Worker SQLite placement, visibility activation and keyed cleanup show no introduced defect. Protected streams bypass the ordinary 256-key cap; Claude auxiliary retention and uncapped subscriber promise-chain depth are pre-existing limitations. Their adverse-load behavior is not proven clean. The extracted prefix module adds no SDK/process startup mechanism. Trailing batching and lifecycle flushes are sound; that does not justify repeated-prefix cost.

Real QA supports the paused-tail repair, but the completeness claim needs correction: durable tails arrived at +142 ms Claude / +54 ms Codex; reported complete rendered tails were +564 / +461 ms, not both within 400 ms. Reload preserved both tails, and resumed outputs reportedly completed exactly. Claude used claude-opus-5-5 medium, not the requested [1m] variant. Simultaneous-thread live QA was not performed; the storage harness is single-threaded. Neither gap should be represented as completed coverage.

Evidence verdict: FAIL/BLOCKED for final head. Detector output [] does not override the performance claim or these findings. No edits, posts, delegation, installs, builds, app launches or tests were performed; worktree remained clean.

@brennanb2025

brennanb2025 commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

@OrcaWin — the measured answer to the closing objection is mixed, and this PR remains BLOCKED.

After merging main once, streaming saves update the current journal_items row. They do not write journal_rows or create the legacy journal database. Only small ID/revision metadata is appended to journal_events. Both refs retained two item rows in the fake-agent workload, and every reopen restored exact final text and placement. No schema change was needed.

On the M4Air, five trials at each reply length produced identical stored sizes/counts:

Reply Main / PR settled DB bytes Main / PR reply UPDATEs Main / PR live DB+WAL bytes before close
32 KiB 659,456 / 724,992 46 / 207 3,997,240 / 18,873,696
64 KiB 724,992 / 864,256 52 / 412 4,747,080 / 44,066,656
128 KiB 856,064 / 1,138,688 58 / 822 6,014,960 / 114,793,040
256 KiB 1,101,824 / 1,695,744 63 / 1,641 7,461,080 / 67,286,200

Settled storage is linear. However, full-prefix logical UPDATE payload totals 218,631,546 B at 256 KiB versus 2,733,924 B on main: about 80×, with roughly quadratic growth. These are logical payload bytes, not physical disk write counts. Accelerated saves reached a 135,074,232 B WAL high-water before page recycling; a separate one-trial control with 100 ms of real checkpoint opportunity per save kept WAL high-water near 4.4 MB. I cannot turn that control into an unconditional storage PASS. The accelerated live footprint meets the requested stop rule.

Reopen medians were 119.0–123.5 ms on main and 123.5–125.9 ms on the PR over the four lengths; the full table and min–max spreads are in the rewritten PR body. The host-save/subscriber/status seam measured 2.49 / 8.84 / 37.77 ms per PR revision at 1k / 10k / 55k items, versus 2.49 / 8.79 / 37.58 ms on main (five corpora × 200 revisions). More frequent saves still amplify those costs. The final independent performance scan found two P1 blockers: repeated full-prefix processing/writes, and amplified history-wide reduction plus unrelated publication work. The harness also omits production settlement/queue/completion consumers and renderer work, so its numbers are partial host evidence.

Scope is now only text checkpoint cadence: digest previews, Codex failure routing, reasoning durability changes and the broad coalescer API rewrite were dropped. No separate PRs were opened for them. Three fresh Claude/Codex repair passes left source correctness clean; the final measurement-aware performance verdict is FAIL/BLOCKED and is posted separately above.

Real Claude and Codex pauses both survived reload while the producer stayed suspended, and both resumed to exact 400-line replies. Durable tails landed at +142 / +54 ms from SIGSTOP; complete rendered tails at +564 / +461 ms. Claude used the available Opus 5.5 medium picker entry, so the requested [1m] variant was not covered. Simultaneous subthreads were not exercised live. Screenshots below show the paused Claude reply and paused Codex reply after reload; these demonstrate preserved text, not a sub-400 ms rendering guarantee.

(screenshot removed: contained real product data)

(screenshot removed: contained real product data)

All 25 local changed checks passed immediately before normal push. The one CI watch finished with 66 passed and zero failed; the previously reported repository-wide wire compatibility extraction issue was not changed here. QA ran on production-identical 99d6b66; final d5e0dc1 only deletes tests. The app stopped gracefully, configs were unchanged and the QA slot was released. This is not ready to merge, and no merge was attempted.

Benchmark: head=d5e0dc1bd505982ab2a346a22086000f76f996cf gate=FAIL storage live DB/WAL and cumulative prefix rewrite amplification; mounted one production chat subscriber and one status-feed subscriber for host cost, with full client delivery/renderer omitted. No waiver.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

BLOCKED — five P1 performance findings at 09841946885c8f64fc1e142ede673d8dfc5ec2d9. The current head offers a 60 ms live-text path and restores growth-gated ordinary saves. It does not retain the previous head’s unconditional 400 ms save loop. It nevertheless introduces repeated full-prefix display work, republishes quiet rows, amplifies history-wide desktop work, adds full-prefix saves on sparse streams, and adds a quadratic placement lookup. These are reproducible work-count regressions; no measured latency/CPU threshold is claimed.

Reviewed 4939ff194f76c9f06c54373ec52a26d8840ae0d8..09841946885c8f64fc1e142ede673d8dfc5ec2d9: all 19 changed files plus production callers, listeners and desktop consumers. Old PR-body measurements and the previous head’s WAL verdict are not evidence for this head.

  1. P1 — Display windows reconstruct whole prefixes, including with no subscribers. Introducing calls: codex-structured-item-streams.ts:138 and claude-streamed-text-checkpoints.ts:99. Codex now admits every text window to the coalescer’s full chunks.join(''); live publication calls snapshot() and joins it again. Claude already joined before its old growth check, but adds the live read/join and delivery. structured-agent-session-live-text-rows.ts:55 reconstructs every placed body; structured-agent-session-dispatch.ts:40 calls read() before subscriber interest is checked. The new durable overlay also reconstructs all live bodies before discovering which rows match a page.

    This runs on the host main thread, Electron main locally. Local desktop deliberately does not request text appends (structured-agent-session-read-transport.ts:39), so full replies cross IPC. Capable remote streams convert to suffixes later (agent-session-text-append.ts:146), after full host construction and prefix comparison.

    Production-function count harness: seed a 20,000-character reply; append 8 ASCII characters every 20 ms; drain the 60 ms windows. Counts exclude seed and final quiet interval. “Joined chars” means characters returned by production joins, not physical allocations, disk bytes or CPU time.

    Appended text Base/head growth saves Base joined chars Head joined chars Head live frames Head live text chars at emitter
    32 KiB 8 / 8 282,664 99,067,496 1,357 49,392,416
    320 KiB 24 / 24 2,874,552 5,017,278,936 13,629 2,507,202,192

    Continuous persistence admission matches base. Display work does not: summing growing prefixes at fixed arrival rate is quadratic in duration/length until the cap. At the longer workload’s average, 100 equivalent active sessions imply 612 million joined chars/s, and 1,000 imply 6.12 billion. These are arithmetic work-volume extrapolations, not measured concurrent throughput. With zero subscribers, a six-second/2,400-new-character control still performs 200 joins producing 4,242,400 characters and zero frames. One hundred unobserved equivalents imply ~70.7 million joined chars/s.

    Bound: 16 MiB retained text/stream, 32 MiB/coalescer, normally 256 evictable streams; not a global fleet budget. Required proof: proportional producer-to-emitter counts at N/10N, no display construction without interest, suffix-sized ordinary append work, and exact initial/reconnect/final output. Preserve background durable buffering.

  2. P1 — One changing row republishes every quiet live row in its session. New structured-agent-session-live-text-rows.ts:57 lacks dirty-row/last-published-body admission. Saved, quiet rows remain included until forgotten. Existing agent-session-live-publications.ts:55 sends the supplied whole array to every caught-up subscriber without content equality. The new Claude/Codex route reaches that behavior every display window.

    Harness: seed S live rows with 20,000 characters each, grow only one for six seconds. Sink live requests are coalesced once per window; these counts do not incorrectly multiply synchronous publication calls in one flush.

    S Frames Rows carried Rows identical to last durable/live value Text chars carried
    10 100 1,000 900 20,121,200
    100 100 10,000 9,900 200,121,200

    Both send 16.667 frames/s and zero wholly unchanged frames, but 150 / 1,650 unchanged rows/s. One hundred sessions with ten retained live rows imply 15,000 unchanged row deliveries/s per subscriber population; 1,000 imply 150,000. A useful delta in a frame does not justify its quiet siblings. Remote suffix encoding can turn siblings into empty-text appends, but construction/comparison/emission/reduction still occurs. The added durable overlay similarly reads S bodies per subscriber/page before revision matching.

    Required proof: one changed row among N/10N quiet rows yields one changed-row publication; an unchanged wake yields zero frames. Cover subscriber baselines, first view, lag/catch-up, revision changes and teardown.

  3. P1 — The new display rate still drives work across loaded desktop history. structured-agent-session-history-state.ts:98 improves tail lookup and avoids retention scanning for in-place revisions, but line 110 still copies all H items. Per-incoming-row tail lookup is O(S×H) in the worst placement. Equal-revision live items are accepted, including quiet sibling restatements. The reducer subsequently calls agentSessionHasOlderTranscript (structured-agent-session-reducer.ts:300): when older history exists and no clear divider is loaded, it scans all H bodies.

    Unchanged desktop consumers matter: structured-agent-session-read-owner-create.ts:67 publishes the new state; use-structured-agent-session-transport-state.ts:36 rescans context boundaries; structured-agent-session-message-stream.ts:91 walks prior items even on its message-reuse path; use-structured-agent-session.ts:207 invalidates transcript derivation. Virtualized drawing does not remove this upstream work.

    Actual reducer, one equal-revision tail text update, older history available and no clear divider: 1,001 / 10,001 existing-body reads at H=1,000 / 10,000, then another 999 / 9,999 existing-body reads in the production context selector, plus the changed row. Both cases copy the items array. At 16.667 frames/s, a 1,000-row chat incurs at least ~16,667 visits/s in that reducer scan alone; 100 active read owners imply ~1.67 million/s, before context/message work. Scale owners or loaded history separately by 10 and that count multiplies by 10.

    The scans predate the span; invoking them between growth saves is new. The old retention scan really is removed for this fast case, but the update is not history-independent. Defaults are 1,024 own / 4,096 total retained rows; explicit older-page loading raises limits. Database history size is not automatically renderer H. Hidden panes deactivate transport when the last visible activation leaves; do not multiply all hidden chats into renderer counts. Mounted consumers sharing an owner can still be notified while another activation is visible.

    Required proof: production read-owner/reducer/context/message counts at H/10H and one localized update, plus real desktop frame gaps. Preserve paging, clear boundaries, row ownership and ordering.

  4. P1 — Quiet-save admission makes sparse output repeatedly persist the whole prefix. agent-session-delta-coalescer.ts:129 joins the stream after one second of quiet; codex-structured-item-streams.ts:143 and claude-streamed-text-checkpoints.ts:118 force-save a changed length without minimum growth. The ordinary append still estimates/serializes the complete body, transfers it to the writer worker and upserts full payload_json (journal-domain-current-item.ts:113). It does not use the specialized incremental text write.

    Actual Codex stream functions, same 20,000-character seed, now 8 new characters every 1.1 s:

    New text Duration Base/head additional saves Head chars passed to persistence
    80 chars 11 s 0 / 10 200,440
    800 chars 110 s 0 / 100 2,040,400

    Exact sum: K×20,000 + 8×K(K+1)/2, before JSON/worker/database overhead. This is 0.909 full-prefix saves/s/session, versus no base saves in those intervals. With 100 such agents at a 1 MiB reply, body volume alone is ~90.9 MiB/s; 1,000 gives 909 MiB/s. The quiet route also newly invokes durable listeners, including avoidable queue-drain wakes below. Timely paused-tail durability is useful; rewriting a growing prefix for each tiny increment is disproportionate work.

    These are sink-admission payload counts, not measured SQLite UPDATE bytes, WAL growth or disk usage. Required proof: repeated-pause workload through the real writer with proportional cumulative preparation/write volume, bounded retained storage, exact paused-tail reopen/final output and refusal recovery. Do not average away sparse traffic with the improved continuous case.

  5. P1 — Placement callbacks search the batch result once per written stream. New structured-agent-session-resolved-append.ts:101 calls result.items.find for each callback. structured-agent-session-dispatch.ts:156 gives each step callback the same batch-wide items, and journal-sql-steps.ts:93 confirms these are the batch’s deduplicated written rows. M distinct saved streams make M(M+1)/2 ID comparisons in write order.

    Actual append-helper callback harness: 10 callbacks → 55 ID reads; 100 → 5,050, for 10/100 required placements. This repeats when the shared coalescing window growth-saves multiple streams, not only startup. At 0.1 such batches/s (approximately the seeded continuous workload’s save rate), ten streams across 100 session owners imply 550 comparisons/s instead of 100 indexed resolutions/s; 1,000 owners imply 5,500 versus 1,000. A session with 100 streams makes 505 comparisons/s instead of 10. Individual quiet-timer callbacks need not share a batch and are not assumed to do so. The ordinary 256-stream Codex bound still permits 32,896 comparisons/batch. Batch width and global agent count are separate dimensions.

    Required proof: O(M) shared/scoped placement resolution at M/10M, plus correct late, forgotten and epoch-replaced commits. No timing claim is needed to establish this new nested scan.

Listener census at this head, including unchanged files and desktop. Rates are text-induced traffic after opening/initial metadata settle, with no unrelated tool/status/reconnect events. Per session and per subscribed client unless stated. A wholly unchanged frame ignores transport timestamps; text already displayed with a newly durable cursor is identified separately, because the cursor carries necessary information. Measured 32 KiB workload: L=1,357/81.92=16.565 live frames/s, D=8/81.92=0.09766 saves/s. Six-second sub-growth window: L=16.667,D=0. Sparse workload: L=D=0.909/s. Listener rates below are source-derived except the explicitly measured seam counts; they are not an end-to-end IPC/phone capture.

Listener / owner Settled idle Under load and unchanged traffic
Live-source bindings: Claude reply/thinking owners, Codex item-stream owner; existing provider timeline source 0 timer frames/s; a final 60 ms tail window and 1 s quiet save may remain immediately after the last delta. Sink snapshots read sources before interest checking, visiting S placements/reconstructing prefixes. Claude’s two owners share session publication-key coalescing. Existing timeline cadence is not newly redesigned.
AgentSessionSubscribers.publishLiveText targets 0 frames/s. Caught-up targets get L frames/s. Single-row continuous harness has 0 wholly unchanged live frames; multi-row unchanged counts are finding 2. Cursor-behind targets get 0 live frames until catch-up; durable overlay supplies latest text. No target still leaves producer construction cost.
RPC agentSession.subscribe: local desktop, environment/SSH/WSL desktop, mobile/relay, other RPC clients 0 text frames/s. L live plus durable row frames per client. Local desktop uses full bodies; capable environment clients use suffix encoding (8 reply / 16 extended append bases); old/unnegotiated clients use full items. Phones split/bound frames, so physical phone frame count is payload-dependent and can exceed L; unmeasured. Transport fanout is not another host producer.
Durable chat subscribers: commit delivery and explicit sink publish() 0 frames/s. Up to 2D delivery attempts/s for isolated drained saves, but cursor/work/queue/command gates suppress unchanged caught-up delivery. Stable single-row case: D durable row frames/s, 0 redundant caught-up frames/s. Sparse quiet saves produce D frames whose text was already live, with meaningful revision/cursor advancement. Continuous growth-save windows carry new text. Pending saves may coalesce; genuine work/activity transitions add frames.
Opening/restate snapshot path No continuing idle cadence. The new snapshot overlay plus existing subsequent live publish yields one content-identical live frame per opening/restate with placed live rows. Overlay/publisher seam reproduced one duplicate. Its rate is opening/restate rate, not L. Resume depends on catch-up owed.
Desktop shared read owner and React/transcript consumers 0 text updates/s without active transport. Owner shared by session/target. L+D text frames/s in stable case; nonempty live batch makes new rows/state identities, even for quiet siblings. Finding 3 prices work. Command listeners add 0 ordinary-text callbacks. PR-link observer checks batch rows but emits 0 links for prose and does not scan tabs unless tool links exist. Equal-cursor text does not create a new view-attention read identity.
Host status projection, saved-status observer, ownership sink, changed-status observer 0 text callbacks/frames/s. Up to 2D projection requests/s; journal/authority cache shares current reads. Saved-status observer runs before equality but its turn-edge guard writes 0 records for continued prose. Stable working state and saturated first-200-character preview in this workload yield 0 status frames/s and 0 unchanged status frames/s, also 0 changed-status/sink notifications. Real preview/status/child changes can broadcast at D, never L. Projection attempts are not frames.
RPC status → desktop host-shared status feed and consumers 0 text frames/s. Same 0 stable-long-reply output after host equality. Head consumers: status bridge/hooks, attention bridge, name observation/tab-name/conversation-name readers, naming-failure UI, busy/close-running-work reads, AI Vault association observer, usage-limit continuation, async-question skip, resume-run watch and restart-occurrence watch. Remote/mobile status clients share this host producer; they are not L listeners.
Completion/prompt feed and its subscribers 0 frames/s. Reuses status projection, up to 2D observations/s; prompt/settled baselines emit 0 completion/prompt frames/s for prose. Head subscribers: configured host-attention-delivery (including state reconciliation), configured host-turn-attention, RPC completion streams. Desktop RPC feed fans out to attention bridge and source-control turn-completion hook. Genuine edges emit once; ordinary text invokes neither downstream action.
Send-settlement waiters 0 text checks; existing timeout can resolve a waiter. Up to 2D checks/s per pending send, 0 from L. Only registered waiters; caps 64/session, 1,024 total; result/abort/timeout/close cleanup. No external stream frame while still pending.
Queue drain/activity owner 0 text work. Commit uses actual inputChanged; an existing-text revision needs no drain there. Explicit translator publication defaults inputChanged=true, allowing D unnecessary drain attempts/s once preceding scheduled work drains. Pending-set dedup does not suppress successive saves. 0 from L. Pre-existing on growth saves, newly exercised by quiet saves.
Journal-publication observer registry 0 callbacks/frames/s. Up to 2D callbacks/s if registered, 0 from L. Production search found no in-tree registration beyond API exposure/wrapping; no fictional mounted listener is counted.
Journal commit observer → conversation publications 0 hints/s. One production observer per adopted conversation; D hints, runtime work refresh, settled-turn routing and scheduled client delivery; 0 from L. Detach/replacement unsubscribes the old journal.
Conversation-publication consumers 0 text hints/s. Automation run observer gets D hints and reads semantic interest (queue card/submission/optional canonical turn+item) before suppressing unchanged completion work. Mailbox redrive gets D hints but relevance rejects ordinary text revisions: 0 redrive callbacks; relevant events use 300 ms trailing/2 s maximum wait. PR-watch handle lookup subscribes only for its initial handle then immediately unsubscribes: 0 retained streaming callbacks. None receives L.
Commit observers: request failures, PR-watch committed rows, prompt telemetry; settled-turn routes 0 text callbacks/s. D commit callbacks, 0 from L. Outcome/action/prompt relevance gates give 0 resulting failure/action/prompt events for ordinary existing prose. Settled-turn routes inspect committed items but invoke listeners only on terminal turns: 0 prose callbacks. Snapshot/epoch replacement and fork-marker/crew observers are not triggered by ordinary text revision.
Separate commands, background-task republish, provider activity routes 0 periodic text frames/s. Live batches reuse subscriber queue publication and omit already-sent rosters; command identity is consulted. Command/roster routes publish changed values. Ordinary reply deltas do not set activity; item-start and bounded reasoning-headline changes can add event-driven frames. Those pre-existing provider-dependent events are excluded from L/D, not counted as silent live-text frames.

Census anchors: structured-agent-session-client-delivery.ts:295, structured-agent-session-publication-wiring.ts:22, structured-agent-session-conversations.ts:86, agent-session-subscriber-frame-fields.ts:64, structured-agent-session-status-feed.ts:210, structured-agent-session-host-assembly.ts:100. Global status/completion feeds are per host/client, not per each of 750 worktrees. Fleet prices use 100 active agents and independently vary owners, loaded rows or stream width to 10×; historical chats are not assumed mounted.

Complete diff work inventory. Host work runs on local Electron main or the corresponding remote host process; existing SQL executes in writer/reader workers. Every changed production file and both test files are covered below.

Changed file(s) Trigger → population/work → bound/disposition
claude-streamed-text-checkpoints.ts Nonempty delta → bounded coalescer; dirty 60 ms window → growth save or live request. Adds source binding, placements, 1 s quiet save and lifecycle flush binding. Save threshold stays max(old+32,ceil(old×1.125)). Drop/dispose remove rows. Findings 1/2/4.
claude-streamed-thinking.ts Reasoning checkpoint → callback forwarding; live read → running reasoning body. Final writes preserve lifecycle/start time. Open-block population; no independent poll.
claude-structured-journal-translation.ts Reply checkpoint → scoped append/callback/publish; live read → full-text body. Same turn/lifecycle attribution. Findings 1/2.
claude-final-output-coverage.ts Each append → optional callback forwarding through try/fallback/lifecycle paths. O(1), no new owner/scan/timer.
codex-streamed-item-body.ts Saved/read stream → item translation and running reasoning lifecycle. Type predicate restricts live route to reply/reasoning/plan, excluding command/file output. Work proportional to requested body construction.
codex-structured-item-streams.ts Text dirty window bypasses growth only for live display; ordinary saves keep growth gate. Adds source/placements/quiet save/cleanup. Command/file output keeps pre-join growth admission. Normally 256 evictable states; existing persistent-command exceptions. Findings 1/2/4.
codex-structured-journal-sink.ts Admitted item → callback forwarded through try/fallback, existing publish. O(1) forwarding; persistence body remains full-prefix.
codex-structured-journal-translation.ts Token-usage notification → no longer forces stream tails through flushStreams; other barriers keep existing thread-scoped forced saves. Removes work at usage-event rate, no polling added.
structured-agent-session-event-sink.ts Optional callback contract and extracted item-submission helper. Callers without callback retain existing estimate/queue/steps work; live bind/publisher already existed.
structured-agent-session-resolved-append.ts Callback-bearing write → identity key plus batch-result search after resolution. O(M²) across M streams, finding 5; no callback without matching row/cursor.
structured-agent-session-live-text-rows.ts Live read → scan placements/rebuild epoch-matching bodies. One map/translator; text stays in coalescer; forget/dispose releases map/source. No dirty/content/interest gate. Claude placements follow tracked blocks until lifecycle cleanup; coalescer eviction does not independently cap this new map at 256. Findings 1/2.
agent-session-delta-coalescer.ts Nonempty append adds monotonic timestamp and O(1) timer admission; empty exits. Existing shared flush timer scans streams/window. Adds at most one quiet timer/key, rearmed for remaining quiet time rather than per token. Successful quiet handling stops; failed Codex idle save retries after 1 s. Joins before downstream type/length skip, including command streams whose idle handler does nothing. Eviction/forget/dispose cancels timers. Findings 1/4.
agent-session-delta-prefix.ts UTF-8 append/truncate helpers moved unchanged. Appends push chunks; overflow materializes bounded prefix/marker. Existing 16 MiB/stream and 32 MiB/coalescer caps. No new algorithm.
agent-session-live-publications.ts Nonempty durable page → read S live bodies, build map, map page and overlay equal revisions. O(S + page rows + text) per subscriber/page even without match; empty pages skip. Existing live emitter sends all supplied rows. Findings 1/2; duplicate opening frame counted.
agent-session-subscriber-catch-up.ts Reset/catch-up/snapshot → overlay before emission. Catch-up page maximum 200; snapshot bound follows reader. Avoids older-body regression at matching placement, at repeated per-subscriber live-read cost. Cursor/lifetime checks remain.
structured-agent-session-history-state.ts Live batch → tail search + array copy; new/removed/moved/root-owner-changed rows use old merge/sort. Worst fast attempt O(S×H + H); paged H has no independent fixed limit. Finding 3.
structured-agent-session-reducer.ts Batch → skip retention only for stable placement/root classification. Roster/window/cursor and subsequent clear-history scan remain. One scan genuinely removed; finding 3 remains.
claude-streamed-text-checkpoints.test.ts; codex-structured-journal-translation-streams.test.ts Fake-time paused-tail/live/quiet/final checks; manual windows distinguish idle timers. Test-only. No production listener/IPC/SQL cost census.

Evidence and limitations. Read-only source audit plus external count harnesses on this Mac, run through TC_GATE_POOL=test tc-gate with ORCA_BACKGROUND_LAUNCH=1. I made no code edits, dependency installs, builds, app launches or CI reruns. Final evidence was rerun in a clean, isolated full-history local clone at the exact head, using linked existing dependencies; every count matched. Artifacts: ~/orca-qa/pr-35462/perf-scan-0984194/{counts.ts,counts-pinned.jsonl,seams.ts,seams-pinned.jsonl,base-streams.ts,base-coalescer.ts,tests-pinned.log}.

The A/B harness executes the actual base/head Codex stream manager/coalescer; base copies come from the pinned git object with production dependencies resolved from this checkout. Its sink records admissions, supplies committed placements, coalesces live requests and calls the actual live publisher. It does not measure SQLite, durable listener execution or IPC. It verifies exact final text, ten minutes of settled silence with zero added saves/frames, and zero timers/source bindings after dispose. Separate production-helper seams count placement searches and duplicated snapshot/live content. The real reducer/context selector is exercised at explicit H with older history. The three targeted test files passed, four tests: Claude checkpoints, Codex translation streams, shared session reducer. These correctness controls do not prove smooth UI.

No packaged Electron frame/event-loop/CPU trace, actual SQLite/WAL measurement, mobile split-frame capture, congested transport, or Windows/Linux/WSL/SSH runtime measurement was performed. Count amplification is established; a seconds-long stall is not claimed reproduced. Existing subscriber promise chaining has no latest-live replacement or independently demonstrated pending-payload bound; slow delivery requires a real congestion/control test. Existing Claude metadata/latest-text maps can survive coalescer eviction until lifecycle cleanup; the new placement map follows that lifetime, so text caps are not total-owner memory caps. Successful/closed paths showed no perpetual timer. Inspected refusal test coverage is not a sustained failed-writer/transport stress test.

Six scan questions. (1) Work before skip: findings 1/2, including zero listeners and overlay-before-match. (2) Ownership multiplication: per-translator sources, per-client delivery, shared desktop owner and host feeds traced; findings 2/3/5. (3) Thread/storage: main joins/estimation, worker SQL and renderer work traced; continuous admission improved, sparse finding 4 remains. (4) Growth/progress: text length, loaded history, live-row width and commit width separately checked at N/10N; durable cursor/overlay provides catch-up, backlog bound remains unmeasured. (5) Host: no added subprocess/Git/filesystem discovery/native probes; remote host pays same preparation and negotiated suffix/phone projection differs. Host-specific timing unassessed; folder/non-git workspaces use the same session-keyed route. (6) Obsolete/idle work: cleanup and settled silence exercised, unobserved producer finding 1 remains; congestion/metadata limits stated. Cold open/reconnect gains overlay plus duplicate frame; no first-paint timing claim.

Touched regression classes. Whole-message streaming/repeated prefix copies: findings 1/4. Hidden/unobserved work before skip: finding 1. Whole-live snapshots/unchanged row publication/identity churn: findings 2/3; one duplicate opening frame separately counted. History rescans/nested item lookup: findings 3/5. Whole-row rewrite per change: continuous gate matches base, sparse finding 4; no claim of accumulated full-text journal history. Fixed-cadence loop never settling: successful quiet/idle control disproves that for the new timer, refusal lifetime not stress-tested. Retention/fanout queues: source cleanup passes control; existing pending-delivery and metadata limits remain explicit gaps. Eager imports: helpers add no SDK/native initialization or independent startup service. New sync main-thread fs/SQLite or per-item subprocess calls: no matching diff; SQL retains worker ownership. Existing durable queue/observer amplification is pre-existing on growth saves and newly invoked by quiet saves, not charged to every live frame.

Verdict: BLOCKED on this head’s own work counts. The 400 ms continuous full-prefix save loop is gone, and the reducer removes one retention walk. Those improvements do not close the five findings. Remedies need proportional operation/byte guards at the production seams with paused-tail durability, ordering, reconnect and final-flush controls.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf-scan verdict: BLOCK — P1 performance regressions remain.

Reviewed exactly 4939ff194f76c9f06c54373ec52a26d8840ae0d8..144b9226d19005b3685b76e965a93ead9711b543. This grades that revision independently, not the earlier 400 ms implementation. GitHub had already advanced to 09841946 when this review began; this is not a verdict on that newer revision. No repository code was edited.

The good change is real: continuous text no longer needs a durable save for every visible update, and in-place reducer updates avoid sorting and retention rescans. However, full-prefix work moves onto the 60 ms live path, that path reaches unchanged desktop history derivations, and quiet saves still bypass geometric growth indefinitely. The counts below establish amplification; they are not measurements of seconds of UI lag.

Findings

1. P1 — Full reply materialization now runs every live window, including unobserved Codex sessions; observed replies also undergo full serialization and local IPC.

Introducing change: codex-structured-item-streams.ts:138 makes every text stream pass shouldEmit. agent-session-delta-coalescer.ts:97,119 then joins the complete growing prefix before the subscriber-interest check. Keeping [text] avoids copying unchanged snapshots, but the next append creates [wholePrefix, delta] and copies the prefix again. Claude already joined before its growth gate at the base; the unobserved copy regression is specifically Codex. Both providers newly publish their text between checkpoints.

The new form(item) in agent-session-live-publications.ts:59–67 reaches agent-session-item-wire-form.ts:73–77: JSON.stringify/UTF-8 sizing of the complete row, and binary-search shortening when oversized. New live row objects miss the WeakMap across publications. The same publication's objects do share cached forms across subscribers; serialization must not be incorrectly multiplied by every identical reader. The durable overlay instead constructs fresh rows per subscriber/page. Remote append encoding happens after this work and checks startsWith(base) over the prefix. The unchanged desktop transport, structured-agent-session-read-transport.ts:39–42, requests appends only for environment targets: local IPC still carries complete replies.

Price: at one occupied window per 60 ms, a 1 MiB reply means about 16.67 MiB/s of joined text per active stream, plus at least that much formatter input when observed, plus the full local IPC payload per local reader. At 100 unobserved Codex streams this is about 1.63 GiB/s of prefix materialization; at 1,000 it is 16.28 GiB/s. These are logical ASCII bytes presented to operations, not sampled memory bandwidth or CPU time. For K growing windows the work is sum(prefixLength[k]), quadratic in accumulated text before the existing caps. The 16 MiB/stream and 32 MiB/coalescer limits bound retention, not repeated copy cost. A single observed 20,000-character reply still presents about 333,000 characters/s to the formatter to deliver a small tail.

Required guard: production producer → publication → wire, with zero and one subscriber, at N/10N windows and text sizes. Unobserved live-only appends should not materialize full snapshots; observed incremental output should not repeatedly serialize the prefix. Preserve first placement, ordering, reconnect snapshots, truncation signaling, final text, and geometric durable saves.

2. P1 — Live publication resends unchanged rows and can emit an entirely unchanged visible frame on every window.

Introducing change: structured-agent-session-live-text-rows.ts:55–60 enumerates every committed live placement; neither it nor publishSubscriberLiveText tracks what changed or what the subscriber last received. One changing row republishes all Q placements, including quiet rows. This is newly reached by the Claude/Codex stream emitters. An opening snapshot now already overlays live text, but AgentSessionSubscribers.open still immediately sends the same live rows again. That is one redundant live frame per opening with live placements, not an idle timer.

The per-row wire bounds make the no-change case particularly concrete: a phone row is limited to 72 KiB, and an ordinary client row to 1,984 KiB. Appends beyond the retained wire prefix produce the same shortened body. They still cause a fresh live frame; shortened also disables text-append encoding. Cursor/fence/body can remain identical while only hostNow changes. Thus a long phone reply can cause roughly 16.67 frames/s with all 16.67 carrying no new visible data, yet still pay full-prefix formatting, transport, and reducer work. At 100 such subscriptions that is approximately 1,667 useless frames/s; at 1,000, 16,667. For one changing row among Q=10/100 live rows, 9/99 rows per frame are unchanged: about 150/1,650 unchanged row deliveries/s per subscriber.

Required guard: one changed key among 10/100 placements sends only that change; repeat an identical post-projection value and emit zero frames; opening emits the live value once. Test clipped rows and a genuine visible change, revision/lifecycle change, reconnect, and final full-content access. Equality must be admitted before repeated expensive construction where possible; simply ignoring the frame in React is too late.

3. P1 — The 60 ms path still invalidates history-wide desktop work; the new binary search does not make a text update local.

Introducing change: the new live producer cadence reaches structured-agent-session-history-state.ts:103–110. Lookup is O(log H) per incoming row, but current.slice() still copies H retained references once per frame, including equal-revision/equal-content rows. reduceStructuredAgentSession returns a new state, and the unchanged desktop read owner publishes it to useSyncExternalStore.

The unchanged consumers are part of the production path: use-structured-agent-session-transport-state.ts recomputes current-context rows, activity and turn timing on the new item array; use-native-chat-context-clear-floor.ts scans again for /clear; use-structured-agent-session.ts derives cut-turn notices and transcript messages; structured-agent-session-message-stream.ts:reuseMessages compares every retained row and copies the message array for a revised row. This is not a claim that every old message is reparsed: that projection reuses unchanged row objects, and streaming Markdown has its own incremental path. It is a claim about proven repeated history visits and copies before rendering.

Price: H=1,024 gives about 17,067 copied references and at least 17,067 context-row visits/s per visible owner at 16.67 updates/s, before the additional walks above. H=10,240 gives 170,667 of each. One hundred active views would multiply these by 100; do not charge all 100 agents as visible views. H is not permanently capped at 1,024: older-page loading increases retained limits. A shared read owner avoids duplicate transport for the same host/session, but multiple mounted consumers still derive their own views. Pure hidden panes deactivate transport; a hidden consumer sharing an owner with a visible pane still receives that owner's store notifications.

The old history walks predate this span; invoking them at the newly introduced live cadence is the amplification. Required guard: actual desktop owner and transcript projection at H and 10H, including one repeated no-op frame. Count upstream visits and copies, not just React commits. Keep live text isolated from history structure, while preserving lifecycle, attribution, retention, /clear, history paging and turn state.

4. P1 — Capped quiet-save backoff restores full-prefix durable rewrites for sparse streams.

Introducing change: agent-session-delta-coalescer.ts:136–142 doubles quiet time only up to 16 seconds. Both new idle callbacks force persistence whenever text length differs, bypassing the 12.5% growth threshold. A stream delivering one tiny burst every 17 seconds therefore saves its entire prefix once per burst indefinitely, even without subscribers. The prior base's growth gate does not do that. With only growth-driven checkpoints, successive saved lengths grow at least 1.125×, so their prefix lengths sum to at most about 9× the last checkpoint (separate explicit lifecycle/linkage writes excluded). Continuous streaming is better: the quiet deadline follows the last delta and adds no periodic saves while input continues.

Price: for 100 such agents with a 1 MiB prefix, about 5.88 full-prefix saves/s and 5.88 MiB/s of logical body input to durable writes, plus their commit/publication work; at 1,000 agents, 58.82 saves/s and MiB/s. SQLite/WAL bytes are not measured and may differ. K small sparse appends still cost K*initialPrefix + delta*K*(K+1)/2 until the text cap. This is a slower version of the rejected full-prefix rewrite class, not a restored 400 ms timer.

Required guard: 100/1,000 sparse bursts, quiet after each, plus a continuous-stream control and final flush. A durability solution must retain accepted text and eventual quiet/final saves without repeatedly rewriting the full prefix per sparse delta; incremental durable representation or a proven total-write budget needs validation.

Work inventory: every changed production path

Production reachability was checked through createClaudeSessionJournalTranslator in claude-structured-session-journal-control.ts and createCodexSessionJournalTranslator in codex-structured-session-journal.ts, both created on native-chat acquisition with the event sink. These are active provider paths, not test-only helpers.

A = attached provider owners; Q = retained live placements for one owner; C = transcript subscribers for that session; H = retained client history; S = reply prefix; F = occupied coalescing windows/s (at most about 16.67 per coalescer, apart from explicit flushes); D = actual durable commit batches/s. Rates are conditional source bounds, not live-machine measurements. “No change” distinguishes identical semantic payload (ignoring hostNow) from no new visible text: a durable cursor/revision advance is protocol progress even if its body was already shown live.

Changed work Trigger, population, owner/thread Work and bound/disposition
Claude claude-streamed-text-checkpoints.ts Dirty text windows, linkage correction, quiet, flush/end; one reply coalescer and one thinking coalescer per translator on host main Existing geometric saves: first, then max(last+32, ceil(last*1.125)); now live publication below threshold and new quiet forced saves. flush still scans retained latest text; lifecycle writes remain. Findings 1/2/4.
Claude claude-structured-journal-translation.ts, claude-streamed-thinking.ts, claude-final-output-coverage.ts Each admitted running-row save; callbacks forwarded through coverage wrapper Constructs running bodies, forwards committed placement callback, preserves turn scope/start time/lifecycle. Constant wrapper overhead per save; reasoning shares the same new live/quiet mechanism.
Codex codex-streamed-item-body.ts, codex-structured-item-streams.ts Each text window; all retained states considered by existing flush New shared running-body helper; only agentMessage/reasoning/plan exposed live, not command output. Text bypasses pre-join growth gate; nontext retains it. State/patch pruning and pending checkpoints remain. Findings 1/2/4.
Codex codex-structured-journal-sink.ts, translation Each save, and each incoming provider event Callback forwarded; token-usage notifications no longer force flushStreams. Other lifecycle/barrier events still flush. This removes an existing source of forced checkpoints rather than adding one.
structured-agent-session-resolved-append.ts, event sink Each append; only callback-bearing saves need lookup Existing byte estimate/admission/worker write. New committed-row index built once per returned batch of B rows, O(B), then O(1) lookup per callback. WeakMap lifetime follows result array, not whole session history.
structured-agent-session-live-text-rows.ts Each live read / durable overlay / snapshot; Q placements per translator Stores epoch and placement without body; reads current body from existing coalescer. O(Q) new rows/read. Commit before first appearance, epoch guard, forget/dispose release. Finding 2; no new full-text ownership here.
Attach orchestration, dispatch, subscribers Each live publish request; A owners and C session listeners Lazy read now skips placement construction with C=0, and publication key coalesces pending ingress notices. It does not skip the earlier coalescer join. Each active subscriber gets a serialized delivery task; cursor mismatch suppresses emission after construction.
agent-session-delta-coalescer.ts Nonempty delta, shared 60 ms flush, per-stream quiet timer Append accounting proportional to delta; complete join on eligible dirty flush, cached on unchanged read. Existing 16 MiB/stream, 32 MiB/coalescer, 256 ordinary streams; protected Codex command streams have separate retention ownership. Quiet checks rearm during input and stop after quiet callback. Empty delta now returns before scheduling. Forget/evict/dispose cancel idle timers. Findings 1/4.
agent-session-delta-prefix.ts Stream overflows byte allowance Moved byte-prefix truncation/UTF-8 helper, substantially unchanged; one bounded truncation then subsequent data does not grow retained text. No new per-token truncation scan.
Live publications Each caught-up listener's live frame Per-row wire formatting, all Q rows; standard/bounded forms cached only for same object. Phone frame splitting adds frames when necessary. Findings 1/2.
Catch-up withSubscriberLiveText Each nonempty durable page/reset/snapshot for each subscriber Reads Q live rows, creates a map, scans P page rows, re-forms revision-matched rows. O(Q+P) plus their prefix bytes. Empty pages skip read. Revision mismatch retains durable body. Needed freshness behavior, but fresh identities do not bypass Findings 1/2.
Shared reducer/history state Every incoming live/durable batch on desktop and phone O(incoming*log H + H) fast path; movement/new ownership/removals fall back to existing merge/trim. Eliminates repeated sort/retention work for revisions, but not history copies/consumers: Finding 3.
Other production consumers of the changed shared helpers ACP/JSONL/Pi timeline lane uses ProviderTimelineTextStreams, which also binds live text and uses the same coalescer/publisher Its per-delta snapshot joins and 400 ms ready-block durable saves predate this span; new wire formatting/overlay also applies to it. With continuous eligible blocks it can make up to 2.5 timer-driven saves/s, live window publications at about 16.67/s plus save-publication notices; explicit event barriers are additional. Do not attribute that pre-existing 400 ms path to the new Claude/Codex implementation.
Three changed test files Test execution only Adds paused-tail/quiet-save tests for both providers and revision-matched overlay test; manual Codex scheduler excludes quiet timers. These tests do not count formatter/IPC/client fanout or sparse-save growth.

Listener census at this head

This census includes registrations outside the diff. It distinguishes publication callbacks from wire frames: a callback can run and emit nothing. “Idle” means no input, no pending retry/catch-up and no owner transition. All paths below have 0 steady-idle frames/s, 0 unchanged frames/s. A final pending quiet save, initial snapshot, reconnect, lifecycle event or unrelated status change is not steady idle.

Live text has one direct listener family: the session's AgentSessionSubscribers registrations. The production RPC entry is structured-agent-session-subscribe-method.ts → background-task-channel subscribe → subscribers.open; local desktop, remote desktop and phone use that same registration. There is no live-text subscription by the status feed, completion feed, automation, mailbox, telemetry, PR watcher or settlement waiters.

Listener / downstream consumer Under sustained reply load Frames carrying no change / gate
Local desktop transcript (structured-agent-session-read-transport.ts → shared live read → read owner) About F-D live batches/s plus durable batches; for a long reply below its next checkpoint, 16.67 live batches/s. Full IPC prefixes. Ordinary changing unshortened reply: 0 entirely unchanged live frames/s. Shortened stable prefix: up to all 16.67/s. Opening adds one redundant live batch after the overlaid snapshot.
Environment desktop transcript Same publication count; append encoding negotiated by capability. Unshortened text sends delta bytes but still pays pre-encoding formatting/prefix comparison. shortened sends full clipped rows; same no-change rate as above.
Mobile transcript (mobile-structured-transcript-subscription.ts, use-mobile-structured-agent-state.ts) Same logical rate, bounded rows and possibly multiple wire batches/publication; negotiates text appends. 72 KiB row clipping can make all live frames unchanged. Frame splitting does not remove them. Exact wire-frame multiple depends on Q and encoded size.
Desktop/phone shared client coalescer Assistant-only batches delayed 48 ms; reasoning/nonassistant rows bypass. A 60 ms producer cadence is not reduced by a 48 ms window. Bursts can merge; they have already paid host/transport work.
Shared reducer, desktop read-owner listeners, transcript controller One application per surviving client frame; shared owner per host/session. Equal-revision rows are still replacements. New snapshot identity notifies mounted readers. Activity observation only runs on changed submission/queue arrays; command listeners require command/open hints; PR-link observer walks incoming rows but text-only rows produce no links/global tab scan. NativeChatBrowserRunPageButton is an additional read-owner subscriber: its latest-browser-call selector caches by item-array identity, so a new array can walk backward through history even if the selected call ID is unchanged. Read-only busy/send/attention snapshot accessors are not extra subscriptions.
Desktop projections/render consumers Context, activity/timing, background foreground-command view, prompt/current-request selection, context usage/goal report, /clear floor, cut-turn notices, message projection, then transcript/Markdown. Array-dependent work runs at delivered cadence; work varies by capability/turn state. Rail outline uses epoch/staleness key, not every live revision. Options and command RPCs are not automatically issued every text frame. Actual React commit/frame times were not measured.

Durable commit listeners: one journal commit callback is installed by StructuredAgentSessionConversations.set. It publishes conversation hints, refreshes activity ownership, routes settled turns, observes request/PR/telemetry facts, then schedules one microtask delivery. Provider saves also call sink.publish() → subscribers.publish(). Therefore a simple save can cause two delivery/status/settlement passes per commit (one commit-driven, one explicit); this predates the span. emitCaughtUp normally suppresses the second wire frame when cursor/work/commands/queue/activity are unchanged. Do not report two transcript frames per save merely because two callbacks ran.

Durable listener at head Work/population and under-load cadence Resulting wire frames / no-change rate during stable long prose
Transcript subscribers, including desktop renderer and phone Up to two delivery passes per D, C registrations; catch-up uses bounded history reads, shared work/queue reads within a fanout, and new live overlay. Usually D advancing history batches/s; second caught-up pass emits 0. Durable revision/cursor advances are protocol changes even when already-seen live text is the same. In the 17-second sparse workload, all D≈0.0588 durable frames/s carry no additional visible text after the earlier live update; clipped durable replies likewise need not change visible text. They are not counted as identical-protocol no-ops. Additional work/queue frames require their gates.
Status projection/feed, saved-status observer, status ownership sink and status-change observer Up to 2D calls; per-journal authority/cursor cache and in-flight read sharing; worker-side status reads on misses. Saved status checks a turn-edge fingerprint. After the 200-character assistant preview and working state stabilize, 0 status frames/s and 0 unchanged status frames/s. Earlier preview/semantic changes can emit at D; saved records do not rewrite per streamed token. The local status-change observer fans into crew status/name notification, orchestration mail status, worker auto-release activity, chat naming and first-turn workspace renaming only after its semantic gate. Fork-marker refresh listens to crew changes and compares the marker fingerprint, rather than subscribing to each live text frame.
Desktop status-feed subscribers One host feed fans into StructuredAgentSessionStatusBridge, naming observation, AI Vault association, resume-run/restart observation, per-session status hooks, conversation-name/naming-failure hooks, usage-limit auto-continue, async-question skip, and attention settlement. Mobile has its host status feed too. They receive the status output above, not F live-text frames. Read-only accessors for busy/name/window-close checks are not extra stream listeners.
Turn-completion feed Up to 2D projection observations, one baseline per session. Host attention delivery, host turn attention, RPC completion subscribers; desktop attention bridge and source-control completion hook downstream. 0 events/s during an unchanged running reply; emits real prompt/settlement edges. No repeated completion frame per text save.
Send-settlement waiters (structured-agent-session-send-settlement.ts) Up to 2D visits per waiter; keyed reads. Caps: 64/session, 1,024 total; timeout/abort/close removes them. No stream frame; one result when satisfied, otherwise 0. Does not run on live text.
Queued-send activity/drain (structured-agent-session-queued-wiring.ts) Commit path touches activity and only schedules on inputChanged; legacy explicit publish defaults inputChanged=true, so can still schedule once per save even for prose. Internal wake, no mandatory frame. Existing work amplification, not a new 60 ms live listener; extra quiet saves amplify its trigger count.
Raw journal-publication observers (StructuredAgentSessionJournalObservers) API exists and is invoked by publishJournal, but repository search found no production caller of observeJournalPublications. Zero registered production listeners; do not invent a fanout here.
Conversation publication: automation run observer Once per D per active run observer; commit/linkage/source checks and semantic interest fingerprint, one in-flight read with dirty follow-up. No transcript frame; stable prose does not produce a new run result. Still pays its interest check. Abort/finish releases.
Conversation publication: orchestration mailbox redrive Once per D per active watch; inserted/deleted/turn/context/input gates reject a plain row revision. Relevant events coalesce at 300 ms, max wait 2 s. 0 redrives/s for pure prose revisions. Not subscribed to live text.
Conversation publication: PR watch's openChatJournal Registers for immediate current-journal seed and immediately unsubscribes. Zero continuing commit listeners from this accessor. The separate committed-row PR observer below remains.
Commit observation: request failures, PR-watch committed rows, native-chat prompt telemetry Once per D, committed batch rows/receipts (not whole fleet); request/turn/item-kind gates. No native-chat stream frame for ordinary reply revisions. PR-watch receives the committed batch for action completion/delivery obligations; not a new live-text listener.
Commit ownership / settled-turn / snapshot routes Activity refresh per commit; settled-turn routes dispatch only terminal turn evidence; epoch-replacement snapshot route is separate. No per-text external frame. The new placement callback indexes one committed batch and updates its row metadata.

For a numerical normal-stream example, S=20,000 characters and 100 characters/s need about 2,500 new characters for the next geometric checkpoint: approximately D=0.04 saves/s, versus F≈16.67 windows/s with sufficiently frequent deltas. The transcript sees roughly 16.63 live + 0.04 durable batches/s; stable status/completion/mailbox listeners emit 0. At 100/1,000 agents, the unobserved main-process producer work still multiplies by 100/1,000, while transport and renderer costs multiply only by actual subscribers/views. At a quiet tail, at most one pending quiet save is made; thereafter rates return to zero. A 17-second sparse stream instead has D≈0.0588/s per stream, as Finding 4 describes. Provider activity notifications are an additional, pre-existing source of row-free frames; they are event-driven and are not a new fixed 60 ms durable publication loop.

Verification and coverage

Executed pinned-source operation probes (both exited 0): macOS, Node 26.5.0, existing esbuild TypeScript transform, fake monotonic clock, no GUI. Both base and target modules were loaded from the exact Git objects, not the concurrently edited source files. All probes ran through the shared test gate.

Workload Base Target
Codex, no subscriber, 1 MiB initial reply then 100 one-character appends at 60 ms 0 joins / 0 additional saves 100 joins, 104,862,650 characters joined, 100 live-publication requests, 0 saves while continuous
Same, 1,000 appends 0 joins / 0 additional saves 1,000 joins, 1,049,076,500 characters joined, 1,000 live-publication requests, 0 saves while continuous
Same, 100 appends spaced 17 seconds apart 0 additional saves 100 saves, 104,862,650 body characters handed to persistence
Same, 1,000 sparse appends 0 additional saves 1,000 saves, 1,049,076,500 body characters handed to persistence
Advance ten minutes after continuous input stops 0 further events One owed quiet save, 0 live publications, then no timers; dispose also leaves 0 timers
Advance ten minutes after sparse input has already settled 0 further events 0 saves, 0 live publications, 0 timers

The continuous-workload “live” counts are producer publication requests, not emitted wire frames: its no-subscriber sink deliberately does not read live rows. This isolates the copy paid before interest admission. The sparse counts are actual calls to the producer's persistence seam; they are not measured disk/WAL byte counts.

Additional head-only probes at the production publisher/reducer seams:

  • 10/100 live rows, one changes, 100 publication calls: exactly 100 frames each; 891/9,801 unchanged row deliveries after the initial baseline, 1,000/10,000 full-row stringifications, and 10,157,590/101,588,590 JSON bytes sized. The harness supplied fresh row objects as the production live-row reader does; it did not exercise a real transport.
  • Ordinary and phone row shortening: ten tail-changing inputs each produced ten frames; nine frames in each run had exactly the same serialized item array as the preceding frame. Only the first established a new baseline. This compares item content, not hostNow.
  • H=1,024/10,240 retained rows, one replacement: the fast path reported rescan=false but copied 1,024/10,240 array slots. The downstream production context selector read 1,023/10,239 instrumented old row bodies, plus the one replacement body: a full H-row walk despite no context-boundary change.

These checks reproduce the operation counts in Findings 1–4 and the idle/teardown controls. They do not measure React rendering or pretend the injected sink is SQLite.

The five existing test files were run through TC_GATE_POOL=test tc-gate, with ORCA_BACKGROUND_LAUNCH=1: Claude checkpoints, Codex translation streams, live publications, delta coalescer, shared reducer. Result: 5 files / 6 tests passed. Their assertions establish selected functional behavior, not the publication census or a packaged-app frame budget.

The external probe loads production TypeScript directly from each pinned Git object, with an injected clock/sink for operation counts. Concurrent staged work appeared in this shared checkout during review; it was left untouched and is excluded from the verdict. The existing-test result is checkout-based, not an isolated pinned-build result. It is not a real SQLite write benchmark or an Electron/phone/network recording. No dependency installation, build, emulator, OS input or application launch was performed. No CPU/heap/frame-time claim is made. Windows/Linux/WSL/SSH and real mobile transports were inspected through shared routing, not executed.

Regression class touched Disposition
Streaming reprocesses whole message; work paid before skip Findings 1/4; geometric continuous durable saves remain a genuine improvement.
One change published as whole snapshot; unchanged publication Finding 2, including quiet siblings, clipped output and opening duplicate.
History-wide derivation / identity churn Finding 3. Binary search and skipped trim reduce work but do not remove changed-array fanout.
Whole-value rewrite; sync storage Finding 4. Full row rewrites, not a claimed whole-database/file rewrite. SQLite journal operations use worker ports at this head; no new synchronous main-thread SQLite call identified. Main-thread construction/formatting remains.
Fixed timers / hidden owners Quiet timer stops after callback; continuous input rearms checks, no free-running idle publication loop. Hidden/unobserved Codex materialization remains Finding 1.
Resource lifetime / retained state New placements contain no body; WeakMap batch index follows batch lifetime; forget/dispose cancel timers/release source. Existing coalescer byte/count bounds retained. Claude's separate identity/latest-text maps are not trimmed by coalescer eviction: with K distinct unfinished blocks, those pre-existing maps can retain O(K) entries and prior text despite the 256 ordinary-stream cap. New placement metadata follows those identities until forget/finish/dispose; therefore Q is not proven globally bounded at 256 for Claude, and Finding 2 also applies to that larger Q. The quoted 32 MiB bounds coalescer text, not all translator maps or pending publications.
Pending fanout / recovery Ingress live notices coalesce; subscriber delivery chains are serialized but have no explicit latest-live replacement/pending-byte budget. Slow/stuck reader backlog remains an unresolved load-test candidate; no measured leak or unbounded-growth P0 is asserted. Cursor/epoch/current-owner gates and teardown were inspected.
Startup imports / subprocess / host probes New value imports are small local helpers; no new SDK, subprocess, probe, scan, or eager whole-history startup read. One-time opening now does live overlay plus redundant live publication (Finding 2).
Six scan questions Disposition
1. Work before skip? Reviewed producer→format→transport→reducer→desktop; Findings 1–3. Zero-subscriber gate is too late for Codex joining.
2. Ownership multiplies work? Reviewed coalescers, session subscribers, shared client owners and all publication families above. Costs priced separately by A/Q/C/H.
3. Thread/storage payer? Main/provider host does join/admission/format; worker-backed journal persists and reads; desktop/phone reducer and derived views pay client work. No timing claim.
4. Growth/progress? Reviewed geometric checkpoints, sparse bypass, byte caps, binary-search reducer, catch-up page bounds and actual cursor advancement. Findings 1–4; blocked-reader backlog remains unmeasured.
5. Execution host? Shared local/remote/mobile paths inspected; local IPC differs materially from negotiated remote appends. No platform-specific launch/path change. Windows/WSL/Linux/SSH and phone hardware performance unexecuted.
6. Obsolete work / idle? Reviewed forget/end/dispose, epoch replacement, hidden transport activation, no-subscriber admission and quiet settling. Timer/source teardown checked; no idle frame loop claimed. Slow-subscriber retained backlog needs a separate controlled transport test.

The remaining evidence gaps are actual UI frame/event-loop/heap traces, stalled-transport queue bounds, and platform runtime costs. They do not demote the source-proven repeated work above. Fixes should be reviewed with the same N/10N production-seam counts and correctness controls before this pinned revision can receive a perf pass.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf-scan verdict: BLOCK — performance regressions remain in the live-display path.

Scope: 4939ff194f76c9f06c54373ec52a26d8840ae0d8..3c2e06b7053ed6431887cc1f1f3ddc7bb31478bc. This grades 3c2e06b, as requested. The PR had already advanced to 0984194 when I started; this is not a verdict on that newer revision. No repository code was edited.

The fixed 400 ms durable rewrite is absent here. Growth checkpoints remain geometric, and the new quiet-save deadline doubles after each quiet callback. That addresses the previous disk-write objection. It does not make the replacement live path incremental end to end.

Findings (P1; block this revision)

  1. Full growing prefixes are now rebuilt/sized/delivered at display cadence. The introducing calls are Claude checkpoints:99 and Codex streams:138–152. For each below-checkpoint dirty 60 ms window, the live reader obtains the entire accumulated string, constructs a new row, and live publication:83–91 calls form(item). The unchanged wire-form:72–98 JSON-stringifies the whole new row; its WeakMap only saves repeated reads of that same object. Coalescer:119–122 also joins prefix plus new chunks when a changed stream is read. At steady growth, K display windows of d bytes entail d*K*(K+1)/2 prefix bytes before caps, not d*K. Codex formerly joined at growth checkpoints; Claude's per-window join already existed and is not itself a new regression.

    The local desktop explicitly omits text-append negotiation (read transport:38–42), so it receives full rows over IPC. Remote desktop and capable phones use append encoding, but only after the full-row sizing; their unchanged sender also checks text.startsWith(base). Shortened rows cannot use append encoding. This is host JS work, followed by transport cloning/serialization and renderer work; moving journal SQL to its worker does not remove it.

    Price: one subscribed 1 MiB reply at 16.67 updates/s means roughly 16.67 MiB/s of full-text sizing and full local-IPC payload, separately from joining and rendering. At 10 such views, 166.7 MiB/s; at 100 subscribed streaming agents, 1.63 GiB/s. With no transcript subscribers, the new Codex live-read/stringification work is zero; do not multiply by all 750 worktrees indiscriminately. The 16 MiB stream / 32 MiB coalescer limits and ~1.94 MiB client row limit cap size, not repeated cost.

    Required guard: production translator → live row → wire → local reader, K and 10K appends, counting joined/serialized/transferred prefix bytes; unchanged rereads must cost zero and real tail updates must remain visible. An incremental text representation/local append path must avoid doing full sizing before compression, while retaining initial hydration, correction, final flush and epoch recovery. No fix was made.

  2. New live frames still trigger history-wide renderer work whose answer cannot change. The new binary search removes one lookup scan and the retention scan, but history-state:115 still copies all H retained references. More decisively, the unchanged context-usage hook:17–19 depends on the changing journalItems; context-usage:75–83 walks all H rows twice to find clear/context facts for every reply-text update, returning unchanged facts. The new rowsBesideStreamedText memo base is not used there.

    The complete consumer trace also includes the unchanged message projection:89 identity scan, message-list reuse:48 scan, conditional subagent turn-neutral scan, /clear filtering, and hasOlder boundary scan. Do not describe the renderer as O(log H) just because row lookup is binary. The four modified projection/attention hooks are useful savings, but do not cover these consumers.

    Price for context usage alone: 2*H*16.67 row visits/s/pane = 33,333 at H=1,000 and 333,333 at H=10,000; ten panes multiply those by ten. Default retention is 1,024 own / 4,096 total plus live slack, but paging deliberately increases both limits, so 10,000 loaded rows is a supported workload. There is no need to reread every old context fact for a prose-only change. These loops predate the diff; newly calling them on almost every coalescing window is the amplification. Required guard: hold context/turn facts fixed, append one reply row at H and 10H, count fact/projection visits and unchanged outputs, including the actual desktop consumer chain. Preserve new rows, context clears, changed turn metadata and paging correctness.

  3. The equality gate precedes wire shortening, so long replies publish frames with no content change. Live publications:76–91 compares original live-row identity, then bounds it. Bounded-frame-item:12–13 limits a phone row to 72 KiB (576 KiB frame content / 8); desktop rows are limited to 2,031,616 bytes. Once an ASCII reply extends beyond that head and only its unseen tail grows, each new source object can produce the same shortened row, at the same durable revision/position. All below-checkpoint windows can therefore send no-change content: 16.67 frames/s, 16.67 no-change frames/s, roughly 1.17 MiB/s per phone or 32.29 MiB/s per desktop at their respective row ceilings. Ten subscribers multiply wire bytes by ten. shortened disables text-append encoding, even on capable remote clients. The receiver's equal-revision merge accepts the new objects and wakes consumers.

    A second no-change interleaving exists: durable catch-up:180 overlays a live row but does not pass the applied callback to advance liveSent. A queued live delivery that reads the same row afterwards can resend it. This is conditional, not an assertion of one duplicate after every checkpoint; opening desktop snapshots do seed liveSent correctly.

    Required guard: compare the final wire-visible value before emitting; test tails beyond phone/desktop ceilings, and durable-overlay → unchanged-live ordering. Preserve meaningful revision/lifecycle changes and full-content access. Counting original object changes is insufficient.

  4. Quiet processing joins Codex command output before the reply-only gate. Coalescer:141–142 evaluates joined(stream) before Codex's idle callback:149–152 tests isText(key). Every command-output stream receives this idle policy, although commands are intentionally excluded from live text and quiet saves. Example: save a 1 MiB command prefix, append four bytes below the growth threshold, then go quiet. The new callback joins 1,048,580 bytes for zero saves and zero live frames, including with no viewer. This repeats for later eligible quiet spells (with exponential spacing) and for each new command; it is not a perpetual idle loop.

    At 100 agents each running one such command, one quiet spell needlessly joins ~100 MiB on their execution hosts; at 10× agents, ~1 GiB. Per-stream/aggregate byte caps do not make this necessary work. Required guard: a non-reply stream below its growth gate must perform zero quiet joins/body builds/publications at N and 10N, while a quiet reply still saves and final command output remains correct. Gate before materialization/timer admission, not inside the callback that already received the text.

Evidence and reproducibility

Executed through TC_GATE_POOL=test tc-gate on this Mac, using the pinned checkout (still clean afterwards):

  • 5 files / 6 tests passed: claude-streamed-text-checkpoints.test.ts, codex-structured-journal-translation-streams.test.ts, agent-session-live-publications.test.ts, agent-session-delta-coalescer.test.ts, and structured-agent-session-reducer.test.ts via node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts with those exact file paths. They cover paused-tail visibility/quiet durability, refused checkpoint retry, eviction backpressure, matching revisions and ordering; they do not exercise a mounted desktop.
  • Temporary external probes imported the production translators, coalescer, live publication/wire forms and merge function; no repository test/code files were added. Fake-clock workload: first save 20,000 ASCII characters, then K appends of 16 characters spaced 60 ms, with 0 or 1 transcript subscriber. K=100 and K=1,000 were run on the head and with the base translator/coalescer modules extracted from the pinned base (shared surrounding helper dependencies; not a second packaged build).
Workload Base Head
K=100, either provider, 1 viewer 1 save / 20,000 saved text bytes; 0 live frames Same save count; 100 live frames / 2,080,800 full text bytes, 2,094,900 wire-form JSON characters
K=1,000, either provider, 1 viewer 5 saves / 128,400 saved text bytes; 0 live frames Same save count; 996 live frames / 27,899,600 full text bytes, 28,040,036 wire-form JSON characters
Codex K=1,000 join work, 1 viewer 108,400 joined string characters 28,008,000 joined string characters
Codex K=1,000, 0 viewers 108,400 joined characters; 0 live frames Same joins; 0 live frames and 0 live wire-form JSON
After the last append No quiet save in base Exactly 1 extra quiet save; 0 further saves/frames across another simulated 10 minutes; disposal leaves 0 scheduled timers and releases the live source

Only live frames are counted by that in-memory delivery port; the save column counts translator persistence calls, not physical SQLite transactions/bytes, and durable frames are not silently included in the live-frame column. Claude's string-join counter was unchanged between base and head, corroborating its pre-existing unobserved materialization.

Additional executed assertions: a 100,000-character phone row and a 2,100,000-character desktop row, each followed by two 16-character tail appends at the same durable revision, emitted 3 frames each, of which the last 2 had identical row content; wire row sizes were exactly 73,728 and 2,031,616 bytes. An unchanged same-object live reread emitted 0 frames. A durable overlay followed by the same live row emitted 1 redundant live frame. One revised row copied exactly 1,000 / 10,000 retained references at H / 10H while correctly skipping the retention rescan and preserving the text-independent memo base. A quiet Codex command joined exactly 1,048,580 extra characters, with 0 additional saves; disposal left 0 timers.

These are deterministic/source counts, not a measured renderer freeze, CPU percentage, RSS measurement, or disk-bandwidth measurement. The synthetic publication seam uses real translator stream owners/coalescer/live publication and wire forms with an in-memory commit/delivery port; it does not pretend to be a packaged Electron run or a full SQL-host benchmark.

Every changed piece of work: trigger → population → bound/owner

Changed work / files Trigger and population Bound, lifetime, and disposition
Claude text checkpoints, streamed thinking, journal translation Each dirty 60 ms window of each open message/reasoning key; growth save, quiet save, lifecycle flush and reattribution Host JS, two coalescer owners per translator. Growth threshold max(saved+32, ceil(saved*1.125)); additional quiet threshold starts at 1 s then doubles. Real message finalization forgets live state; translator teardown disposes it. Live path F1–F3; no new 400 ms disk timer.
Claude final-output coverage Each forwarded append/admission Passes one optional committed callback through; O(1), no extra provider client/process or standalone scan.
Codex streamed-item-body and item-streams Replies/reasoning/plans publish between growth saves; commands retain old growth checkpoint path One translator/coalescer, ordinary stream/state cap 256; protected long-lived commands follow existing retention exceptions. F1–F4. Normal forget/eviction/disposal also forgets live rows.
Codex journal sink Each accepted item save Forwards callback once and retains existing publication; refusal remains an admission result.
Codex journal translation Token-usage notifications Stops forcing the all-stream flush on token-usage notifications; other lifecycle barriers still flush. Reduces rather than adds prefix saves.
Shared delta coalescer and extracted delta-prefix Nonempty delta; dirty-window flush; per-stream quiet timer Incoming byte accounting is O(delta); existing 16 MiB/key, 32 MiB/owner and 256 ordinary streams. One flush timer/owner, at most one quiet timer/key; unchanged joins reuse one string. Quiet callbacks stop after firing; continued input can wake/rearm them, not continuously save. Empty delta is now a no-op. Prefix/truncation implementation moved unchanged.
New live-text rows Successful commit records placement; observed live read visits placed keys O(M) placement traversal per read, body rebuilt only when placement/length changes. Sources bound once; clear on forget/dispose; epoch/hold checks reject old placement. Newly retained shown rows and per-subscriber sent rows are real extra memory, not covered by the raw chunk counter.
Event sink and resolved append Append callback after writer result Existing full-body admission estimate remains; new WeakMap builds one O(B) index per committed result array, then O(1) lookups for its callbacks, not B scans/callback. Callback threading does not add a SQLite write.
Dispatch and attach orchestration Live publication admitted to sink Defers read instead of materializing it before subscription interest. Existing publication-key coalescing and journal ordering apply. No subscriber means zero live row reads, though publication admission/read-order bookkeeping still occurs.
Live-publications and subscriber state Per live publication × transcript subscribers, plus initial/reset/durable overlays O(M) fresh filtering/map rebuilding per subscriber, wire form shared by row object; actual wire row bounds as above. F1/F3. A durable overlay visits P delivered rows plus M live rows, not all journal rows.
Subscriber catch-up and subscribers Open/reset/catch-up/live delivery Lazy read at queued delivery; overlays only matching durable revisions. Desktop opening snapshots seed liveSent; bounded phone snapshots follow with a separate live batch; ordinary durable catch-up does not seed it. Existing serialized subscriber promise queue remains (see limits below).
Reducer and history-state Every received revision batch New O(I log H) lookup plus O(H) array copy, skips retention traversal for stable positions/ownership. Insertions/removals/moves fall back to existing merge/retention. F2 remains downstream.
New streamed-text-rows Compare incoming non-user message shapes; retain a memo base Two metadata/block-type JSON shapes per revised message, excludes text; one WeakMap base, flattened rather than chaining every old revision. Retains an earlier array while current text-only revisions live.
Renderer context-clear-floor, turn-timing, transport-state, attention-read-observation Read-owner update / React render Reuses text-independent row base for clear-floor lookup, turn/activity/background projections and attention observation. WeakMap attention cache keys rows plus epoch/submissions/fence/actionable IDs. Saves those derivations; context usage and transcript work remain F2.
Three changed/new test files Test execution only Claude/Codex paused-tail cases and matching-revision live overlay; Codex manual scheduler now excludes quiet timers. No application runtime cost. These cases alone do not assert production listener fanout/byte/retention budgets.

Publication/listener census at the audited head

Rates below count application data frames, not WebSocket heartbeats or display refresh. Idle means a connected, already-hydrated owner after its last quiet/lifecycle work settles: 0 frames/s and 0 no-change frames/s on both publication paths. Opening/reset is a finite snapshot burst, not idle cadence. Let f ≤ 1000/60 = 16.67 dirty windows/s for one continuously growing stream, D = durable commits/s (growth + quiet + explicit lifecycle), S = transcript subscriptions to this session, M = placed live keys, H = retained client rows. Multiple independently ticking stream owners can add publications; actual frames can be fewer through sink coalescing, cursor gating and row-identity dedup. There is no universal fixed D.

Listener / reachable consumer Live-text path under load Durable path under load; no-change disposition
AgentSessionSubscribers.bySession via sink → attach → publishLiveText; registered by host.subscribe/background-task channel → RPC agentSession.subscribe Only this session's S subscriptions. Up to S*(f-Dgrowth) live frames/s in the simple one-stream steady case. No subscribers: 0 frames and 0 reads. Same-object reread: 0 frames. Each save also has commit-driven delivery and the translator's explicit publish; thus up to two delivery attempts/save, not two guaranteed frames. Cursor catch-up and unchanged field gates normally leave one changed batch/subscriber/save. Existing row-free explicit publication still re-enters status/queue observers.
Local desktop read transport / shared read owner / event coalescer / reducer Full rows. One active transport per target+session; subscribers to that owner share it. Assistant events have 48 ms client coalescing, which does not merge regularly spaced 60 ms updates; reasoning can bypass it. Same reducer/owner. Ordinary growing unshortened text has about f total data frames/s across live and growth saves, normally 0 no-change content frames; F3 adds conditional duplicates.
Desktop useSyncExternalStore listeners and their session/transcript UI Every new state wakes owner listeners. Usage, message projection, list/fold/subagent grouping, /clear filter, timing/attention, and markdown/reveal consumers are included above. Modified text-independent hooks reuse their memo; unchanged hooks still run. Same path at D plus lifecycle. DOM paints are not inferred from data-frame counts; existing reveal animation can request display frames between data updates. Hidden pane activations release the transport when the last visible owner deactivates.
Desktop command-change listeners and PR-link observer inside the read owner Command listeners: 0 calls for pure text; PR-link observer checks incoming rows but searches workspace tabs only if a tool-output PR link exists, so prose does not fan out over worktrees. Command hints/openings and relevant tool-output links only; not one workspace scan per reply frame.
Remote desktop transcript, including SSH/WSL/paired-runtime transport Same session subscriber; negotiated append encoding for unshortened text saves wire bytes, not host sizing/prefix checks. Legacy/fallback clients receive complete rows. Same ordering/catch-up path. No extra provider subprocess per publication.
Mobile transcript (mobile-structured-transcript-subscription, shared live reader) Bounded frames, then capability-dependent append encoding. At >72 KiB row ceiling, up to f frames/s and f no-change-content frames/s between saves; source identities change although bounded output does not. Initial bounded page plus separate live batch; batches can split at 576 KiB content. For the one-row workload no split multiplier. Meaningful durable metadata still advances.
Host status projection → savedStatus.observe 0 invocations/frames. Up to 2D publication attempts; same-authority pending/read cache shares SQL work. Saved record compares turn-edge identity: 0 record writes/s for steady prose, even though callback runs. SQL observer selects current work/indexed populations and latest assistant evidence; it is not a proven whole-history scan per live frame.
Status feed subscribers: desktop shared per-target status owner → status bridge and per-session option/sleep readers; mobile shared status feed; other RPC clients 0 frames. Changed summaries only. For a stable long assistant prefix already beyond the normalized 200-character preview, steady appended prose yields 0 status frames/s, 0 no-change status frames/s; while preview/semantic state changes, ≤ publication rate. No status frame is owed merely because cursor/revision advanced.
Status sink/ownership → host agent-status/sidebar consumers; onSessionStatusChanged runtime observer 0 calls. After summary/input equality gating; normally 0 semantic updates for stable long prose. Location changes/child work/real status changes still publish. Saved-status callback is before that gate, as distinguished above.
Turn-completion feed → host-attention-delivery, optional host-turn-attention, RPC/desktop turn-completion feed 0 calls/frames. Projection evaluated at durable publication, but running prose raises no completion/prompt edge: 0 frames/s, 0 no-change frames/s. Emits on actual settlement/prompt transitions; reconciliation is not a per-token broadcast. Mobile transcript/status are separate from these completion subscribers.
Send-settlement waiters 0 wakeups. Up to 2D checks for each pending waiter; maximum 64/session and 1,024/host, normal 30 s deadline (explicit startup wait can be longer). No stream frame; unchanged pending state resolves nothing.
Queue onJournalActivity; host delivery afterCommit 0 calls. Commit route passes inputChanged, skipping input drain/afterCommit for pure prose. Existing explicit publish() defaults inputChanged=true and can schedule drain again; this redundant route predates the span. No extra 16.67 Hz queue wake from live text.
Commit request-failure observer, PR-watch committed-row observer, prompt-submission telemetry 0 calls. One callback/commit, inspecting the commit's changed rows/receipts, not all worktrees. Pure prose causes no new request failure/accepted-prompt telemetry/finished-PR-action output. PR-watch open-journal observer immediately unsubscribes after obtaining its seed; it is not a permanent extra stream.
workChanged/runtime activity refresh; settled-turn routes and bound sink listeners 0 commit/settled-turn signals (live publication has zero work-operation count). Commit activity refresh; terminal-turn routing scans changed commit rows and invokes bound callbacks only for terminal turns. Pure reply revision has 0 terminal-turn callbacks. Snapshot/epoch-replacement routes act on replacement, not every live update.
Conversation-publication observers: automation run observer; parked-mail redrive observer 0 hints. One commit hint per observer/commit. Automation compares its interest fingerprint and coalesces rereads; mailbox rejects streamed revisions via inputChanged/inserted/deleted/turn tests, so 0 mail redrives/s for pure prose. Relevant mail changes use 300 ms trailing / 2 s max-wait coalescing. These callbacks are not wire frames.
observeJournalPublications registry 0 callbacks. publishJournal visits registered observers, but repository production-call-site census found no registrations of this API at this head; do not invent an extra consumer.
Fork-marker, command-inventory and background-task channels No independent trigger from live text. Per-live-frame field builder checks cached commands/current projection; already-published roster and queue fields are withheld/reused. Their own actual source changes can publish; they are not periodic reply listeners. Pure prose does not imply a whole-roster frame.

No-change rates are workload-specific: 0/f for ordinary unshortened growth, f/f after a stable shortening boundary, and conditional duplicate batches after durable overlay. A status/queue callback doing a check is not a transmitted no-change frame. All of these registrations and downstream paths were inspected in head code, including unchanged files; this is a static census, not a claim that all optional subscribers were mounted on this Mac.

Six-question disposition / regression-class screen

Skill question Disposition
Work before skip gate Findings 1, 3, 4. Subscriber-interest gate improves lazy live reads, but wire equality and command-type admission occur too late.
Ownership/fanout Session-scoped transcript subscribers, shared renderer owner and per-target status feed traced. No 750-worktree fanout invented. Per-view full bytes/history work priced in findings 1–3.
Thread/storage Provider/coalescer/row sizing/publication JS runs on execution-host main; journal writer/reader use worker ports and node:sqlite; renderer projections run on renderer thread. Commit body estimates/IPC still copy full checkpoint prefixes. No measured stall/CPU claim.
Growth/progress Geometric durable saves survive; quiet saves back off. Live prefix/history growth remains findings 1–3. Cursor/epoch matching, bounded wire heads, catch-up replacement and finalization paths inspected.
Host differences Local desktop, remote desktop/SSH/WSL transport and phone source paths examined. No new OS-specific probe/spawn. Mac deterministic checks only; Windows/Linux/WSL/live network performance not executed. Folder workspaces add no git-dependent work here.
Stop/release/idle Quiet timers are one-shot and cancelled on forget/evict/dispose; live sources release on teardown. Ordinary connected idle frame rate is zero. Hidden/unobserved command materialization is finding 4; existing Claude unobserved joins remain. Slow-delivery queue/backing-memory limits below remain unmeasured.

Touched regression classes: streaming whole-prefix reprocessing F1; repeated unchanged input/output and no-op publication F3; history-wide derivation/identity churn F2; hidden/unobserved work and admission after construction F4; fixed timers not a permanent idle loop, but active-stream quiet checks remain; whole-row durable writes geometric growth plus logarithmically spaced quiet saves, not fixed 400 ms; per-entity lifetime normal disposal checked and forget paths inspected, caveats below; eager startup imports small local modules only, no new SDK load/client; subprocess-per-event no matching new path. The prefix utility move adds no new algorithm. No CI/build/infrastructure changes.

Pre-existing costs and remaining evidence limits

  • Claude already joined text before checking its growth threshold, even with zero viewers. At f windows/s this is f*currentPrefixBytes per active stream; head caching helps unchanged rereads but does not remove changed-window joins. Existing checkpoint saves still JSON-estimate, serialize and store whole prefixes. For uninterrupted geometric saves, their prefix sum is O(final bytes), roughly ≤9× the last checkpoint (plus initial/small-threshold and final/lifecycle costs), rather than K full rewrites.
  • The commit-driven plus explicit durable publication routes, the remaining renderer identity scans, and full local-row transport existed before this span. Their new live-trigger frequency is the regression where noted; their existence alone is not charged to this diff. Status projection invalidates on durable cursor movement but has indexed/current-work readers, so I am not carrying forward an unsupported claim that every live frame scans tens of GB of history.
  • The subscriber promise chain has no explicit pending-count cap or latest-live replacement at its own queue boundary. A blocked delivery can accumulate live closures at the publication rate; sink coalescing does not bound already-enqueued subscriber work. Cancellation skips deliveries but does not remove already-chained promises immediately. No slow-transport/blocked-reader experiment established the sustained production backlog here, so this remains an unresolved overload candidate, not a clean bill or a measured leak.
  • Raw coalescer byte caps do not bound every retained object: shown/liveSent caches, an earlier text-only memo-base array, and already-delivered client histories add storage. liveSent may retain the last live rows until replaced/reset/unsubscribed. Claude metadata maps are lifecycle-owned and not globally capped by coalescer eviction; this pre-existing metadata-retention pattern needs an adverse many-key run to price the added placement/shown maps. Normal disposal is not proof of an aggregate 100/1,000-agent heap budget.
  • No packaged Electron/UI stall trace, physical SQLite write-byte trace, adverse huge-history SQL profile, real mobile bridge, Windows/Linux run, or slow SSH transport was executed. Those limits do not demote the source-proven repeated work above. Fix verification should include a real long visible reply, pause/resume, clear/turn boundary, hidden/closed view, refused save and reconnect, without sacrificing the timely tail display this PR is intended to restore.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

@OrcaWin — this head takes the second route from your closing note: streaming previews stay out of durable storage.

The reply's newest text goes to the screen every 60 ms through the existing live-text path, which writes nothing to disk. Saves are back to main's rule (the first text, then every ~12.5% of growth), plus one save after a second of quiet and the save at completion. Measured on the M4Air against main 4939ff1, with the same harness as before (5 fresh databases per length):

Reply Saves main / PR Logical UPDATE bytes main / PR WAL high-water main / PR Reopen median main / PR
32 KiB 46 / 46 419,182 / 419,182 3.43 / 3.49 MB 153 / 154 ms
256 KiB 63 / 63 2,733,924 / 2,733,924 6.71 / 6.79 MB 162 / 126 ms
  • Durable write volume and settled size are identical to main at every length (the previous head wrote 218.6 MB at 256 KiB).
  • journal_rows is never touched, and reopen is unchanged.
  • Screen updates during a 256 KiB reply went from gaps of up to 65 s on main to a steady 60 ms.
  • Real Claude and Codex runs paused mid-reply showed the paused tail on screen within 369–445 ms, saved it within about 1 s, and kept it across a reload.

The bundled changes from the first round are gone; this PR is only the stream display and save cadence. Full tables are in the PR body.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf-scan verdict: BLOCK — P1 performance regressions remain at ece566eaddd042b02a65335e1df71c66d706e8e6.

Audited only 4939ff194f76c9f06c54373ec52a26d8840ae0d8..ece566eaddd042b02a65335e1df71c66d706e8e6, including unchanged producers, publication consumers, desktop IPC/renderer and mobile. The old 400 ms full-save implementation is not the comparison. This head restores the geometric durable-write gate and adds an ephemeral live-text lane: that is a material improvement, but it does not remove repeated full-prefix and history-wide work from that new lane. No code was edited.

Findings

  1. P1 — the new 60 ms live lane repeatedly materializes and serializes the entire growing reply; local desktop sends that whole prefix over IPC. Introduced by claude-streamed-text-checkpoints.ts:99 and codex-structured-item-streams.ts:138 calling live publication below the durable growth threshold. At agent-session-subscriber-live-text.ts:167–176, each new source row calls form(source) before the send/no-change gate. The unchanged agent-session-item-wire-form.ts:74–79 calls jsonBytes on the full row. The object cache helps repeated reads of the same prefix, not the next prefix. structured-agent-session-live-text-rows.ts:62–79 requests a snapshot; agent-session-delta-coalescer.ts:122–125 joins the prior prefix plus new chunks. Local desktop deliberately does not negotiate append frames (structured-agent-session-read-transport.ts:39–42), so its real production subscription sends the full row. Remote desktop/capable phones use append encoding, but only after host wire-form serialization, and the sender still checks text.startsWith(base).

    Price: with one growing row of L bytes and occupied 60 ms windows, this is about 16.67 × L bytes/s per viewed session for each full-prefix pass, plus 16.67 × L × local subscribers bytes/s carried over IPC (before envelopes). At 1 MiB: 16.67 MiB/s for one view; ten views: 166.7 MiB/s; 100 independently viewed agents: 1.63 GiB/s; the 1,000-agent stress dimension is 16.3 GiB/s. These are byte-work counts, not measured CPU or bandwidth. Hidden/unsubscribed sessions must not be multiplied by the viewer count: Codex's lazy read avoids this join when unobserved; Claude's pre-existing coalescer already joins before its growth check. Before this span, these Claude/Codex transcript deliveries were growth-gated; now the below-threshold windows reach the expensive path too. For K equal additions, full-prefix processing is proportional to K*L0 + delta*K*(K+1)/2 until the size cap, whereas delivered new text is K*delta.

    The no-viewer gate is also late: both providers still call live.publish() below the save threshold even with S=0. createLiveTextPublication submits a publication-key operation; StructuredAgentSessionDispatch.seal performs a journal-order readInOrder barrier before AgentSessionSubscribers.publishLiveText finally finds an empty subscriber list. The probe's unobserved Codex stream makes 985 such live requests in 60 seconds (16.42/s), even though it makes only 15 incremental saves. That is about 1,642 unnecessary host queue publications/s for 100 simultaneously streaming unviewed agents, or 16,417/s at 1,000. They carry no rows and emit 0 frames; the lazy-read change avoids payload construction but does not eliminate this newly added background work. An interest check before live-only queue admission must still let a later subscriber obtain the latest overlay and preserve durable saves.

    The finite bounds do not make this cheap: retained stream text is 16 MiB/stream and 32 MiB/coalescer; desktop row form is about 1.94 MiB, phone row budget 72 KiB (576 KiB frame content divided by eight). Oversized live prefixes are still serialized before shortening and sameSentForm; therefore zero outgoing frames can still conceal repeated full-prefix work. Keep durable placement/recovery, but carry or cache incremental live content before whole-row sizing/IPC, including local desktop. Verification needed in the PR: production-seam byte/serialization counts at K and 10K, visible/unobserved, multiple subscribers and already-shortened rows; meaningful append/final/reconnect controls. Simply reducing render count does not guard this.

  2. P1 — newly frequent text-only frames still invalidate history-wide transcript derivation. The new reducer fast path (structured-agent-session-history-state.ts:86–147, called at structured-agent-session-reducer.ts:274) avoids rebuilding indexes/sorting and skips retention scans for in-place revisions. The new text-only base protects projections whose other dependencies remain stable; finding 3 covers the important exceptions. It does not protect the unchanged desktop call at use-structured-agent-session.ts:208–215, or mobile use-mobile-structured-transcript.ts:64–85: each fresh items array runs withNativeChatCutTurnNotices, then the message projection. native-chat-cut-turn-notice.ts:187–204 walks the history to derive notices that cannot change when only reply text changes; each unexplained cut turn additionally scans its remaining suffix in lastRowOfTurn (:127–148). structured-agent-session-message-stream.ts:89–121 walks every prior item even when only one row changed. The reducer also calls agentSessionHasOlderTranscript on each update, which scans H rows when hasOlder is true and no clear divider is loaded. The O(H) array copy in replaceItemsInPlace should not be described as an O(log H) whole update.

    Price: at 60 ms occupied windows, each full pass visits 16.67 × H × mounted transcript consumers rows/s, although a text-only update cannot alter the notice result. H=1,024 and 10,240 means 17,067 and 170,667 visits/s per pass per pane. At ten such panes that is 170,667 / 1,706,667; cut-turn suffix scans add O(C*H) per update. History limits are not a fixed lifetime bound: default 1,024 own/4,096 total rows plus slack grows with explicitly retained/paged history. This does not visit all 750 worktrees; the population is retained rows in each actual transcript consumer. The loops predate the span; their new below-threshold trigger rate is the regression. At a 100 kB reply growing 100 bytes/60 ms, the 12.5% gate previously delivered roughly 0.13 checkpoints/s, while the new view can receive 16.67 text updates/s.

    Keep the live cadence, but invalidate non-text notice/clear derivations on their actual inputs and update text-bearing projections by changed row identity. Verification needed: production desktop/mobile projection operation counts at H and 10H with one changing reply, including old unexplained cut turns and a meaningful lifecycle/clear change. The new memo lookups alone do not establish that the whole renderer is independent of history.

  3. P1 — live host-work restatement defeats the new timing and attention memo gates after IPC/JSON cloning. agent-session-subscriber-live-text.ts:190 adds hostWorkFields(subscriber) to every live row frame, correctly preserving the receiver's existing restatement contract. However, the unchanged batch field reducers (structured-agent-session-live-turn.ts:137–165) adopt each incoming latestTurn object and actionablePromptIds array without preserving equal-value identities. Local src/main/ipc/runtime.ts:155 uses Electron sender.send; remote/phone JSON decoding likewise creates new objects. Thus the newly changed use-structured-agent-turn-timing.ts:33–36 and mobile timing hook invalidate [rows, submissions, turnId, latestTurn] on every live frame even when rows is stable. selectStructuredAgentTurnBars rebuilds turn anchors/maps over retained history. The new attention cache (structured-attention-read-observation.ts:27–35) also misses because prior.inputs.actionablePromptIds === state.actionablePromptIds is false even for freshly cloned empty arrays, and runs projectStructuredAgentSessionStatusState again. Background-task projection also depends on latestTurn.

    Price: up to 16.67 history projections/s per visible chat instead of a stable memo hit, even though every one of those frames carries unchanged turn/prompt metadata. At H=1,024 / 10,240, each full history pass is at least 17,067 / 170,667 row visits/s per consumer; 100/1,000 actively viewed agents multiply this independently, not every background agent. This is distinct from finding 2's ungated notice loop: these attempted gates fail at the real serialization boundary. A same-process object-identity fixture misses it. Preserve equal semantic host-work identities in the reducer or use appropriate semantic cache keys without dropping required restatements. Required guard: construct frames through structured clone/JSON, apply the production reducer, and count timing/attention projection work at H and 10H; real turn/prompt changes must still invalidate.

Rate model and listener census

These are source-derived application-event rates for an established, caught-up connection, not a running-user-machine listener inventory or compositor FPS. Counts exclude startup snapshots, reconnect resets, lifecycle edges, unrelated usage/tool/background-task events and transport heartbeats. The W/D model below describes the newly added Claude/Codex lane; the separate generic-source row records its different no-change behavior, which also applies when that source uses any of the listed transports. “Idle” means no provider input and any owed quiet save has settled. “No change” means unchanged application content, not merely an unchanged durable cursor: equal-cursor text batches contain real text changes.

Let W be occupied coalescing windows/s (maximum approximately 16.67 for one continuous stream), D the growth/quiet/lifecycle durable checkpoints/s, and S the actual subscribers to that session. For uninterrupted text-only streaming, the extra live lane is approximately W−D; total transcript updates are approximately W, subject to queued-delivery coalescing. D is not 2.5/s or 1/s: length must reach max(previous+32, ceil(previous*1.125)); quiet starts at 1 s after the last delta, doubles after each quiet callback, and emits no repeating idle saves. At steady g bytes/s and a large prefix L, growth saves are roughly g/(0.125*L) per second. First/final frames are additional finite edges.

Publisher / every production recipient category at this head Owner/population and work Idle frames/s (unchanged) Continuous text-only load; unchanged frames
Live-text sources → AgentSessionSubscribers.publishLiveText Two Claude sources (reply and reasoning), one Codex source per translator. One lazy read per actual subscriber delivery, these Claude/Codex source objects reused across readers. No subscribers means no source read in this publisher, but live queue admission/ordering still happens (finding 1). 0 (0) W−D live requests/session; up to S*(W−D) emitted batches; 0 unchanged-source batches. Same object is skipped before form; identical shortened visible text is skipped after form.
Existing generic timeline live source → same subscribers provider-timeline-text-streams.ts:264 reads all A open streams per delivery; provider-timeline-text-stream.ts:31 creates fresh row objects even for unchanged text. Unlike the new Claude/Codex source, these objects cannot hit the identity gate/cache across reads or subscribers. 0 (0) Pre-existing dirty-window requests up to W per dirty stream plus plan.onPublished requests after saves; dispatch coalescing may combine them. Each surviving delivery can carry A unshortened rows, even if only one changed: at one delivery/window, W*(A−1) unchanged row payloads/s. A repeated post-save live read can also emit a wholly unchanged unshortened batch; its exact rate depends on save/delivery ordering (0 through the surviving repeated-publication rate), not guaranteed zero. Same shortened-form gate still suppresses unchanged shortened rows, after forming them. This cadence and fresh-row producer predate the span; applying wire-form sizing on this path is changed work.
Local desktop transcript RPC → IPC → shared read owner → useStructuredAgentSessionRead structured-agent-session-subscribe-method.ts → structured-agent-session-subscriptions.ts → structured-agent-session-read-transport.ts → structured-agent-session-live-read.ts. One active transport per (sessionId,target) read owner, not per hook; multiple view listeners can share it. Local carries full rows. Visibility deactivates the transport when no active view owns it. 0 (0) About W including D; ordinary assistant batches have a 48 ms client coalescer, so 60 ms host traffic ordinarily remains about 16.67 updates/s. 0 unchanged Claude/Codex live-source frames; durable revisions can restate already-shown text, but advance the durable revision/cursor.
Remote desktop transcript Same read owner/reducer/UI, environment target negotiates text appends; RPC/remote transport handles one stream per owner. 0 (0) Same W frame cadence; append payload for supported unshortened rows, whole-row fallback otherwise. 0 unchanged Claude/Codex live-source frames; host full-prefix sizing still paid.
Phone transcript, direct or desktop-relayed mobile-structured-transcript-subscription.ts and the shared live read/reducer; actual mounted phone session readers. Host bounds/splits frames; relay forwards, not an independent journal/status observer. 0 (0) Same logical W for one fitting row; multi-row/side-list frames may split, so no universal physical-frame cap of 16.67. Capable phones request append encoding; old clients use full rows. Unchanged shortened live rows: 0 frames after expensive form comparison.
Durable row commit → conversation publication observers StructuredAgentSessionConversations is the production journal.observeCommits registration. It notifies optional automation-run observers and orchestration parked-mail redrive listeners for this session. PR-watch's conversation observer is a one-shot journal lookup and immediately unsubscribes. 0 (0) D commit callbacks per registered observer, all commits real. Automation inspects commit/semantic interest; redrive uses relevance plus 300 ms trailing/2 s maximum-wait coalescing. No live-text callbacks. These callbacks are not network frames.
Durable commit → runtime activity, settled-turn routing, request failures, PR-watch committed rows, prompt telemetry structured-agent-session-publication-wiring.ts, structured-agent-session-conversations.ts, structured-agent-session-settled-turn-routes.ts; one host owner/session plus actual optional listeners. Settled-turn route reaches the sink and generic timeline assembler only for terminal turn rows. Snapshot routes run at initial acquisition/epoch replacement, not per reply tick. 0 (0) D bounded changed-row inspections/activity refreshes; 0 settled-turn/request-failure/prompt/PR-action output events for ordinary prose. No live-text notifications.
Durable commit fan-out → transcript subscribers deliverFrames → deliverToSubscriber; catches up cursor, merges matching live overlay, remembers what was sent. Initial/reset phone pages follow with live rows because their bounded page cannot be enlarged in place. 0 (0) D changed-row batches/subscriber for one fitting row, included in W above. A checkpoint can repeat the displayed prefix but is a genuine persistence/cursor transition. No repeated empty batch solely because publish() runs again at the same cursor with unchanged fields.
Durable publishJournal → host status projection StructuredAgentSessionClientDelivery.publishJournal calls status, send settlement, queue activity and journal observers. Commit delivery and provider sink.publish() can both enter it; they are callbacks, not two guaranteed wire frames. structuredStatusSummariesEqual gates status broadcast; preview is bounded to 200 characters. 0 (0) Up to about 2D status/settlement/queue invocations for a normal standalone checkpoint (microtask/concurrent reads may combine); at most D semantically changed status frames, and 0 long-reply status frames once the 200-character preview and other status facts are stable. No W-rate live-text status fan-out.
Host status projection → saved status, status sink, status callback and status RPC subscribers Saved-status observer is called before equality, but writes only turn edges. The status sink updates runtime agent status. The status callback in workspace-process-listing.ts:284 feeds crew status/names, mail, worker activity, chat naming and first-turn workspace naming. agentSession.subscribeStatus broadcasts to registered desktop/phone clients. 0 (0) For the stable long-prefix workload: 0 downstream frames/writes/semantic callbacks; equality blocks them. During preview growth: changed summary events only, at most D per session; no unchanged status frames. Saved-status checks remain at projection-call rate, writes 0 while the turn stays open.
Host completion feed → host phone-attention delivery, host worker turn reporter, completion RPC → desktop per-tab attention listeners structured-agent-session-host-assembly.ts:103,129, structured-agent-session-turn-completion-stream.ts, renderer completion feed and StructuredAgentSessionAttentionBridge. One host feed; per-target desktop transport; per-tab local callbacks on actual edges. 0 (0) 0 prose-stream completion/prompt frames; completion/prompt lifecycle edges only. Current status projection is reused. No live-text subscription.
Durable publish → send-settlement waiters StructuredAgentSessionSendSettlement; at most 64/session and 1,024 globally; absent waiters cause no per-send scan; timeout/abort/close cleanup. 0 publication frames (0) Publication wakes inspect actual waiters, up to about 2D invocations; no RPC completion until the awaited send condition changes. No live-text wakes.
Durable publish → queued drain and delivery-order reconciliation Commit path respects inputChanged; pure output commits skip afterCommit/input drain. Explicit provider sink.publish() still defaults to inputChanged=true in publishJournal, scheduling existing queue work. 0 (0) Up to D extra queue-drain schedules from explicit publishes, even for prose; coalesced by session. This pre-existing duplicate wake is not a 60 ms live-text consumer. It produces no frame when no queue/send facts changed.
observeJournalPublications observer registry Exported through host, but repository-wide search finds no production registration at this head. 0 (0) Registry traversal has 0 listeners; do not invent an additional consumer.

Desktop renderer census beyond the wire: every live state publication reaches the read owner's snapshot listeners (useSyncExternalStore), then transport-state, context-clear, timing, goal, usage, attention observation, transcript notices/message projection, prompt/send/queue presentation and mounted transcript rows. The new rowsBesideStreamedText protects desktop current-context/activity, usage, goal and clear-floor derivations when their other inputs are stable; mobile protects usage, goal and clear-floor. Timing, attention and the background-task memo have additional reference dependencies that defeat the intended savings after transport cloning (finding 3). The renderer PR-link observer is called per applied batch but only examines tool output; prose does not enumerate worktree tabs. Command-refresh listeners fire on command hints/open, not every text frame. Read activity only reacts when submissions/queued-message identities change. Rail outline requests are keyed by epoch/oldest loaded position, not prose. Markdown has existing incremental block/tail rendering and paced reveal; DOM/animation FPS was not measured and is not equated to W. The retained-history passes in finding 2 remain upstream of that renderer optimization.

The separate desktop status stream is shared per target. Its repository registration census is: StructuredAgentSessionStatusBridge; naming observation; per-session status hooks/conversation name/naming failure; usage-limit auto-continue; async-question skip; AI Vault association observation; resume-run and resume-offer watches. Per-session listeners are keyed; global subscribers receive touched IDs. Window-close/busy/name lookup helpers only read its snapshot. The attention bridge also reads status for edge reconciliation but subscribes to completion edges, not live text. Phone status-feed consumers are agent history, host execution, async questions, usage-limit status and option-stamp/option-state. All inherit the 0 fps steady long-reply status rate, not the transcript's 16.67 fps. Opening a status subscription still seeds naming and retained-summary snapshots over that host's sessions; that startup cost predates the span.

Changed-work ledger (all 36 changed files, grouped by mechanism)

Changed files / work Trigger → owner/thread → population Bound / invalidation / disposition
agent-session-delta-prefix.ts; agent-session-delta-coalescer.ts Each provider delta → execution-host JS → incoming bytes; each occupied 60 ms window → retained streams; explicit snapshot → joined prefix. Prefix/truncation helper extracted. Joined text now replaces chunks for reuse. 16 MiB/stream, 32 MiB/coalescer, 256 ordinary streams; protected long-lived Codex command streams and generic timeline streams are exempt from the ordinary count limit and remain until lifecycle cleanup (pre-existing); their text shares the byte budget. Claude identity/latest-text maps can also retain coalescer-evicted entries until lifecycle cleanup (pre-existing). This scan does not claim an aggregate count cap for that exception. Append is O(delta), unchanged snapshot O(1); first read after append joins O(L). New zero-length skip; truncation is one bounded prefix construction. Findings above distinguish useful append storage from repeated live materialization.
Coalescer's new quiet timers One timer per eligible stream, plus existing shared window timer, on host JS; no timer allocation per token while already armed. First quiet requirement 1 s, then 2/4/8… s. Continuous input makes timer checks rearm for the remaining quiet period; a satisfied quiet callback doubles the requirement and stops until another append. Only satisfied quiet attempts are O(log elapsed time); timer checks during uninterrupted input are not logarithmic (62 checks/60 s in the independent deterministic schedule). Actual save only if length differs. Forget/eviction/dispose cancels. No fixed periodic durable rewrite.
claude-streamed-text-checkpoints.ts; claude-streamed-thinking.ts; claude-structured-journal-translation.ts Reply/reasoning windows → growth check → save or new live notification. Force flush/final/reattribution uses existing lifecycle ownership. Geometric +32/12.5% durable checkpoints, added quiet saves, final flush. Ordinary growth-save bytes sum O(final length), not K full saves. Claude still joins before threshold even unobserved (pre-existing). Two live registries per translator; final/settle/dispose removes entries.
claude-final-output-coverage.ts Each append through coverage wrapper forwards new committed callback. Constant forwarding; no new journal scan. Required to establish live placement after real commit.
codex-streamed-item-body.ts; codex-structured-item-streams.ts; codex-structured-journal-sink.ts; codex-structured-journal-translation.ts Agent-message/reasoning/plan stream windows → save gate; below gate live publication for supported text kinds; token-usage notifications no longer force text flush. Gate precedes join for Codex; hidden/no-reader avoids live snapshot construction. Tool-output stream bounds/cadence remain existing behavior. Pending checkpoint set retains final-save debt; refusal follows existing retry/barrier rules. Lifecycle/other notifications still flush. New callback forwarding adds O(1) per saved row.
structured-agent-session-event-sink.ts; structured-agent-session-resolved-append.ts Append admission → estimated body bytes and writer step; committed callback after outcome → lookup row. Existing serialization/worker write costs stay on durable path. One WeakMap index per returned committed-row array: O(B) construction shared by B callbacks, then O(1) lookups. No new history-wide scan.
structured-agent-session-live-text-rows.ts Live read → current placements only on host JS; body regenerated only when placement/length changes. Cache stores current source row plus placement per tracked stream, epoch check rejects old journal; forget/dispose release. No durable read for each row. Per-read O(active placements), full text read cost as finding 1; no repository/worktree inventory.
structured-agent-session-dispatch.ts; structured-agent-session-attach-orchestration.ts Live notification handed through ordered sink → bound session subscribers; pass a lazy read function instead of eager rows. Existing sink publication-key coalescing; attachment/journal identity gate; text read deferred until subscriber execution so older queued text cannot overwrite a newer save. A live-only sink dispatch still joins journal ordering; no database append.
agent-session-subscriber-live-text.ts; agent-session-live-publications.ts; agent-session-subscribe-input.ts; structured-agent-session-subscribers.ts Each live publication → S session subscribers, per-subscriber sequential delivery; remember source/sent rows and last host-work fields. Same-source and same-shortened-form gates, no empty frame, skip cursor mismatch, preserve required latestTurn/working/prompts. Per-row wire budgets, S*active-row scans. Source cache shared, subscriber sent map replaced with current rows. Finding 1. Subscriber promise chain has no separate explicit capacity; see unmeasured overload gap below.
agent-session-subscriber-catch-up.ts Durable incremental read / initial or replacement page → overlay live rows of matching revision; bounded phone page gets follow-up live batch. O(page rows + active live rows) per delivered page; default 40 / max 200 history count plus byte budgets. Only rows being delivered are overlaid; no additional whole-history fetch. Resets clear subscriber sent state; disposed subscribers stop delivery.
structured-agent-session-history-state.ts; structured-agent-session-reducer.ts Every client batch → binary lookup for revised rows, copy current array once, shape check, optional retention fallback. O(I log H + H copy), not O(log H) total. New/moved/ownership-changing/removal rows fall back to full merge/retention. Revised positions skip index rebuilding/sort/retention scan. Remaining hasOlder scan and UI scans: finding 2.
structured-agent-session-streamed-text-rows.ts Compare revised non-user message shapes → JSON metadata excluding text payload and revision; mark earlier non-text base in WeakMap. O(changed-row metadata/block count); one flattened base reference rather than an accumulating chain. No full reply-text stringify here; base lives while its dependent rows live, released with rows/owner. Meaningful shape/ownership changes invalidate.
Desktop use-native-chat-context-clear-floor.ts, use-structured-agent-turn-timing.ts, use-structured-agent-session-thread-goal.ts, use-structured-agent-session-transport-state.ts, use-structured-agent-session-context-usage.ts, structured-attention-read-observation.ts Each renderer state update consults text-only base; memo/projection cache hit for unchanged non-text inputs. Constant WeakMap lookup; substantive new row/host-work/submissions/fence/epoch changes still invalidate. Equal-value cloned host-work objects also invalidate timing/attention/background memos (finding 3). Remaining downstream history work is finding 2.
Mobile use-mobile-structured-context-usage.ts, use-mobile-structured-thread-goal.ts, use-mobile-structured-agent-turn-timing.ts, use-mobile-structured-transcript.ts Same shared reducer updates → corresponding non-text memo gates. Same invalidation rule, including cloned latestTurn defeating the timing memo (finding 3); mobile transcript projection/notices still run for changing text. No new transport owner or polling.
Three changed test files: Claude checkpoint, Codex translation-streams, subscriber-live-text CI/test execution only; fake timers/checkpoint placement, usage flush, overlay revision assertions. No app-runtime work. They do not assert downstream byte counts, renderer history visits, full listener fan-out, or slow-subscriber backlog. Validation results below.

Six-question disposition and regression-class screen

  1. Work before skip: finding 1 (full prefix form/shortening before no-change gate); Codex unobserved source read and same-source gate avoid bytes, but the unobserved live queue publication is still paid; Claude unobserved join predates the span. New projection memo gates are incomplete and some are defeated by transport cloning (findings 2–3).
  2. Ownership multiplication: reviewed. One shared desktop transcript read owner per session/target, one status/completion feed per target; S wire deliveries, M mounted UI consumers, and per-translator live maps/timers are the real multipliers. No multiplication by all worktrees/repos/terminals. Subscriber delivery queue overload remains unmeasured.
  3. Paying thread/storage: host JS joins/sizes/forms rows and does IPC; desktop renderer merges/projects/renders. Durable writes use the existing journal writer worker and SQL read/work paths; this is not a newly introduced synchronous SQLite write on Electron main. Full-body admission estimation/worker transfer remains on geometric saves. No elapsed stall/CPU claim is inferred from byte counts.
  4. Growth/progress: findings 1–2 for reply length and retained history. Satisfied quiet-save attempts logarithmic in stream time (not timer-check callbacks); durable growth saves logarithmic in length; stream bytes are capped, while protected identities are exempt from the ordinary stream-count cap. Retained client history can grow on paging. Cursor/epoch/revision matching and final flush maintain progress on inspected paths; overload latency not exercised.
  5. Host differences: shared TS traced for local desktop, remote desktop and direct/relayed mobile. Local IPC has the worse payload shape; remote append reduces transmitted text but not host sizing. No new git/shell/probe/SSH subprocesses, platform branches, startup SDK import or repo-only assumption. Windows/Linux/SSH and phone-device CPU/transport measurements were not run.
  6. Stop/release/idle: reviewed cancel/forget/settle/dispose, weak cache retention, epoch replacement, subscriber close/failure and read-owner visibility cleanup. Established idle publication rate 0. Necessary background durable buffering continues. Slow-client pending promise depth, crash/reload timing and aggregate heap were not measured; no blanket cleanup/performance pass claimed.
Touched regression class Disposition
Streaming re-processes whole message / per-prefix hot work P1 finding 1; durable-only geometric gate is preserved, live row materialization/sizing/local IPC is not incremental.
Update with no change Claude/Codex same source suppressed; generic fresh-row sources can still send unchanged unshortened rows at their pre-existing publication cadence; same shortened form suppressed after expensive work; stable status equality suppresses global frames. Explicit durable publish still repeats observer/drain work (pre-existing). No new periodic idle frames.
Full snapshots / history-wide derivation / broad invalidation Live sends changed rows, not all chats. P1 findings 2–3 for retained-history derivation and cloned metadata invalidation on a one-row text update; partial memo fixes confirmed.
Hidden/unobserved work / timers that never settle Codex live text reads viewer-gated, but unobserved live-only queue admission remains finding 1; Claude eager join pre-existing. Quiet timers stop and double their quiet requirement. No new idle polling loop.
Whole-file/whole-row writes and sync SQLite No 400 ms save loop or new whole-history/file flush. Per-item geometric writes plus quiet/final saves; SQL remains existing worker-owned path.
Resource lifetime / cache retention / fan-out queues New maps follow translator/subscriber lifetimes; WeakMaps do not form a prefix-history chain. Per-subscriber promise chains are sequential but lack an explicit pending cap; overload measurement missing, not declared clean.
Startup/import cost Small local helper modules only; lazy host/provider installation unchanged. First text still waits for its first committed placement; no cold-start timing measurement.

Evidence and limits

Executed the five relevant existing test files through TC_GATE_POOL=test tc-gate node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts, with ORCA_BACKGROUND_LAUNCH=1: Claude claude-streamed-text-checkpoints.test.ts, Codex codex-structured-journal-translation-streams.test.ts, subscriber agent-session-delta-coalescer.test.ts and agent-session-subscriber-live-text.test.ts, and shared structured-agent-session-reducer.test.ts. 5 files / 6 tests passed. These checks cover their existing assertions, not end-to-end responsiveness.

Production-seam probes also ran through tc-gate with actual imported implementations, manual coalescing windows, an in-memory sink/committed-placement callback and an inert subscriber emitter. The exact base coalescer/provider modules were extracted outside the repository and run against the same workload. Seed: 20,000 ASCII characters; append 100 characters once per 60 ms window. Results include the initial save, exclude lifecycle barriers, and deliberately do not simulate quiet timer expiration:

Operation count 100 windows 1,000 windows
Durable saves, both refs and both providers 4 16
Serialized durable body bytes, both refs/providers 96,796 904,684
Base live requests 0 0
Head live requests, viewed or unviewed 97 985
Codex base joined characters, viewed or unviewed 76,500 883,500
Codex head joined characters, viewed 2,505,000 70,050,000
Codex head joined characters, unviewed 76,500 883,500
Claude joined characters, both refs/viewer states (pre-existing) 2,505,000 70,050,000

A separate actual head-publisher loop sent each fresh row twice. It emitted 100 / 1,000 frames, zero duplicate unchanged-source frames, sized 2,505,000 / 70,050,000 text characters, and produced 2,533,900 / 70,339,000 cumulative whole-frame JSON bytes versus 42,700 / 427,200 after the actual append encoder. This compares JSON representations; it does not measure Electron structured-clone bytes or run IPC. With an already-shortened row, 100 further updates emitted 0 frames while full-form input contained 100,505,000 characters for a phone (1,000,000-character seed), or 300,505,000 for desktop (3,000,000-character seed).

An independent fresh performance reviewer reproduced a stricter below-checkpoint case with exact source functions in standalone Node: seed 262,144 ASCII characters, then 16 characters/window for 1,000 windows. Base Codex admission had 0 joins/0 saves after the seed; head had 1,000 joins / 270,152,000 characters and still 0 saves. Desktop form sizing generated 270,289,000 cumulative JSON bytes. Phone fitting made 24,075 stringify calls / 2,040,519,293 cumulative JSON bytes, emitting 0 frames. That is 3.40 GB/s at 100 independently viewed phone sessions, 34.0 GB/s at 1,000, of cumulative serialization work, not network traffic, resident memory or CPU duration. This harness used source-equivalent reader wiring and inert journal/emit adapters; it did not run a real phone or transport. Its deterministic timer run counted 62 idle checks during 60 seconds of uninterrupted input, no streaming save, then one quiet save and zero remaining timers; disposal also left zero timers.

Renderer/shared probes provide independent controls:

  • The actual revised merge at H=100 / 1,000 used 109 / 1,012 indexed array reads, reported rescan=false, and preserved the text-only base. This confirms the implemented merge improvement; it does not erase its H-reference copy.
  • Actual withNativeChatCutTurnNotices with H=1,024 / 10,240 rows made 5,120 / 51,200 body-property reads despite returning the original array. This is a direct counter of existing work reached at the new cadence, not a render benchmark.
  • Actual reducer plus attention projection, with a text-only batch passed through structuredClone, preserved the base rows but changed both latestTurn and actionablePromptIds identities. The observation key stayed equal while projection made 19,463 / 194,567 body-property reads at H=1,024 / 10,240. Repeating the exact same state made 0 reads. At 16.67 such updates/s this fixture implies approximately 324,383 / 3,242,783 body reads/s per attention consumer; these are fixture operation counts, not CPU estimates. Timing-hook invalidation was source-traced, not mounted in this probe.

The independent review corroborated full-prefix work, remaining shared-history scans and unobserved lane admissions. This report additionally traced desktop transport and cloned-metadata invalidation. Neither review claims a reproduced multi-second stall, a measured P0 threshold, or proof that pending subscriber chains are bounded under an independent delivery blockage.

Counts above price 100 active agents and 1,000 as the stress dimension, actual subscribers separately, and H/10H retained rows separately. The 750/7,500 worktree, repository/remote/ref and terminal-count dimensions do not enter these changed hot paths, so multiplying by them would be false. Tens of thousands of archived chats are not broadcast on live text; initial status hydration and historical SQL reads remain separate workloads. No build, app launch, external-machine QA, installs or code edits were performed. This scan proves work amplification, not that a particular multi-second stall was reproduced or that either suggested remedy is already validated.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: not ready. A performance decision is needed from Brennan. Head ece566eaddd042b02a65335e1df71c66d706e8e6.

Problem: long Claude/Codex replies froze on screen between saves. Change: reply text is shown every 60 ms through the live-text path, and saves stay on main's growth rule plus a quiet save and completion. Numbers and screenshots are in the PR body.

Verified on this head:

  • QA on the M4Air: durable writes are identical to main (32–256 KiB) and display gaps are a flat 60 ms. Real Claude and Codex pauses showed the paused tail on screen in 369–445 ms, saved it in about 1 s, kept it across a reload, and finished exactly L001–L400.
  • 40/40 local changed checks passed.
  • CI: 33 pass. The WSL2 debian-12 job hit its 45 min infrastructure timeout and is re-running.

Review:

  • Three Claude/Codex passes found correctness issues, all fixed: the write-barrier force-saves, phone frame overflow, host-work facts cleared by live frames, stale live frames and resent unchanged rows.
  • Those fixes were in the last commit, so no fresh reviewer pair has re-checked them.

Perf scan on this head: FAIL (report).

  1. An observed streaming reply is rebuilt, sized and sent whole to the local desktop every 60 ms. This is the same live-text design provider timelines use, and phones and remote desktops get appends. Passing needs an incremental live representation, including local appends, before row sizing.
  2. The transcript's cut-turn notices and message projection still walk the loaded history on each text-only frame.
  3. latestTurn/actionablePromptIds lose object identity across IPC, so the timing and attention memos miss. This is a small reducer fix that hasn't been made yet.

Deferred:

  • Live text pauses after a mid-reply epoch change until the next save.
  • The phone's offline transcript copy can lag until the next cursor move.

… the gap before it; compare block props without allocating

A reply that redraws whole showed each save in two back-to-back frames and then sat still until the next save. It now takes the same two steps spread over the measured gap between saves, on the shared reveal clock. The block memo compare ran for every block on every step and built two entry arrays and a Map each time; it now compares in place.
…d redraws

The previous commit spread a save on the shared step clock, which on a slow machine spaced draws further apart than the saves and could draw a save three times. A reply that redraws whole now draws half of a save's new text when it comes and the rest half the gap between saves later, off the shared clock; without a gap (the first save or the turn's end) the rest follows after the usual 350 ms. The gap rides in the reveal state, so a remount resumes on time. The block memo compare skips inherited keys, as the entries-based compare did.
…arrival, never draw a save back

A remounted reply shown at its saves resumes its save's reveal instead of finishing it at once. Only the last save's arrival is kept, since that alone times the next draw. The save reveal starts from whichever is further, the screen or the reveal, so a finished reveal (a turn's end, reduced motion) is not reopened.
…text over a held save does no work

A reply shown at its saves records which save's first half it drew, so reopening it schedules only the rest. Live text that arrives while it holds an unchanged save (another drawing of the chat still takes live text) no longer re-runs the reveal over the saved text. Only the last save's arrival is kept, since that alone times the next draw.
…ip the midpoint scan once drawn

A save that keeps its text (it changed only attribution) still moves the reveal's save revision, so a remount doesn't take later live text as a save. A remount checks whether this save's first half is drawn before finding its midpoint.
…nothing

When a save's remaining text is one unfinished word its midpoint adds nothing; recording the attempt anyway keeps a remount from scanning that word again.
…ing it every window

Every 60 ms window reads every streaming reply's text, and rejoining the chunks copied the whole reply each time, even for chats nobody is viewing. New text is now appended to the kept text, which a save or a shown reply flattens once when it reads it, so a window no longer allocates a reply-sized string per stream.
… from pinning larger strings

Each window's new text is now its own copy, so a delta sliced from a larger string can't keep that string alive, and the kept text is copied flat on the first join and then once every 64 windows that add to it, which bounds its concatenation chain at 64 links while still not copying a long reply every window.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan follow-up: PR #35462 at d71e4c8e65e

Scope: the PR's own changes since the last clean scan at e0fd5327c17 (8 commits plus two merge conflict resolutions). Code review only.

No introduced or amplified P0/P1 regression found at d71e4c8e65ea85ccea773cf97996284ebe4b471b. I reviewed every specified commit and both-parent comparisons for the merge resolutions.

One pre-existing P1, which does not block this span:

  • Repeated whole-word scans during streaming — native-chat-text-reveal.ts:104, through pacedTextEnd at line 43. Concrete input: a displayed 100,000-character ASCII word followed by more characters every 60 ms. Before the current arrival’s deadline, boundary detection scans forward to the string’s end and backward to its beginning: approximately L character-boundary checks per step, even when the displayed length stays unchanged. At 15 steps/s, that is 1.5 million checks/s for 100,000 characters and 15 million for 1 million characters, per mounted reply. Ten such mounted replies multiply that by ten; background agents without mounted replies do not. This work competes with renderer input handling. The same implementation exists at e0fd5327…; the new save-reveal path reduces repeated attempts. A deterministic guard should count boundary checks across appends and unchanged steps at those two lengths, while checking identical revealed output. These are source-derived counts, not measured latency.

The touched regression classes have these dispositions:

Class Disposition and evidence
Streaming reprocesses whole text; hot-path rescans Main coalescing replaces full-prefix joins on growth reads with owned additions and a full copy every 64 combining joins. Re-reading a consolidated stream copies no text. The pre-existing word scan above remains.
Work before skip gates shouldEmit still runs before joining. Live readers reject hidden/uninterested rows and over-budget text before reading it. Codex’s save-growth gate remains intact.
No-op identities and publications Unchanged save-paced text returns the existing reveal object; unchanged save revisions retain it. The markdown comparator removes entry arrays and a Map without broadening expensive renders.
Ownership multiplication and retained state Save pacing retains at most one arrival. Midpoint attempts are remembered, including attempts revealing nothing. Held reasoning state keeps one key; existing forget/dispose paths release stream state.
Fixed cadence, hidden work, idle wakeups Save reveals use at most one midpoint attempt and one deadline timer, cancelled on replacement or unmount. Completed reveals schedule none. This replaces an existing frame/deadline loop; steady-idle wakeups remain 0 → 0. Existing hidden normal-reveal scheduling is unchanged.
Collection derivation on streaming updates Rail structure uses constant-time weak-map lookups and stable structural identities. Prompt indexes avoid rebuilding for text-only revisions; live preview work is restricted to the selected turn.
Synchronous main work and eager imports The new string copier runs synchronously, but full-prefix copying is less frequent than baseline. No new filesystem, SQLite, subprocess, network, or heavyweight startup import was introduced.

All six scan questions were addressed:

  1. Admission: traced coalescer → checkpoint/live publication → reader-interest gates → renderer.
  2. Multiplicity: counted per-stream coalescing, per-mounted-reply reveal work, and per-transcript rail work; no new all-chat fan-out.
  3. Thread: string copying runs on Electron main; reveal, comparison, parsing, and rail work run on the renderer.
  4. Growth/progress: inspected byte caps, append-chain resets, arrival pruning, midpoint memory, and advancing deadlines.
  5. Host effects: changed mechanisms are platform-neutral. No new host-specific probing or remote round trips.
  6. Retirement: inspected timer cancellation, hidden delivery admission, collapsible-body unmounting, and stream/reveal cleanup.

Coverage includes the six requested files and their scheduler, markdown/reasoning consumers, rail builders, string copier, Claude/Codex/provider stream owners, and live-publication/visibility callers. Both merge resolutions preserve the relevant pacing and structural-identity mechanisms.

Each fading word was a span with an opacity transition, which the compositor gives its own layer; once a reply streams smoothly those transitions actually run, and the layers held hundreds of MiB of GPU memory while replies streamed (gone with reduced motion). Words now fade their own color from transparent, which repaints the word and creates no layer. Links, inline code and blocks keep their opacity fade.
A stream that has only ever had one delta returned that delta as is, so a delta sliced from a larger string kept the larger string alive. The first read now copies it, as later reads copy appended text.
When a stream's owner skips a window (Codex below its next checkpoint), its deltas stayed raw, so a delta sliced from a larger string kept that string alive. The skipped window now joins its text like any other read.
A reply that redraws whole draws each save in two steps on timers, outside the step clock that lets typing go first. Each of those redraws now waits up to four 50 ms turns while a key or click is pending, so the input is handled before the long redraw instead of after it. The input check moves to the reveal scheduler module, which both paths share.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: not ready. One open finding (typing latency), so this needs a decision.

Measured on the PR head against main (c475b79).

Better than main:

  • Low-spec Windows, footnote reply, 4 runs each: worst mid-stream gap 3.73 s (3.47–3.99) vs 5.33 s (5.15–5.59); long tasks 22.6 s vs 35.6 s; 8/8 correct.
  • High-spec Windows, 10 concurrent ~1 MB replies: main-process heap peak 193–226 vs 281–374 MiB; GPU 597–816 vs 1002–1393 MiB; renderer private memory 1.9–3.2 vs 3.3–5.2 GB. The renderer JS heap peak is wider (1164–1689 vs 864–1850 MiB); a reviewer judged that bounded and acceptable (memory: pass).
  • Typing while streaming, keystroke to painted frame p95: 541 vs 607 ms.

Open:

  • Typing while streaming, key-dispatch round-trip p95: 534 vs 402 ms (+33%). The reviewer still marks typing FAIL on this. One round (save draws wait for pending input) improved painted frames but not dispatch.

Checks: perf scan clean; latest code audit pass; real-agent QA pass on ef04467. CI is rerunning on 336f892, which fixes a max-lines failure from the main merge.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: code ready. One accepted trade-off.

Problem. Long native-chat replies streamed unevenly: the reply could stall for seconds mid-stream, and 10 long chats at once used a lot of memory in the main process and the GPU.

Change. Streamed text now appears in steady steps instead of stalls. A reply that is redrawn whole (footnotes) draws half of each new piece at once and the rest shortly after, waiting briefly while you type. The main process appends to each stream instead of re-joining it, and new words fade in by color instead of opacity, so they no longer each get a GPU layer.

Brennan's decision. While a reply streams, key-dispatch p95 is 534 ms vs 402 ms on main; keystroke to painted frame p95 is better, 541 vs 607 ms. Brennan accepted this trade-off for smoother streaming: "accept it".

Perf waiver (Brennan): "accept it" #35462 (comment)

Verified.
Benchmark: name=footnote head=36a83f78161d9c93a6a2a97a8998ff235127d1b4 gate=PASS low-spec Windows, footnote reply vs main c475b79, 4+4 runs: worst mid-stream gap 3.73 s (3.47–3.99) vs 5.33 s (5.15–5.59); long tasks 22.6 s vs 35.6 s; 8/8 correct. Listeners: one native chat pane, its reveal scheduler and the stream publication.
Benchmark: name=memory10 head=ef044674264a4cddd1102d942eca55e2d8304516 gate=PASS high-spec Windows, 10 concurrent ~1 MB replies vs main c475b79: main heap peak 193–226 vs 281–374 MiB; GPU 597–816 vs 1002–1393 MiB; renderer private 1.9–3.2 vs 3.3–5.2 GB; renderer JS heap 1164–1689 vs 864–1850 MiB (reviewer: bounded, pass). Later commits change only saves-only replies and the Codex-only coalescer path, neither in this workload. Listeners: 10 native chat panes and their stream publications.
Benchmark: name=typing head=36a83f78161d9c93a6a2a97a8998ff235127d1b4 gate=FAIL typing while streaming: key-dispatch p95 534 vs 402 ms (painted-frame p95 541 vs 607 ms). Accepted by Brennan, above.

  • Real-agent QA on 336f892 (high-spec Windows, real Claude): the footnote reply streamed in 25 growth steps and never shrank; footnotes rendered, the end marker appeared once, and the text was identical after switching chats and back. Mid-stream, a footnote reference shows as [^1] until its definition arrives at the end of the reply.
  • Codex regression audit on 336f892: SAFE (merge with main compared against both parents; moved failure-row hook unchanged). Perf scan clean; CI green on 336f892.

Deferred. The perf scan's pre-existing, non-blocking long-word scan in pacedTextEnd is a follow-up.

Mid-stream on 336f892
End of reply on 336f892

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Perf scan (fresh reviewer), head 7686535. Full scan of the PR at 88f1d54 found two P1s, both fixed (subagent sheet header rebuilt per text window: 2953abb; skipped coalescer windows re-copied the whole reply: 88f1d54). Incremental scans of the truncation fixes found two more P1s, fixed in 4303654 and b42c20d. Final incremental scan below.

No P0/P1 findings. The earlier clean result still holds for the two scoped files at 7686535aafdef265d61d1160d99424fa2f80b4e3.

Reviewed all five commits, the net diff from 88f1d542681, and the Codex, Claude, timeline, and live-text publication callers. The coalescer is byte-for-byte unchanged from the earlier clean head.

Regression class Disposition and evidence
Whole-text work past skip gates Disproved: shouldEmit precedes joining; skipped windows own only their new tail. Viewer interest and length gates precede live-text reads.
Truncation scans/copies the final delta Disproved: agent-session-delta-prefix.ts:66–98 never measures the final delta or concatenates the carry with it. Pair construction uses at most two code units; writes use remaining buffer capacity.
String retention Disproved: the carry is at most one code unit, and the final delta/suffix is not stored in the result. Truncation retains newly decoded bounded text.
Repeated work, ownership and timers Unchanged: truncation runs once per stream; subsequent appends bypass it. No new timer, owner, listener, or publication cadence.

Concrete adverse input inspected: current=['ab\uD83D'], currentBytes=5, delta='\uDE00'+'x'.repeat(N), deltaBytes=N+3, maxBytes=44, for N=1 MiB and 10 MiB. Both allocate a 10-byte head buffer and construct the same bounded pair. The coalescer’s existing input-byte measurement remains; truncation adds no whole-final-delta measurement. At 100 or 1,000 such stream truncations, these head allocations total 1,000 or 10,000 bytes respectively, without multiplying by N.

The six scan questions resolve as follows:

  1. Skip gates: preserved before joining or viewer text construction.
  2. Ownership: existing producer-owned coalescers; no additional consumers or resources.
  3. Paying thread/storage: synchronous work remains on main; added work follows required bounded output, with no new storage operation.
  4. Growth/progress: production limits remain 16 MiB per stream and 32 MiB per coalescer; truncation latches once.
  5. Host differences: no changed filesystem, subprocess, remote-call, or platform-specific behavior.
  6. Cleanup: carry is call-local; forget/dispose and timer cancellation are unchanged.

Evidence is source inspection on this Mac. The surrogate correctness assertions and existing N/10N live-text contract were inspected, not executed. No edits, app launches, delegation, or runtime timing/heap claims. The marker carries forward the supplied earlier full-scan coverage and adds the two inspected test files.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Status: code ready. One trade-off, accepted by Brennan.

Problem. Long native-chat replies streamed unevenly: a reply could stall for seconds mid-stream, and 10 long chats at once used a lot of main-process and GPU memory.

Change. Streamed text now appears in steady steps instead of stalls. A reply that redraws whole (footnotes) draws half of each new piece at once and the rest shortly after, waiting briefly while you type. The main process appends to each stream instead of re-joining it, and new words fade in by color instead of opacity, so they no longer each get a GPU layer.

Brennan's decision. While a reply streams, key dispatch is slower: p95 904 vs 764 ms on the low-spec run below (534 vs 402 ms on the earlier run). Keystroke to painted frame is better (928 vs 987 ms). Brennan accepted this for smoother streaming: "accept it".

Perf waiver (Brennan): "accept it" #35462 (comment)

Fixed since the last status (336f892 → 7686535). Main was merged again, and fresh reviewers found and I fixed:

  • A subagent sheet's header (new on main) rebuilt its switcher on every streamed text window; it now gets the structural map (2953abb).
  • Unwatched Codex streams re-copied the whole retained reply every 64 skipped windows; a skipped window now copies only its own new text (88f1d54).
  • Truncation encoded each chunk alone, so an emoji split across chunks became two replacement characters; it now writes the pair whole, without measuring or copying the final delta (91d12cc, 1a9cc0a, 4303654, b42c20d, 7686535; one invariant test added). b42c20d also reverts a stray lockfile change.

Verified on 7686535.
Benchmark: name=footnote head=7686535aafdef265d61d1160d99424fa2f80b4e3 gate=PASS low-spec Windows, footnote reply vs main cd3d912, 4+4 alternating: worst mid-stream gap 4.33 s (4.02–4.62) vs 6.00 s (5.68–6.64); long tasks 34.9 s vs 51.9 s; rAF p95 44 vs 284 ms; 8/8 correct. Listeners: one native chat pane, its reveal scheduler and the stream publication.
Benchmark: name=memory10 head=7686535aafdef265d61d1160d99424fa2f80b4e3 gate=PASS high-spec Windows, 10 concurrent ~1 MB replies vs main cd3d912, 2+2 alternating × 3 runs: main heap peak 154–217 vs 263–401 MiB; GPU peak 518–788 vs 460–1518 MiB; renderer process peak 1.7–3.9 vs 2.8–6.7 GB; renderer JS heap peak 844–1488 vs 804–1631 MiB; settled renderer JS heap 457–839 vs 820–1597 MiB. Listeners: 10 native chat panes and their stream publications.
Benchmark: name=typing head=7686535aafdef265d61d1160d99424fa2f80b4e3 gate=FAIL low-spec Windows, typing while the footnote reply streams: key-dispatch p95 904 (865–1,110) vs 764 (476–839) ms; keystroke-to-painted-frame p95 928 vs 987 ms. Accepted by Brennan, above.

  • Real-agent QA on 7686535 (high-spec Windows): a real Claude reply and a real Codex reply with footnotes each streamed without ever shrinking (18 and 58 growth steps). Footnotes rendered, the end marker appeared once, and the text was identical after switching chats and back.
  • Reviews on 7686535: the Codex regression audit says SAFE; the fresh Claude review passes; the perf scan is clean (comment above). CI is green.

Deferred. The perf scan's pre-existing, non-blocking long-word scan in pacedTextEnd is a follow-up.

Claude reply, end
Claude reply, mid-stream
Codex reply, end

@brennanb2025
brennanb2025 merged commit 192f829 into main Nov 25, 2026
61 checks passed
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