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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 and the flow-control poll.** `stopCpuMonitoring` was an empty method and `ConnController.cleanup` never cleared the 1s `getFlowControlSignals` interval; both are now cancelled, and the poll logs rather than throws on a bad IPC response.
- **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`.
Expand Down
6 changes: 3 additions & 3 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.
Expand Down
51 changes: 51 additions & 0 deletions src/main/RxStreamBuffer.spec.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
74 changes: 74 additions & 0 deletions src/main/RxStreamBuffer.ts
Original file line number Diff line number Diff line change
@@ -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);
}
}
24 changes: 17 additions & 7 deletions src/main/mcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,30 @@
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<string, { mcpServer: McpServer; transport: StreamableHTTPServerTransport; rxBuffer: { text: string } }>();
private sessions = new Map<string, { mcpServer: McpServer; transport: StreamableHTTPServerTransport; rxBuffer: RxStreamBuffer }>();
private registeredPort: number = 0;

/**
* Pending renderer request callbacks, keyed by request ID.
*/
private pendingRequests = new Map<string, { resolve: (data: any) => void; reject: (err: Error) => void }>();

Check warning on line 33 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (windows-2022)

Unexpected any. Specify a different type

Check warning on line 33 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (macos-15)

Unexpected any. Specify a different type

Check warning on line 33 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (ubuntu-latest)

Unexpected any. Specify a different type

constructor(mainWindow: BrowserWindow) {
this.mainWindow = mainWindow;
Expand All @@ -31,7 +40,7 @@
* Send a request to the renderer process and wait for a response.
* The renderer is the single source of truth for terminal state.
*/
requestFromRenderer(method: string, params: any = {}): Promise<any> {

Check warning on line 43 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (windows-2022)

Unexpected any. Specify a different type

Check warning on line 43 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (windows-2022)

Unexpected any. Specify a different type

Check warning on line 43 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (macos-15)

Unexpected any. Specify a different type

Check warning on line 43 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (macos-15)

Unexpected any. Specify a different type

Check warning on line 43 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (ubuntu-latest)

Unexpected any. Specify a different type

Check warning on line 43 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (ubuntu-latest)

Unexpected any. Specify a different type
return new Promise((resolve, reject) => {
const id = randomUUID();
const timeout = setTimeout(() => {
Expand All @@ -51,7 +60,7 @@
/**
* Called by the ipcMain 'mcp:response' handler when the renderer replies.
*/
handleRendererResponse(id: string, data: any, error?: string) {

Check warning on line 63 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (windows-2022)

Unexpected any. Specify a different type

Check warning on line 63 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (macos-15)

Unexpected any. Specify a different type

Check warning on line 63 in src/main/mcpService.ts

View workflow job for this annotation

GitHub Actions / test-electron (ubuntu-latest)

Unexpected any. Specify a different type
const pending = this.pendingRequests.get(id);
if (!pending) return;
this.pendingRequests.delete(id);
Expand Down Expand Up @@ -89,7 +98,7 @@

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) => {
Expand Down Expand Up @@ -167,12 +176,12 @@
*/
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',
Expand Down Expand Up @@ -256,11 +265,12 @@
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 }],
};
Expand Down
22 changes: 22 additions & 0 deletions src/renderer/src/model/App.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,25 @@ describe('App rate-tracking buffers', () => {
expect(length).toBeLessThanOrEqual(4096);
});
});

describe('App cleanup', () => {
beforeEach(() => {
window.localStorage.clear();
});

test('cleanup cancels the CPU-monitor animation frame', () => {
const cancelSpy = vi.spyOn(window, 'cancelAnimationFrame');
const app = new App();
// The constructor scheduled a frame...
const handle = (app as any).cpuMonitorRafHandle;
expect(handle).not.toBeNull();

app.cleanup();

// ...and cleanup cancelled that exact frame. `stopCpuMonitoring` used to
// be an empty method, so the loop ran until the window unloaded.
expect(cancelSpy).toHaveBeenCalledWith(handle);
expect((app as any).cpuMonitorRafHandle).toBeNull();
cancelSpy.mockRestore();
});
});
30 changes: 25 additions & 5 deletions src/renderer/src/model/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,15 @@ export class App {
// CPU monitoring variables - measuring overall renderer process load
private readonly CPU_MEASUREMENT_WINDOW_MS = 1000; // 1 second window

/**
* The CPU monitor's pending animation frame, so `stopCpuMonitoring` can
* cancel it. Null when the monitor is not running.
*/
private cpuMonitorRafHandle: number | null = null;

/** The CPU monitor's pending idle callback, if one is outstanding. */
private cpuMonitorIdleHandle: number | null = null;

// If true app is being tested by code.
// Used for force terminal height to value when browser is not
// available to determine height
Expand Down Expand Up @@ -273,6 +282,9 @@ export class App {
// no subscriber.
rxDataPoints: false,
txDataPoints: false,
// Written once per animation frame; nothing observes them.
cpuMonitorRafHandle: false,
cpuMonitorIdleHandle: false,
} as any); // Make sure this near the end
}

Expand Down Expand Up @@ -456,7 +468,8 @@ export class App {

// Use requestIdleCallback to get more accurate idle time measurements
if (typeof requestIdleCallback !== 'undefined') {
requestIdleCallback((deadline) => {
this.cpuMonitorIdleHandle = requestIdleCallback((deadline) => {
this.cpuMonitorIdleHandle = null;
// If we have very little idle time, we're CPU bound
const availableTime = deadline.timeRemaining();
if (availableTime < 1) { // Less than 1ms idle time indicates high CPU usage
Expand All @@ -465,8 +478,9 @@ export class App {
});
}

// Continue monitoring
requestAnimationFrame(measureCpuUsage);
// Continue monitoring. Keep the handle so `stopCpuMonitoring` can end
// the loop; before this it ran until the window unloaded.
this.cpuMonitorRafHandle = requestAnimationFrame(measureCpuUsage);
};

measureCpuUsage();
Expand All @@ -476,8 +490,14 @@ export class App {
* Stops CPU monitoring.
*/
private stopCpuMonitoring() {
// CPU monitoring is handled by requestAnimationFrame and requestIdleCallback
// These will stop when the window is unloaded
if (this.cpuMonitorRafHandle !== null) {
cancelAnimationFrame(this.cpuMonitorRafHandle);
this.cpuMonitorRafHandle = null;
}
if (this.cpuMonitorIdleHandle !== null && typeof cancelIdleCallback !== 'undefined') {
cancelIdleCallback(this.cpuMonitorIdleHandle);
this.cpuMonitorIdleHandle = null;
}
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import type { Mock } from 'vitest';

import { App } from '../App';
Expand Down Expand Up @@ -107,6 +107,12 @@ describe('ConnController connection lifecycle', () => {
conn = app.connController;
});

afterEach(() => {
// Tests that leave a port open have started the flow-control poll; without
// this it outlives the test and fires against a torn-down environment.
app.cleanup();
});

/** Points the app at a serial port and opens it. */
async function openSerial() {
app.settings.portConfiguration.setConnectionType(ConnectionType.SERIAL_PORT);
Expand Down
28 changes: 19 additions & 9 deletions src/renderer/src/model/ConnController/ConnController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,10 @@ export class ConnController {

cleanup() {
this.stopPollingForReconnection();
// Was missing, so the 1s flow-control poll outlived the controller: in the
// app it ran until the window unloaded, and in tests a leaked interval
// fired after the file was torn down and surfaced as an unhandled rejection.
this.stopFlowControlPolling();
this.disposeConnListeners();
}

Expand Down Expand Up @@ -349,16 +353,22 @@ export class ConnController {
if (portPath === null) {
return;
}
const response = await window.electronAPI.serial.getFlowControlSignals(portPath);
if (!response.success) {
console.error('Error getting flow control signals:', response.error);
return;
// An async interval callback has nobody awaiting it, so anything thrown
// here is an unhandled rejection. Log and try again next tick instead.
try {
const response = await window.electronAPI.serial.getFlowControlSignals(portPath);
if (!response?.success) {
console.error('Error getting flow control signals:', response?.error);
return;
}
runInAction(() => {
this.currentFlowControlState.dsr = response.signals?.dsr || false;
this.currentFlowControlState.cts = response.signals?.cts || false;
this.currentFlowControlState.dcd = response.signals?.dcd || false;
});
} catch (error) {
console.error('Error getting flow control signals:', error);
}
runInAction(() => {
this.currentFlowControlState.dsr = response.signals!.dsr || false;
this.currentFlowControlState.cts = response.signals!.cts || false;
this.currentFlowControlState.dcd = response.signals!.dcd || false;
});
}, 1000);
}

Expand Down
Loading
Loading