Skip to content

perf(streaming): cut bundle, Markdown, and protocol overhead - #91

Merged
qybaihe merged 14 commits into
mainfrom
perf/streaming-and-stability
Nov 30, 2026
Merged

qybaihe merged 14 commits into
mainfrom
perf/streaming-and-stability

Conversation

@qybaihe

@qybaihe qybaihe commented Nov 30, 2026

Copy link
Copy Markdown
Owner

Why

Goal: rigorously measure and reduce BotArk's startup, streaming, and protocol stability bottlenecks, building on the merged Grok reply-delivery fix (#89) and portable packages (#90).

What changed

  • Production bundles: enabled build.minify for main, preload, and renderer (electron-vite defaults to unminified output), and lazy-loaded InfoPanel plus its platform inspectors on first open. Total JS dropped from 5.06 MB to 2.65 MB (-47.6%).
  • Streaming Markdown: MarkdownText caches completed blocks split at blank lines outside fenced code blocks in a bounded, locale- and handler-aware cache, and MessageBubble passes stable callbacks. Parser-only time across 80 incremental renders of a 30-section report fell from 8.73 ms to 3.67 ms (-58.0%, median of 5 interleaved A/B pairs).
  • Collaboration rooms: debounced room persistence (350 ms, lazy serialization), flush on pagehide, and cancel queued writes when clearing data.
  • Protocol and main-process stability:
    • Grok watchTranscripts: 4 MiB frame cap + single-copy frame reassembly instead of per-read Buffer.concat.
    • Grok grokWatchManager: prune removed roster/conversation cursors while preserving incremental watch registrations.
    • DS Bot: single-flight relay connect shared by ensureRelayClient and probes, closing superseded sockets.
    • MCP hub: clear the connect timeout before paginated tools/list.
    • Security vault / updater: async single-flight codesign inspection instead of blocking spawnSync (up to 3.5 s).

Scope

Renderer chat/room hot paths, Electron build config, Grok/DS Bot/MCP transports, and vault/updater signature check. Added scripts/bench/ and scripts/smoke/electron-smoke.mjs.

Tradeoffs

  • MarkdownText keeps a bounded 400-block cache to make both streaming appends and remounts cheap; keys include locale and per-instance handler IDs so cached nodes never leak stale closures across chats.
  • Full SSR wall-clock streaming time overlaps under heavy host load because renderToStaticMarkup re-serializes the whole tree each step; parser-only and interleaved A/B numbers are reported separately.

Blast Radius

No IPC or persisted-schema changes. Default installs, auto-update manifests, and platform wire formats are unchanged.

Verification

  • npm run typecheck, npx vitest run (109 files), npx vitest run --config vitest.e2e.config.mts (76 tests): all pass.
  • npm run build + node scripts/smoke/electron-smoke.mjs: real Electron production boot with 0 exceptions and 0 console errors; InfoPanel chunk loads only on open.
  • Benchmarks: node scripts/bench/run.mjs and node scripts/bench/compare.mjs (frozen harness SHA-256 verified, 5 interleaved A/B pairs, 0 errors; results table in PR comment).

张少谦 added 14 commits November 30, 2026 20:25
Split Markdown at blank lines outside fenced code blocks and cache parsed blocks in a bounded locale- and handler-aware LRU so streaming appends only re-parse the trailing block. Stabilize MessageBubble link callbacks so memoized bubbles skip re-parsing on unrelated renders.
…istrations

Prune removed roster agents on explicit agentIds updates, prune removed conversations on full conversationMap sync, and keep only the latest standalone session pin per agent while preserving watermarks for surviving cursors. Incremental ensureWatch calls from sendMessage, listAgents, and listTranscriptEntries keep unrelated watches intact.
@qybaihe

qybaihe commented Nov 30, 2026

Copy link
Copy Markdown
Owner Author

Benchmark evidence (median of 5 interleaved A/B pairs, NODE_ENV=production, 0 errors)

Host was shared and busy (load average 25.26–31.80 on 15 cores), so both sides alternated A/B/A/B to see the same noise. Reproduce with node scripts/bench/compare.mjs <baseline-worktree>.

Metric Before (85a38f1) median ms (range) After median ms (range) Delta
connect_2mib_frame_ms (2 MiB frame in 1 KiB chunks) 110.84 (99.30..125.18) 26.91 (22.47..31.11) -75.7%
connect_stream_300_frames_ms 2.32 (1.85..2.62) 1.81 (1.46..2.67) -21.9%
markdown_rerender_40x_ms (40 full SSR renders) 26.20 (23.95..26.54) 20.78 (18.29..27.29) -20.7%
markdown_stream_80_steps_ms (full SSR stream) 41.40 (40.81..47.56) 38.52 (32.70..50.17) -6.9% (ranges overlap)
Markdown parser-only, 80 stream steps (excludes SSR string serialization) 8.73 (8.51..9.20) 3.67 (3.58..3.88) -58.0%

Limiter notes (benchmark-checklist):

  • connect_2mib_frame_ms was bound by O(N²) Buffer.concat per 1 KiB read; reassembling once per frame removed it (non-overlapping ranges).
  • Full SSR markdown_stream_80_steps_ms is floored by renderToStaticMarkup re-serializing the entire report to an HTML string on every step. In the mounted app, unchanged <Fragment> blocks keep referential equality so React skips both parsing and subtree reconciliation; useMemo + stable MessageBubble callbacks also skip work on unrelated parent renders.

Production bundle bytes (npm run build)

Artifact Before After Delta
Renderer entry index-*.js 2,048.81 kB 729.07 kB -64.4%
Main out/main/index.js 1,556.89 kB 857.03 kB -45.0%
Preload out/preload/index.js 24.96 kB 14.99 kB -39.9%
Total JS across all chunks 5,055.97 kB 2,653.58 kB -47.5%

@qybaihe

qybaihe commented Nov 30, 2026

Copy link
Copy Markdown
Owner Author

PASS+NOTES

Independent pre-merge verification of 9c52fcd579e5816c449f1a10bdf2f04c20a7f915 (9c52fcd, perf/streaming-and-stability) against origin/main (d6445c5bc332dca975f2ac055b17cd3f1603e343). I did not author this PR. All checks ran in an isolated worktree without touching a real BotArk profile.

Commands and results

  1. npm run typecheck: exit 0 (tsc --noEmit for both tsconfig.node.json and tsconfig.web.json).
  2. npx vitest run: exit 0. 109 test files passed, 880 tests passed, 0 failed.
  3. npx vitest run --config vitest.e2e.config.mts: exit 0. 6 E2E files passed, 76 tests passed, 0 failed.
  4. npm run build: exit 0. Production minified bundles built for main (857.02 kB), preload (14.99 kB), and renderer (index-CTbfgSnf.js 729.06 kB, with InfoPanel-BH5cqy07.js split out at 278.61 kB).
  5. node scripts/smoke/electron-smoke.mjs: exit 0 in a real Electron 45.4.1 window using a throwaway --user-data-dir that the script deletes on exit.
    {
      "entryLoaded": true,
      "infoLoadedBefore": false,
      "infoLoadedAfter": true,
      "mainRendered": true,
      "exceptions": [],
      "consoleErrors": [],
      "scriptsLoaded": 13
    }
    The seeded chat (**Hello** smoke) rendered in <main>. InfoPanel-*.js did not load before opening the panel and loaded on demand when toggled, rendering the bot inspector in <aside>.
  6. npx vitest run src/renderer/src/components/chat/MarkdownText.test.ts src/renderer/src/rooms/roomPersistence.test.ts: exit 0, 8 tests passed. I also ran read-only Vite SSR differential checks comparing the shared block cache against fresh uncached module instances for 388 prefix and flag combinations (unclosed code fences with blank lines, blank lines inside closed fences, CRLF line endings, GFM tables, [[hatch_widget:...]] spanning blocks, and onFileLinkClick / suppressWorkspaceImages combinations). All matched. Locale switching en -> zh -> en after cache warmup updated inline file-link titles correctly.
  7. npx vitest run src/main/portableDataDir.test.ts: exit 0, 20 tests passed. I also extracted the minified resolver (GA) from the built out/main/index.js and executed it in a Node VM sandbox against temp directories. All 5 runtime probes passed: PORTABLE_EXECUTABLE_DIR, macOS sibling .botark-portable marker, --user-data-dir precedence, read-only fallback with warning, and legacy bothub migration. The minified startup sequence still calls app.setPath('userData', ...) before requestSingleInstanceLock().
  8. git diff origin/main...HEAD --stat and full added-line scan: 26 files changed (+1731 / -216), all scoped to streaming, bundle splitting, protocol framing, room persistence, updater/codesign, benchmarks, smoke test, and changelog. Zero private keys, API keys, GitHub or Slack tokens, AWS keys, Google API keys, or JWTs found in added lines. git status is clean.

What a user would notice

  • Production startup renders the seeded chat with zero console errors or uncaught exceptions.
  • The right-side inspector chunk (~279 kB) no longer loads at startup; it loads the first time the panel opens.
  • Streaming long Markdown replies re-parses only the trailing block. Unclosed code fences keep blank lines intact, and completed blocks keep working across flag and locale changes.
  • Collaboration room edits coalesce localStorage writes into one 350 ms debounced write, flush on pagehide, and cancel cleanly when saved data is cleared.

Non-blocking notes

  • src/renderer/src/components/chat/MarkdownText.test.ts:54 is named renders every streaming prefix identically to a full parse of that prefix, but both streamed and direct pass prefix to MarkdownText, so both sides use the same module cache. The overlapping-prefix/sibling-document test below it and the fresh-module differential checks above confirm the behavior is correct, but the test name claims more than lines 54-60 assert.
  • npm run build still prints the informational >500 kB chunk warning from Vite for the 729.06 kB renderer entry chunk (down from 2,048.81 kB).

@qybaihe
qybaihe merged commit 4a518a6 into main Nov 30, 2026
3 checks passed
GOXF added a commit to GOXF/botark that referenced this pull request Nov 30, 2026
* 修复 Grok Bot 实时回复及历史补取

* 让 Grok 群聊实时接收回复和文件

* feat(portable): add portable data directory and Windows portable package

Resolve userData at startup in order of --user-data-dir, PORTABLE_EXECUTABLE_DIR, a sibling BotArkData folder or .botark-portable marker, legacy bothub migration, then the default userData path. Verify portable writability with a probe file and fall back to the default userData with a warning when read-only.

Add the Windows portable target (BotArk-Portable-<version>-<arch>.exe) alongside NSIS, and document portable mode.

Closes qybaihe#87

* test(portable): use cross-platform read-only fallback fixtures on Windows

* perf(streaming): cut bundle, Markdown, and protocol overhead (qybaihe#91)

* test(bench): add production-mode streaming and protocol benchmarks

* test(chat): pin MarkdownText rendering and handler behavior

* perf(chat): cache completed Markdown blocks during streaming

Split Markdown at blank lines outside fenced code blocks and cache parsed blocks in a bounded locale- and handler-aware LRU so streaming appends only re-parse the trailing block. Stabilize MessageBubble link callbacks so memoized bubbles skip re-parsing on unrelated renders.

* perf(build): minify production main, preload, and renderer bundles

* perf(renderer): load InfoPanel on demand and add Electron smoke check

* fix(grok): bound watch frame size and avoid quadratic buffering

* fix(dsbot): deduplicate concurrent relay connects and close stale flights

* fix(mcp): clear connect timeout before paginated tools/list discovery

* perf(rooms): debounce room persistence and cancel pending writes on clear

* perf(vault): inspect macOS code signature asynchronously

* fix(grok): prune stale watch cursors without dropping incremental registrations

Prune removed roster agents on explicit agentIds updates, prune removed conversations on full conversationMap sync, and keep only the latest standalone session pin per agent while preserving watermarks for surviving cursors. Incremental ensureWatch calls from sendMessage, listAgents, and listTranscriptEntries keep unrelated watches intact.

* test: fix strict TypeScript signatures in vault and room persistence tests

* style(dsbot): drop redundant relay reuse comment

* docs(changelog): document streaming, bundle, and protocol stability improvements

---------

Co-authored-by: 张少谦 <zhangshaoqian@moonshot.ai>

* chore(release): bump BotArk to v0.18.0

---------

Co-authored-by: rainhan99 <16128160+rainhan99@users.noreply.github.com>
Co-authored-by: Timo Zhang <qybaihe@gmail.com>
Co-authored-by: 张少谦 <zhangshaoqian@moonshot.ai>
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.

1 participant