From fece6eadba044d881acec5444b73e2378b990311 Mon Sep 17 00:00:00 2001 From: Geoffrey Hunter Date: Sat, 5 Sep 2026 15:31:12 +1200 Subject: [PATCH 1/2] Fix the three open bugs from TODO section 4 MCP rxstream buffer grew without bound. handleRxData appended every RX chunk to a per-session string that only shrank when a client read the resource, so a client that subscribed and never read -- or dropped its connection without closing the session -- held the entire serial stream in main-process memory for the life of the app. RxStreamBuffer caps it at the last 1,000,000 characters, drop-oldest, and prefixes the next read with a one-line notice of how much was dropped so the reader sees a gap rather than a silent mid-line join. Trimming is amortised (runs a quarter over the cap) so a saturated stream costs one copy per 250k characters, not one per chunk. The resource description tells clients about the cap. First unit tests for main-process code. stopCpuMonitoring was an empty method with a comment saying the loop stops when the window unloads, which is not what App.cleanup is for. The requestAnimationFrame loop now records its handle and cleanup cancels it, along with any outstanding requestIdleCallback. The handles are excluded from MobX observation since they are written once per frame and nothing observes them. App.spec asserts cleanup cancels the exact frame that was pending. Find was substring-only while Filters and Highlight Rules both take regex. A findUseRegex flag and a `.*` toggle in the Find bar switch the query to a regex compiled with `g` (plus `i` unless case-sensitive). findMatches walks every hit in a row with exec, skipping zero-width matches so `x*` can neither hang nor report empty spans. An invalid pattern yields no matches and a findRegex.errorMsg the bar shows as "Invalid" with the compile error on hover. Toggling the mode resets the current match like the other find controls. --- CHANGELOG.md | 6 ++ TODO.md | 6 +- src/main/RxStreamBuffer.spec.ts | 51 +++++++++++++ src/main/RxStreamBuffer.ts | 74 +++++++++++++++++++ src/main/mcpService.ts | 24 ++++-- src/renderer/src/model/App.spec.ts | 25 +++++++ src/renderer/src/model/App.tsx | 30 ++++++-- .../Terminals/SingleTerminal/Find.spec.ts | 55 ++++++++++++++ .../SingleTerminal/SingleTerminal.ts | 60 +++++++++++++-- .../view/Terminals/SingleTerminal/FindBar.tsx | 39 +++++++--- 10 files changed, 339 insertions(+), 31 deletions(-) create mode 100644 src/main/RxStreamBuffer.spec.ts create mode 100644 src/main/RxStreamBuffer.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index af99face..2f768979 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,8 +7,14 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0. ## Unreleased +### Added + +- **Find supports regular expressions.** A `.*` toggle in the Find bar switches the query to a regex (the case toggle still applies); an invalid pattern shows `Invalid`, with the compile error on hover. Filters and Highlight Rules already took regex. + ### Fixed +- **The MCP `rxstream` buffer is capped.** A session that subscribed but never read the resource held the entire serial stream in main-process memory for the life of the app; `RxStreamBuffer` keeps the last 1,000,000 characters, drops the oldest, and prefixes the next read with a one-line notice of how much was dropped. +- **Closing the window now stops the CPU-usage monitor.** `stopCpuMonitoring` was an empty method; the `requestAnimationFrame` loop now records its handle and cleanup cancels it, along with any pending idle callback. - **Toggling ANSI parsing from a fake port now sticks.** `FakePortsController` wrote `rxSettings.ansiEscapeCodeParsingEnabled` directly, which only ever reached the runtime copy of the setting; the persisted value kept the old state and a preset or restart silently reverted it. Seven such writes now go through the setter — and the settings classes no longer *have* a runtime copy to bypass. - **Applying a preset that names a serial port now connects to that port.** `setSelectedPort` wrote a `serialPortInfo` field nothing read, so the open used whichever port was selected in the UI — or failed outright — while the snackbar reported the preset's port. The serial reconnection poller went through the same call and was equally ineffective. - **Packaged builds no longer download the React DevTools extension on every launch.** `installExtension` ran unconditionally, so a shipped build fetched an extension from Google's CDN at startup and installed it with file access; now guarded by `app.isPackaged`. diff --git a/TODO.md b/TODO.md index 4f55bc22..c475c85c 100644 --- a/TODO.md +++ b/TODO.md @@ -269,7 +269,7 @@ The CHANGELOG shows this is a bug factory: IPC-serialising a JS number array. Store `Uint8Array` chunks in a **plain** (non-observable) array and concat once at write time. -- [ ] **MCP `rxBuffer` grows without bound.** `mcpService.ts:170`. +- [x] **MCP `rxBuffer` grows without bound.** (done 2026-09-05, `RxStreamBuffer`) `mcpService.ts:170`. `session.rxBuffer.text += text` on every RX chunk, cleared only when a client *reads* the resource. A client that subscribes and never reads (or disconnects without closing the session) leaks the entire stream into @@ -278,11 +278,11 @@ The CHANGELOG shows this is a bug factory: - [x] **React DevTools installs in production.** (done 2026-09-04) Guarded with `if (!app.isPackaged)`. -- [ ] **`stopCpuMonitoring()` is a no-op.** `App.tsx:437-440`. The +- [x] **`stopCpuMonitoring()` is a no-op.** (done 2026-09-05) `App.tsx:437-440`. The `requestAnimationFrame` loop it claims to stop keeps running. Capture the rAF handle and cancel it. -- [ ] **Find is substring-only** while Filters and Highlight Rules both support +- [x] **Find is substring-only** (done 2026-09-05) while Filters and Highlight Rules both support regex. `SingleTerminal.ts:180-199` uses `indexOf`; compare `TerminalFilter.ts:45-76`. Inconsistent, and regex-in-find is what you actually want in a 100k-line scrollback. diff --git a/src/main/RxStreamBuffer.spec.ts b/src/main/RxStreamBuffer.spec.ts new file mode 100644 index 00000000..28b46510 --- /dev/null +++ b/src/main/RxStreamBuffer.spec.ts @@ -0,0 +1,51 @@ +import { describe, expect, test } from 'vitest'; + +import { RxStreamBuffer } from './RxStreamBuffer'; + +describe('RxStreamBuffer', () => { + test('drain returns what was appended and empties the buffer', () => { + const buf = new RxStreamBuffer(100); + buf.append('hello '); + buf.append('world'); + expect(buf.drain()).toBe('hello world'); + expect(buf.drain()).toBe(''); + expect(buf.length).toBe(0); + }); + + test('never grows past the cap plus the amortisation slack', () => { + const buf = new RxStreamBuffer(1000); + for (let i = 0; i < 10_000; i += 1) { + buf.append('0123456789'); + } + // Trim runs when a quarter over the cap, so the buffer can sit a little + // above it between trims, but it must never run away. + expect(buf.length).toBeLessThanOrEqual(1250); + }); + + test('drops the oldest data and says so once on the next drain', () => { + const buf = new RxStreamBuffer(10); + buf.append('aaaaaaaaaa'); // 10, at cap + buf.append('bbbbbbbbbb'); // 20, over the 12-char trim threshold -> keep last 10 + const out = buf.drain(); + expect(out.startsWith('[NinjaTerm: 10 characters of received data were dropped')).toBe(true); + expect(out.endsWith('\nbbbbbbbbbb')).toBe(true); + // The notice is not repeated on a clean read. + buf.append('cc'); + expect(buf.drain()).toBe('cc'); + }); + + test('a drain never returns more than the cap, even inside the slack window', () => { + const buf = new RxStreamBuffer(10); + buf.append('aaaaaaaaaaaa'); // 12: over cap, but at the threshold, so not yet trimmed + expect(buf.length).toBe(12); + const out = buf.drain(); + const data = out.slice(out.indexOf('\n') + 1); + expect(data).toBe('aaaaaaaaaa'); + expect(out).toContain('2 characters'); + }); + + test('rejects a nonsensical cap', () => { + expect(() => new RxStreamBuffer(0)).toThrow(); + expect(() => new RxStreamBuffer(1.5)).toThrow(); + }); +}); diff --git a/src/main/RxStreamBuffer.ts b/src/main/RxStreamBuffer.ts new file mode 100644 index 00000000..2fc56851 --- /dev/null +++ b/src/main/RxStreamBuffer.ts @@ -0,0 +1,74 @@ +/** + * Bounded text buffer for the MCP `rxstream` resource. + * + * One of these exists per MCP session. Received text is appended as it + * arrives and drained when the client reads the resource. Before this + * existed the buffer was a bare string that only ever shrank on a read, so a + * client that subscribed and never read (or dropped its connection without + * closing the session) leaked the entire serial stream into main-process + * memory for as long as the app ran. + * + * The cap is drop-oldest: once the buffer would exceed `maxChars`, the front + * is discarded and the number of dropped characters is remembered so the next + * `drain()` can tell the client the stream has a gap rather than handing it + * a silently truncated mid-line join. + */ +export class RxStreamBuffer { + private text = ''; + + /** Characters discarded since the last `drain()`. */ + private droppedChars = 0; + + /** + * @param maxChars Most characters kept. Once exceeded the oldest are dropped. + * Trimming is amortised — it runs when the buffer is a quarter over the + * cap, not on every chunk — so a saturated stream costs one copy per + * `maxChars / 4` characters received rather than one per chunk. + */ + constructor(private readonly maxChars: number) { + if (!Number.isInteger(maxChars) || maxChars <= 0) { + throw new Error(`RxStreamBuffer maxChars must be a positive integer, got ${maxChars}`); + } + } + + get length(): number { + return this.text.length; + } + + append(chunk: string): void { + this.text += chunk; + const trimThreshold = this.maxChars + Math.floor(this.maxChars / 4); + if (this.text.length > trimThreshold) { + this._trimToCap(); + } + } + + /** + * Returns everything buffered and empties the buffer. If anything was + * dropped since the previous drain, a single notice line precedes the data + * so the reader knows there is a gap. + */ + drain(): string { + // A read must never hand back more than the cap either, so trim any + // amortisation slack first. + if (this.text.length > this.maxChars) { + this._trimToCap(); + } + let out = this.text; + this.text = ''; + if (this.droppedChars > 0) { + out = `[NinjaTerm: ${this.droppedChars} characters of received data were dropped because the stream buffer overflowed]\n${out}`; + this.droppedChars = 0; + } + return out; + } + + private _trimToCap(): void { + const excess = this.text.length - this.maxChars; + if (excess <= 0) { + return; + } + this.droppedChars += excess; + this.text = this.text.slice(excess); + } +} diff --git a/src/main/mcpService.ts b/src/main/mcpService.ts index 46e351f3..e232bc64 100644 --- a/src/main/mcpService.ts +++ b/src/main/mcpService.ts @@ -7,15 +7,24 @@ import { randomUUID } from 'crypto'; import { BrowserWindow } from 'electron'; import { log } from './Logging'; +import { RxStreamBuffer } from './RxStreamBuffer'; import { getActivePortPath, writeToPort, listPorts } from './serialService'; const REQUEST_TIMEOUT_MS = 5000; +/** + * Most characters the `rxstream` resource holds per session between reads. + * Bounds main-process memory for a client that subscribes and never reads + * (or disconnects without closing its session). Comfortably above what a + * client polling every few seconds sees at typical serial rates. + */ +const RX_STREAM_BUFFER_MAX_CHARS = 1_000_000; + export class McpService { private httpServer: Server | null = null; private mainWindow: BrowserWindow | null = null; /** Active sessions keyed by session ID. A new entry is created for each initialize request. */ - private sessions = new Map(); + private sessions = new Map(); private registeredPort: number = 0; /** @@ -89,7 +98,7 @@ export class McpService { if (!sessionId) { // New session: create a fresh McpServer + transport pair - const rxBuffer = { text: '' }; + const rxBuffer = new RxStreamBuffer(RX_STREAM_BUFFER_MAX_CHARS); const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID(), onsessioninitialized: (id) => { @@ -167,12 +176,12 @@ export class McpService { */ handleRxData(text: string) { for (const [, session] of this.sessions) { - session.rxBuffer.text += text; + session.rxBuffer.append(text); session.mcpServer.server.sendResourceUpdated({ uri: 'ninjaterm://terminal/rxstream' }).catch(() => {}); } } - private registerTools(server: McpServer, rxBuffer: { text: string }) { + private registerTools(server: McpServer, rxBuffer: RxStreamBuffer) { server.tool( 'get_terminal_output', @@ -256,11 +265,12 @@ export class McpService { description: 'Real-time stream of incoming serial data. Subscribe to receive push notifications ' + '(notifications/resources/updated) when new data arrives, then read this resource to ' + - 'retrieve buffered data since the last read. For historical data use the get_terminal_output tool.', + 'retrieve buffered data since the last read. For historical data use the get_terminal_output tool. ' + + `At most the last ${RX_STREAM_BUFFER_MAX_CHARS} characters are kept between reads; if the buffer ` + + 'overflows the oldest data is dropped and the next read starts with a one-line notice saying how much.', }, async () => { - const data = rxBuffer.text; - rxBuffer.text = ''; + const data = rxBuffer.drain(); return { contents: [{ uri: 'ninjaterm://terminal/rxstream', mimeType: 'text/plain', text: data }], }; diff --git a/src/renderer/src/model/App.spec.ts b/src/renderer/src/model/App.spec.ts index 3e3c0002..e5626653 100644 --- a/src/renderer/src/model/App.spec.ts +++ b/src/renderer/src/model/App.spec.ts @@ -47,3 +47,28 @@ describe('App rate-tracking buffers', () => { expect(length).toBeLessThanOrEqual(4096); }); }); + +describe('App cleanup', () => { + beforeEach(() => { + window.localStorage.clear(); + }); + + test('cleanup cancels the CPU-monitor animation frame', () => { + // jsdom does not implement media playback; cleanup pauses the sound + // player's