Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(settings): live debug log panel — a redacted in-memory ring behind a toggle

enesb3f136a0dd60
diff --git a/src/core/log-buffer.test.ts b/src/core/log-buffer.test.ts
new file mode 100644
index 000000000..b347ad332
--- /dev/null
+++ b/src/core/log-buffer.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect } from 'vitest'
+import { LogBuffer, LOG_BUFFER_CAP, LOG_LINE_MAX } from './log-buffer'
+
+const rec = (msg: string) => ({ level: 'info' as const, tag: 't', msg })
+
+describe('LogBuffer', () => {
+ it('assigns monotonic seqs and snapshots in order', () => {
+ const b = new LogBuffer()
+ b.push(rec('a'))
+ b.push(rec('b'))
+ const snap = b.snapshot()
+ expect(snap.map((r) => r.msg)).toEqual(['a', 'b'])
+ expect(snap[1].seq).toBeGreaterThan(snap[0].seq)
+ })
+
+ it('drops oldest past the cap — the ring never grows unbounded', () => {
+ const b = new LogBuffer()
+ for (let i = 0; i < LOG_BUFFER_CAP + 10; i++) b.push(rec(`m${i}`))
+ const snap = b.snapshot()
+ expect(snap.length).toBe(LOG_BUFFER_CAP)
+ expect(snap[0].msg).toBe('m10')
+ // seq keeps counting across drops — since() stays correct after eviction.
+ expect(b.lastSeq()).toBe(LOG_BUFFER_CAP + 10)
+ })
+
+ it('since(seq) returns only newer records', () => {
+ const b = new LogBuffer()
+ b.push(rec('a'))
+ const mark = b.lastSeq()
+ b.push(rec('b'))
+ b.push(rec('c'))
+ expect(b.since(mark).map((r) => r.msg)).toEqual(['b', 'c'])
+ expect(b.since(b.lastSeq())).toEqual([])
+ })
+
+ it('redacts at the push boundary — nothing unredacted ever exists in the ring', () => {
+ const b = new LogBuffer()
+ b.push(rec('NODETERM_HOOK_TOKEN=abc123'))
+ expect(b.snapshot()[0].msg).toBe('NODETERM_HOOK_TOKEN=[redacted]')
+ })
+
+ it('caps a runaway line at LOG_LINE_MAX', () => {
+ const b = new LogBuffer()
+ b.push(rec('x'.repeat(LOG_LINE_MAX * 2)))
+ expect(b.snapshot()[0].msg.length).toBeLessThanOrEqual(LOG_LINE_MAX + 1)
+ })
+
+ it('notifies onAppend, and a throwing listener does not break logging', () => {
+ const b = new LogBuffer()
+ let n = 0
+ b.onAppend(() => {
+ throw new Error('boom')
+ })
+ const un = b.onAppend(() => n++)
+ b.push(rec('a'))
+ expect(n).toBe(1)
+ un()
+ b.push(rec('b'))
+ expect(n).toBe(1)
+ })
+})
diff --git a/src/core/log-buffer.ts b/src/core/log-buffer.ts
new file mode 100644
index 000000000..d3d02a6a1
--- /dev/null
+++ b/src/core/log-buffer.ts
@@ -0,0 +1,64 @@
+import { redactSecrets } from './log-redact'
+import type { LogRecord } from '../shared/types'
+
+export type { LogRecord }
+
+/** Ring capacity. Big enough to hold a debugging session, small enough to never matter in RAM
+ * (~2000 × a few hundred bytes). */
+export const LOG_BUFFER_CAP = 2000
+
+/** A single line is capped so a runaway payload (a whole file echoed into console) cannot make
+ * the ring one giant entry — the tail is what debugging needs anyway. */
+export const LOG_LINE_MAX = 4000
+
+/**
+ * The in-memory debug log ring (issue #78). Redaction happens HERE, in push(): nothing
+ * unredacted ever exists in the ring, so no later consumer — the panel, a copy-export, a
+ * screenshot — can leak a credential the boundary already removed.
+ */
+export class LogBuffer {
+ private entries: LogRecord[] = []
+ private seq = 0
+ private listeners = new Set<() => void>()
+
+ push(r: { level: LogRecord['level']; tag: string; msg: string }): void {
+ const msg = redactSecrets(r.msg.length > LOG_LINE_MAX ? `${r.msg.slice(0, LOG_LINE_MAX)}…` : r.msg)
+ this.entries.push({ seq: ++this.seq, ts: Date.now(), level: r.level, tag: r.tag, msg })
+ if (this.entries.length > LOG_BUFFER_CAP) {
+ this.entries.splice(0, this.entries.length - LOG_BUFFER_CAP)
+ }
+ for (const cb of this.listeners) {
+ try {
+ cb()
+ } catch {
+ /* a broken listener must not break logging */
+ }
+ }
+ }
+
+ /** Everything currently in the ring (panel open → initial fill). */
+ snapshot(): LogRecord[] {
+ return [...this.entries]
+ }
+
+ /** Records newer than `seq` (batched push to an already-filled subscriber). */
+ since(seq: number): LogRecord[] {
+ // The ring is sorted by seq; find the first newer record.
+ const idx = this.entries.findIndex((e) => e.seq > seq)
+ return idx === -1 ? [] : this.entries.slice(idx)
+ }
+
+ lastSeq(): number {
+ return this.seq
+ }
+
+ clear(): void {
+ this.entries = []
+ }
+
+ /** Notify on every push — the handlers layer debounces, so this stays a plain sync fan-out. */
+ onAppend(cb: () => void): () => void {
+ this.listeners.add(cb)
+ return () => this.listeners.delete(cb)
+ }
+}
diff --git a/src/core/log-handlers.test.ts b/src/core/log-handlers.test.ts
new file mode 100644
index 000000000..d99549781
--- /dev/null
+++ b/src/core/log-handlers.test.ts
@@ -0,0 +1,89 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { fakePlatform } from './platform-fake'
+import { LogBuffer } from './log-buffer'
+import { registerLogHandlers, LOG_PUSH_DEBOUNCE_MS } from './log-handlers'
+import { installLogSink, splitTag } from './log-sink'
+import { IPC } from '../shared/ipc'
+
+const rec = (msg: string) => ({ level: 'info' as const, tag: 't', msg })
+const batches = (f: ReturnType<typeof fakePlatform>) =>
+ f.sent.filter((s) => s.channel === IPC.logBatch).map((s) => s.args[0] as { msg: string }[])
+
+describe('registerLogHandlers', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ it('pushes nothing while no panel is subscribed — the ring fills silently', () => {
+ const f = fakePlatform()
+ const b = new LogBuffer()
+ registerLogHandlers(f, b, () => true)
+ b.push(rec('a'))
+ vi.advanceTimersByTime(LOG_PUSH_DEBOUNCE_MS * 2)
+ expect(batches(f)).toEqual([])
+ expect((f.handlers[IPC.logSnapshot]() as { msg: string }[]).map((r) => r.msg)).toEqual(['a'])
+ })
+
+ it('batches pushes while subscribed, starting from the subscribe point', () => {
+ const f = fakePlatform()
+ const b = new LogBuffer()
+ registerLogHandlers(f, b, () => true)
+ b.push(rec('before'))
+ f.listeners[IPC.logSubscribe]()
+ b.push(rec('x'))
+ b.push(rec('y'))
+ vi.advanceTimersByTime(LOG_PUSH_DEBOUNCE_MS + 10)
+ expect(batches(f)).toEqual([[expect.objectContaining({ msg: 'x' }), expect.objectContaining({ msg: 'y' })]])
+ })
+
+ it('stops pushing after the last unsubscribe and when the setting is off', () => {
+ const f = fakePlatform()
+ const b = new LogBuffer()
+ let on = true
+ registerLogHandlers(f, b, () => on)
+ f.listeners[IPC.logSubscribe]()
+ f.listeners[IPC.logUnsubscribe]()
+ b.push(rec('a'))
+ vi.advanceTimersByTime(LOG_PUSH_DEBOUNCE_MS * 2)
+ expect(batches(f)).toEqual([])
+
+ f.listeners[IPC.logSubscribe]()
+ on = false
+ b.push(rec('b'))
+ vi.advanceTimersByTime(LOG_PUSH_DEBOUNCE_MS * 2)
+ expect(batches(f)).toEqual([])
+ })
+
+ it('logClear empties the ring', () => {
+ const f = fakePlatform()
+ const b = new LogBuffer()
+ registerLogHandlers(f, b, () => true)
+ b.push(rec('a'))
+ f.listeners[IPC.logClear]()
+ expect(f.handlers[IPC.logSnapshot]()).toEqual([])
+ })
+})
+
+describe('installLogSink', () => {
+ it('mirrors console calls into the ring with the [tag] convention, and uninstalls cleanly', () => {
+ const b = new LogBuffer()
+ const orig = console.warn
+ const un = installLogSink(b)
+ console.warn('[updater] check failed', new Error('offline'))
+ un()
+ expect(console.warn).toBe(orig)
+ const snap = b.snapshot()
+ expect(snap.length).toBe(1)
+ expect(snap[0].level).toBe('warn')
+ expect(snap[0].tag).toBe('updater')
+ expect(snap[0].msg).toContain('check failed')
+ expect(snap[0].msg).toContain('offline')
+ // Nothing logged after uninstall.
+ console.warn = orig
+ })
+
+ it('splitTag handles the untagged and non-string cases', () => {
+ expect(splitTag('[main] hello')).toEqual({ tag: 'main', rest: 'hello' })
+ expect(splitTag('plain line')).toEqual({ tag: '', rest: 'plain line' })
+ expect(splitTag(42)).toEqual({ tag: '', rest: '42' })
+ })
+})
diff --git a/src/core/log-handlers.ts b/src/core/log-handlers.ts
new file mode 100644
index 000000000..ed5a07b49
--- /dev/null
+++ b/src/core/log-handlers.ts
@@ -0,0 +1,57 @@
+import { IPC } from '../shared/ipc'
+import type { CorePlatform } from './platform'
+import type { LogBuffer } from './log-buffer'
+
+/** Coalesce bursts into one push — a build spraying warnings must not become an IPC-per-line. */
+export const LOG_PUSH_DEBOUNCE_MS = 200
+
+/**
+ * IPC for the debug log panel (issue #78): snapshot/clear request-response plus a ref-counted
+ * subscribe → batched `logBatch` broadcasts (the board-log-handlers pattern). Batches flow only
+ * while at least one panel is subscribed AND the setting is on — with the panel closed the ring
+ * still fills, but nothing crosses the process boundary.
+ *
+ * Duplicate delivery is possible around the subscribe edge (the panel snapshots, then the first
+ * flush may include records the snapshot already carried) — the client dedupes by `seq`, which
+ * is monotonic, instead of this layer trying to track per-subscriber positions.
+ */
+export function registerLogHandlers(
+ platform: CorePlatform,
+ buffer: LogBuffer,
+ enabled: () => boolean
+): void {
+ let subscribers = 0
+ let lastSent = 0
+ let timer: ReturnType<typeof setTimeout> | null = null
+
+ const flush = (): void => {
+ timer = null
+ if (subscribers <= 0 || !enabled()) return
+ const batch = buffer.since(lastSent)
+ if (batch.length === 0) return
+ lastSent = batch[batch.length - 1].seq
+ platform.broadcast(IPC.logBatch, batch)
+ }
+ const schedule = (): void => {
+ if (timer) return
+ timer = setTimeout(flush, LOG_PUSH_DEBOUNCE_MS)
+ timer.unref?.()
+ }
+
+ buffer.onAppend(() => {
+ if (subscribers > 0 && enabled()) schedule()
+ })
+
+ platform.on(IPC.logSubscribe, () => {
+ subscribers++
+ // New panel: it snapshots for the fill; start the stream from "now" so the first flush
+ // doesn't replay the whole ring (the seq-dedupe on the client makes the overlap harmless).
+ if (subscribers === 1) lastSent = buffer.lastSeq()
+ schedule()
+ })
+ platform.on(IPC.logUnsubscribe, () => {
+ subscribers = Math.max(0, subscribers - 1)
+ })
+ platform.handle(IPC.logSnapshot, () => buffer.snapshot())
+ platform.on(IPC.logClear, () => buffer.clear())
+}
diff --git a/src/core/log-redact.test.ts b/src/core/log-redact.test.ts
new file mode 100644
index 000000000..79cce3970
--- /dev/null
+++ b/src/core/log-redact.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect } from 'vitest'
+import { redactSecrets, SECRET_VALUE_NAMES } from './log-redact'
+
+describe('redactSecrets', () => {
+ it('redacts every named credential in NAME=value form', () => {
+ for (const name of SECRET_VALUE_NAMES) {
+ const out = redactSecrets(`spawning with ${name}=super-secret-123 in env`)
+ expect(out, name).not.toContain('super-secret-123')
+ expect(out, name).toContain(`${name}=[redacted]`)
+ }
+ })
+
+ it('redacts NAME: value and quoted JSON forms', () => {
+ expect(redactSecrets('NODETERM_HOOK_TOKEN: abc123')).toBe('NODETERM_HOOK_TOKEN: [redacted]')
+ const json = redactSecrets('{"access_token":"eyJhbGciOi.payload.sig","scope":"x"}')
+ expect(json).not.toContain('eyJhbGciOi')
+ expect(json).toContain('"scope":"x"')
+ })
+
+ it('redacts Authorization and X-Nodeterm-*-Token headers whatever the scheme', () => {
+ expect(redactSecrets('Authorization: Bearer abc.def.ghi')).toBe('Authorization: [redacted]')
+ expect(redactSecrets('authorization: Basic dXNlcjpwYXNz')).toBe('authorization: [redacted]')
+ expect(redactSecrets('X-Nodeterm-Hook-Token: tok123')).toBe('X-Nodeterm-Hook-Token: [redacted]')
+ expect(redactSecrets('X-Nodeterm-Askpass-Token: tok123')).toBe('X-Nodeterm-Askpass-Token: [redacted]')
+ expect(redactSecrets('cookie: session=abc; theme=dark')).toBe('cookie: [redacted]')
+ })
+
+ it('redacts bare well-known token shapes (argv echoes)', () => {
+ expect(redactSecrets('ran curl -H x sk-ant-api03-abcdefghijklmnop')).not.toContain('sk-ant')
+ expect(redactSecrets('cloning with ghp_abcdefghijklmnop1234')).not.toContain('ghp_')
+ expect(redactSecrets('github_pat_11ABCDEFG_abcdefghijklmnop')).not.toContain('github_pat_')
+ })
+
+ it('leaves the debugging substance alone — SHAs, paths, node ids, ports', () => {
+ const line =
+ '[remote-hooks] installed for nt-4f2a at /home/u/.nodeterm on 127.0.0.1:53187 (commit 9c8f3bcf1234567890abcdef1234567890abcdef)'
+ expect(redactSecrets(line)).toBe(line)
+ })
+
+ it('is idempotent', () => {
+ const once = redactSecrets('GH_TOKEN=abc Authorization: Bearer x')
+ expect(redactSecrets(once)).toBe(once)
+ })
+})
diff --git a/src/core/log-redact.ts b/src/core/log-redact.ts
new file mode 100644
index 000000000..30f54fb6f
--- /dev/null
+++ b/src/core/log-redact.ts
@@ -0,0 +1,53 @@
+/**
+ * Secret redaction for the debug log ring (issue #78). Applied INSIDE LogBuffer.push(), not at
+ * the IPC boundary: the invariant being upheld is pairing-core's "NEVER sent to the renderer" —
+ * once a value exists unredacted in the ring, any later consumer (the panel, an export, a crash
+ * report someone pastes) can leak it, so nothing unredacted may enter the ring at all.
+ *
+ * The list is deny-by-name plus a few well-known token SHAPES. Deliberately NOT a generic
+ * high-entropy matcher: git SHAs, node ids and file paths are exactly what makes a debug log
+ * useful, and an entropy heuristic eats them.
+ */
+
+/**
+ * Env-var / config names whose VALUE is a credential when logged as `NAME=x`, `NAME: x` or
+ * `"NAME":"x"`. Seeded from AUTH_ENV_STRIP (claude-accounts-core) plus every token-bearing
+ * name this codebase actually sets — keep in sync when a new one appears.
+ */
+export const SECRET_VALUE_NAMES: readonly string[] = [
+ 'ANTHROPIC_API_KEY',
+ 'ANTHROPIC_AUTH_TOKEN',
+ 'CLAUDE_CODE_OAUTH_TOKEN',
+ 'NODETERM_HOOK_TOKEN',
+ 'NODETERM_ASKPASS_TOKEN',
+ 'NODETERM_SERVER_PASSWORD',
+ 'GH_TOKEN',
+ 'GITHUB_TOKEN',
+ 'GROK_CLI_AUTH_HEADER',
+ 'access_token',
+ 'refresh_token'
+]
+
+const REPLACEMENT = '[redacted]'
+
+// `NAME=value` / `NAME: value` / `"NAME":"value"` — the value runs to whitespace or a closing
+// quote, so a token never survives partially. Case-insensitive: headers and JSON keys vary.
+const namePattern = new RegExp(
+ `(["']?(?:${SECRET_VALUE_NAMES.join('|')})["']?\\s*[=:]\\s*)("[^"]*"|'[^']*'|\\S+)`,
+ 'gi'
+)
+
+// Authorization / token-carrying headers, whatever the scheme (Bearer, Basic, token …).
+const headerPattern = /((?:authorization|proxy-authorization|x-nodeterm-[a-z-]*token|cookie|set-cookie)\s*[=:]\s*)([^\r\n]+)/gi
+
+// Well-known token shapes that appear WITHOUT a name label (argv echoes, pasted URLs):
+// Anthropic sk-ant-…, generic sk-…, GitHub ghp_/gho_/ghu_/ghs_/ghr_ and fine-grained PATs.
+const shapePattern = /\b(sk-[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[A-Za-z0-9_]{16,})\b/g
+
+/** Redact known credentials from one log line. Pure; idempotent. */
+export function redactSecrets(text: string): string {
+ return text
+ .replace(namePattern, (_m, head: string) => `${head}${REPLACEMENT}`)
+ .replace(headerPattern, (_m, head: string) => `${head}${REPLACEMENT}`)
+ .replace(shapePattern, REPLACEMENT)
+}
diff --git a/src/core/log-sink.ts b/src/core/log-sink.ts
new file mode 100644
index 000000000..acf18d7fe
--- /dev/null
+++ b/src/core/log-sink.ts
@@ -0,0 +1,82 @@
+import { inspect } from 'util'
+import type { LogBuffer, LogRecord } from './log-buffer'
+
+/**
+ * Console capture for the debug log ring (issue #78). Packaged apps swallow the process console
+ * entirely — this is the only place the app's own `console.warn('[tag] …')` calls become
+ * observable in the field. The wrap forwards to the original console untouched (dev terminals
+ * keep working), then mirrors a formatted line into the ring.
+ */
+
+const LEVEL: Record<string, LogRecord['level']> = {
+ log: 'info',
+ info: 'info',
+ debug: 'debug',
+ warn: 'warn',
+ error: 'error'
+}
+
+/** The `[subsystem]` prefix convention: split it off the first arg when present. */
+export function splitTag(first: unknown): { tag: string; rest: string } {
+ if (typeof first === 'string') {
+ const m = /^\[([^\]\n]{1,32})\]\s*/.exec(first)
+ if (m) return { tag: m[1], rest: first.slice(m[0].length) }
+ return { tag: '', rest: first }
+ }
+ return { tag: '', rest: formatArg(first) }
+}
+
+function formatArg(a: unknown): string {
+ if (typeof a === 'string') return a
+ if (a instanceof Error) return a.stack ?? String(a)
+ try {
+ // util.inspect over JSON.stringify: it survives cycles and prints Errors usefully.
+ return inspect(a, { depth: 3, breakLength: Infinity })
+ } catch {
+ return String(a)
+ }
+}
+
+/**
+ * Wrap the console methods so every call also lands in the ring. Returns an uninstaller that
+ * restores the originals (tests; and the wrap must never stack twice).
+ *
+ * Also mirrors `uncaughtExceptionMonitor` — the MONITOR hook, deliberately: a plain
+ * `process.on('uncaughtException')` listener changes crash semantics (the process no longer
+ * dies), and a debug log must observe failures, not swallow them. There is no monitor
+ * equivalent for 'unhandledRejection', and installing that listener suppresses the default
+ * throw-on-unhandled behavior — so rejections are left alone here on purpose.
+ */
+export function installLogSink(buffer: LogBuffer): () => void {
+ const originals = {
+ log: console.log,
+ info: console.info,
+ debug: console.debug,
+ warn: console.warn,
+ error: console.error
+ }
+ for (const name of Object.keys(originals) as (keyof typeof originals)[]) {
+ console[name] = (...args: unknown[]): void => {
+ originals[name].apply(console, args)
+ try {
+ const { tag, rest } = splitTag(args[0])
+ const tail = args.slice(1).map(formatArg).join(' ')
+ buffer.push({ level: LEVEL[name], tag, msg: tail ? `${rest} ${tail}` : rest })
+ } catch {
+ /* logging must never throw into the caller */
+ }
+ }
+ }
+ const onUncaught = (err: Error): void => {
+ try {
+ buffer.push({ level: 'error', tag: 'uncaught', msg: err?.stack ?? String(err) })
+ } catch {
+ /* see above */
+ }
+ }
+ process.on('uncaughtExceptionMonitor', onUncaught)
+ return () => {
+ Object.assign(console, originals)
+ process.removeListener('uncaughtExceptionMonitor', onUncaught)
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 32067ee58..5c672d0a5 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -7,8 +7,17 @@ import { homedir, hostname } from 'os'
import { randomUUID } from 'crypto'
import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, Notification, powerMonitor, safeStorage, shell, systemPreferences, webContents } from 'electron'
import { IPC } from '../shared/ipc'
+
+// Debug log ring (issue #78): capture the process console from the first line — a packaged app
+// swallows it entirely, and the boot path is where the interesting warnings are. The ring is
+// in-memory and redacted at its push boundary; the panel/IPC side is gated on the setting.
+const logBuffer = new LogBuffer()
+installLogSink(logBuffer)
import { writeFilesToClipboard } from './clipboard-files'
import { registerFsHandlers } from '../core/fs-handlers'
+import { LogBuffer } from '../core/log-buffer'
+import { installLogSink } from '../core/log-sink'
+import { registerLogHandlers } from '../core/log-handlers'
import {
registerBrowserGuest,
type BrowserGuest,
@@ -670,6 +679,17 @@ app.whenReady().then(async () => {
// window's setWindowOpenHandler / will-navigate above don't cover it). Registered once at
// startup for all current and future guests.
app.on('web-contents-created', (_e, contents) => {
+ // Mirror renderer consoles into the debug ring (issue #78) — a packaged app swallows them
+ // too, and React error boundaries report through console.error. All webContents kinds:
+ // the main window and webview guests alike.
+ contents.on('console-message', (event) => {
+ try {
+ const level = event.level === 'error' ? 'error' : event.level === 'warning' ? 'warn' : 'info'
+ logBuffer.push({ level, tag: 'renderer', msg: String(event.message ?? '') })
+ } catch {
+ /* logging must never break a page */
+ }
+ })
if (contents.getType() !== 'webview') return
// Web nodes may only show http(s) pages or local content we serve via the jailed
// nt-media:// scheme.
@@ -1096,6 +1116,7 @@ app.whenReady().then(async () => {
}
}
registerBoardLogHandlers(corePlatform, boardLogRouter)
+ registerLogHandlers(corePlatform, logBuffer, () => settingsStore.get().debugLogPanel)
// Agent messaging (the `send`/`reply` control verbs). Canvas.tsx forwards the validated verb
// here; everything that authorizes or performs the delivery reads MAIN's stores. See
diff --git a/src/preload/index.ts b/src/preload/index.ts
index f4072ed00..27a321e10 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -7,6 +7,7 @@ import type {
Project,
PtyCreateOptions,
PtyPressure,
+ LogRecord,
RecycledInfo,
RelayPeerPending,
RemoteUsageQuery,
@@ -567,6 +568,19 @@ const api: NodeTerminalApi = {
}
}
},
+ logs: {
+ snapshot: () => ipcRenderer.invoke(IPC.logSnapshot),
+ clear: () => ipcRenderer.send(IPC.logClear),
+ onBatch: (cb) => {
+ const handler = (_e: unknown, batch: LogRecord[]): void => cb(batch)
+ ipcRenderer.on(IPC.logBatch, handler)
+ ipcRenderer.send(IPC.logSubscribe)
+ return () => {
+ ipcRenderer.removeListener(IPC.logBatch, handler)
+ ipcRenderer.send(IPC.logUnsubscribe)
+ }
+ }
+ },
// Per-node subscriptions (each terminal/editor listens) — multiplexed so they don't pile up
// ipcRenderer listeners and trip the MaxListeners warning.
onMarkdownToggle: subscribe(IPC.appToggleMarkdown),
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index 9e8bee22e..c31869fc5 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -11,7 +11,7 @@
// benign value, and everything else rejects with a coded error.
//
// The object is `satisfies Omit<NodeTerminalApi, 'pty' | 'workspace' | 'settings' | 'fs' | 'git'
-// | 'files' | 'context' | 'boardLog' | 'dialog'>`, so the TypeScript compiler is the completeness test: if
+// | 'files' | 'context' | 'boardLog' | 'logs' | 'dialog'>`, so the TypeScript compiler is the completeness test: if
// `NodeTerminalApi` gains a member, this file fails to typecheck until the stub is declared.
import {
@@ -112,6 +112,7 @@ export function buildStubApi(): Omit<
| 'files'
| 'context'
| 'boardLog'
+ | 'logs'
| 'githubIssues'
| 'githubControl'
| 'canvas'
@@ -415,6 +416,7 @@ export function buildStubApi(): Omit<
| 'files'
| 'context'
| 'boardLog'
+ | 'logs'
| 'githubIssues'
| 'githubControl'
| 'canvas'
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index e9c6d11fa..1762f6079 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -18,6 +18,8 @@ import type { GitHubControlApi, GitHubIssuesApi } from '../../shared/github-issu
import {
UNKNOWN_CLAUDE_CLI_CAPS,
type BoardLogApi,
+ type LogApi,
+ type LogRecord,
type BoardLogReadResult,
type ChatTranscriptResult,
type ClaudeApi,
@@ -381,7 +383,7 @@ export function buildGitHubApi(
*/
export function buildFilesApi(
client: RpcClient
-): Pick<NodeTerminalApi, 'fs' | 'git' | 'files' | 'context' | 'boardLog'> {
+): Pick<NodeTerminalApi, 'fs' | 'git' | 'files' | 'context' | 'boardLog' | 'logs'> {
const fs: FsApi = {
list: (dirPath) => client.request(IPC.fsList, dirPath) as ReturnType<FsApi['list']>,
read: (filePath) => client.request(IPC.fsRead, filePath) as Promise<string>,
@@ -518,7 +520,22 @@ export function buildFilesApi(
}
}
- return { fs, git, files, context, boardLog }
+ // Same core on the server, so the log ring is real over the bridge — the panel debugs the
+ // Server Edition process, which is exactly where a packaged-app console is least visible.
+ const logs: LogApi = {
+ snapshot: () => client.request(IPC.logSnapshot) as Promise<LogRecord[]>,
+ clear: () => client.cast(IPC.logClear),
+ onBatch: (cb) => {
+ const unsub = client.subscribe(IPC.logBatch, cb as Listener)
+ client.cast(IPC.logSubscribe)
+ return () => {
+ unsub()
+ client.cast(IPC.logUnsubscribe)
+ }
+ }
+ }
+
+ return { fs, git, files, context, boardLog, logs }
}
/**
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 9b4a284c6..bd54242be 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -831,6 +831,17 @@ export function Canvas() {
const [settingsSection, setSettingsSection] = useState<SettingsSectionId | undefined>(undefined)
const [scOpen, setScOpen] = useState(false)
const [shortcutsOpen, setShortcutsOpen] = useState(false)
+ // Debug log panel (issue #78). Settings' "Open" button fires the event (the dialog can't
+ // reach Canvas state directly), and the settings dialog closes so the panel is visible.
+ const [logPanelOpen, setLogPanelOpen] = useState(false)
+ useEffect(() => {
+ const onOpen = (): void => {
+ setSettingsOpen(false)
+ setLogPanelOpen(true)
+ }
+ window.addEventListener('nodeterm:open-log-panel', onOpen)
+ return () => window.removeEventListener('nodeterm:open-log-panel', onOpen)
+ }, [])
// First-run setup tour (agents / dictation / kanban / notifications) — see OnboardingFlow.
const [onboardingOpen, setOnboardingOpen] = useState(false)
// One-shot mobile-launch announcement for established installs — see MobileLaunchCard.
@@ -8855,6 +8866,18 @@ export function Canvas() {
note: isSshProject ? WORKTREE_SSH_HINT : undefined,
run: () => openWorktreeDialog(null)
},
+ ...(useSettings.getState().settings.debugLogPanel
+ ? [
+ {
+ id: 'debug-log',
+ label: 'Show debug log',
+ hint: 'console diagnostics troubleshoot',
+ section: 'View',
+ icon: <IconGear />,
+ run: () => setLogPanelOpen(true)
+ } satisfies Command
+ ]
+ : []),
{ id: 'new-project', label: 'New project', icon: <IconProject />, run: () => addProject() },
{ id: 'clone-repo', label: 'Clone repository…', icon: <IconProject />, run: () => setCloneDialogOpen(true) },
{
diff --git a/src/renderer/components/LogPanel.tsx b/src/renderer/components/LogPanel.tsx
new file mode 100644
index 000000000..d96f81d94
--- /dev/null
+++ b/src/renderer/components/LogPanel.tsx
@@ -0,0 +1,161 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { createPortal } from 'react-dom'
+import type { LogRecord } from '@shared/types'
+
+export interface LogPanelProps {
+ onClose: () => void
+}
+
+const LEVELS = ['debug', 'info', 'warn', 'error'] as const
+type Level = (typeof LEVELS)[number]
+
+/** Mirror cap — same as the main-process ring, so the panel can never outgrow its source. */
+const MIRROR_CAP = 2000
+
+function fmtTime(ts: number): string {
+ const d = new Date(ts)
+ const p = (n: number): string => String(n).padStart(2, '0')
+ return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
+}
+
+/**
+ * Live debug log viewer (issue #78). The main process's ring is the source of truth: mount
+ * snapshots it, then batched pushes stream in — both dedupe by `seq`, so the overlap around the
+ * subscribe edge is harmless. Everything here is view state; closing the panel loses nothing.
+ */
+export function LogPanel({ onClose }: LogPanelProps) {
+ const [entries, setEntries] = useState<LogRecord[]>([])
+ const [levels, setLevels] = useState<Set<Level>>(() => new Set(LEVELS))
+ const [query, setQuery] = useState('')
+ const feedRef = useRef<HTMLDivElement>(null)
+ // Stick to the bottom while the user is AT the bottom; a manual scroll up pins the view so a
+ // chatty subsystem can't yank the line being read out from under the pointer.
+ const stickRef = useRef(true)
+
+ useEffect(() => {
+ let dead = false
+ const append = (batch: LogRecord[]): void => {
+ if (dead || batch.length === 0) return
+ setEntries((prev) => {
+ const last = prev.length ? prev[prev.length - 1].seq : 0
+ const fresh = batch.filter((r) => r.seq > last)
+ if (fresh.length === 0) return prev
+ const next = [...prev, ...fresh]
+ return next.length > MIRROR_CAP ? next.slice(next.length - MIRROR_CAP) : next
+ })
+ }
+ void window.nodeTerminal.logs.snapshot().then((snap) => {
+ if (!dead) setEntries(snap)
+ })
+ const unsub = window.nodeTerminal.logs.onBatch(append)
+ return () => {
+ dead = true
+ unsub()
+ }
+ }, [])
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => {
+ if (e.key === 'Escape') onClose()
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [onClose])
+
+ const filtered = useMemo(() => {
+ const q = query.trim().toLowerCase()
+ return entries.filter(
+ (r) =>
+ levels.has(r.level) &&
+ (!q || r.msg.toLowerCase().includes(q) || r.tag.toLowerCase().includes(q))
+ )
+ }, [entries, levels, query])
+
+ // Auto-scroll after each render while stuck to the bottom.
+ useEffect(() => {
+ const el = feedRef.current
+ if (el && stickRef.current) el.scrollTop = el.scrollHeight
+ }, [filtered])
+
+ const toggleLevel = (l: Level): void => {
+ setLevels((prev) => {
+ const next = new Set(prev)
+ if (next.has(l)) next.delete(l)
+ else next.add(l)
+ return next
+ })
+ }
+
+ const copyAll = (): void => {
+ const text = filtered
+ .map((r) => `${fmtTime(r.ts)} ${r.level.toUpperCase().padEnd(5)} ${r.tag ? `[${r.tag}] ` : ''}${r.msg}`)
+ .join('\n')
+ void navigator.clipboard.writeText(text)
+ }
+
+ const clear = (): void => {
+ window.nodeTerminal.logs.clear()
+ setEntries([])
+ }
+
+ return createPortal(
+ <div className="sc-overlay" onClick={onClose}>
+ <div className="logpanel" onClick={(e) => e.stopPropagation()}>
+ <div className="logpanel__head">
+ <h2>Debug log</h2>
+ <div className="logpanel__chips">
+ {LEVELS.map((l) => (
+ <button
+ key={l}
+ className={`logpanel__chip logpanel__chip--${l}${levels.has(l) ? ' is-on' : ''}`}
+ onClick={() => toggleLevel(l)}
+ >
+ {l}
+ </button>
+ ))}
+ </div>
+ <input
+ className="logpanel__filter"
+ placeholder="Filter…"
+ value={query}
+ spellCheck={false}
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ <button className="logpanel__act" title="Copy the filtered lines" onClick={copyAll}>
+ Copy
+ </button>
+ <button className="logpanel__act" title="Empty the ring" onClick={clear}>
+ Clear
+ </button>
+ <button className="drawer__close" onClick={onClose}>
+ ×
+ </button>
+ </div>
+ <div
+ className="logpanel__feed"
+ ref={feedRef}
+ onScroll={(e) => {
+ const el = e.currentTarget
+ stickRef.current = el.scrollTop + el.clientHeight >= el.scrollHeight - 8
+ }}
+ >
+ {filtered.length === 0 ? (
+ <div className="logpanel__empty">
+ Nothing captured{query || levels.size < LEVELS.length ? ' matching the filter' : ' yet'}.
+ </div>
+ ) : (
+ filtered.map((r) => (
+ <div key={r.seq} className={`logpanel__row logpanel__row--${r.level}`}>
+ <span className="logpanel__time">{fmtTime(r.ts)}</span>
+ <span className={`logpanel__level logpanel__level--${r.level}`}>{r.level}</span>
+ {r.tag && <span className="logpanel__tag">[{r.tag}]</span>}
+ <span className="logpanel__msg">{r.msg}</span>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/lazyPanels.tsx b/src/renderer/components/lazyPanels.tsx
index 84966dda1..dd8ad2805 100644
--- a/src/renderer/components/lazyPanels.tsx
+++ b/src/renderer/components/lazyPanels.tsx
@@ -68,6 +68,9 @@ export const MobileLaunchCard = withSuspense(
export const PhonePairPopover = withSuspense(
lazy(() => import('./PhonePairPopover').then((m) => ({ default: m.PhonePairPopover })))
)
+export const LogPanel = withSuspense(
+ lazy(() => import('./LogPanel').then((m) => ({ default: m.LogPanel })))
+)
export const KanbanView = withSuspense(
lazy(() => import('./kanban/KanbanView').then((m) => ({ default: m.KanbanView })))
)
diff --git a/src/renderer/components/settings/SettingsIcons.tsx b/src/renderer/components/settings/SettingsIcons.tsx
index b5ce81c4f..3df4e9a6c 100644
--- a/src/renderer/components/settings/SettingsIcons.tsx
+++ b/src/renderer/components/settings/SettingsIcons.tsx
@@ -127,7 +127,14 @@ const PATHS: Record<SettingsSectionId, React.JSX.Element> = {
</>
),
updates: <path d="M8 2.6v7M5 6.6 8 9.6l3-3M3.6 12.6h8.8" />,
- privacy: <path d="M8 2.4 12.4 4.2V8c0 3-2 4.8-4.4 5.6C5.6 12.8 3.6 11 3.6 8V4.2Z" />
+ privacy: <path d="M8 2.4 12.4 4.2V8c0 3-2 4.8-4.4 5.6C5.6 12.8 3.6 11 3.6 8V4.2Z" />,
+ // A tiny bug (the debug section).
+ debug: (
+ <>
+ <circle cx="8" cy="9" r="3.5" />
+ <path d="M8 5.5V3.5M4.9 6.6 3.4 5.1M11.1 6.6l1.5-1.5M4.5 9H2.5M13.5 9h-2M4.9 11.4l-1.5 1.5M11.1 11.4l1.5 1.5" />
+ </>
+ )
}
export function SectionIcon({ id }: { id: SettingsSectionId }): React.JSX.Element {
diff --git a/src/renderer/components/settings/SettingsPage.tsx b/src/renderer/components/settings/SettingsPage.tsx
index dd684ef81..d69d9d67d 100644
--- a/src/renderer/components/settings/SettingsPage.tsx
+++ b/src/renderer/components/settings/SettingsPage.tsx
@@ -25,6 +25,7 @@ import { TeamAccessSection } from './sections/TeamAccessSection'
import { SshSection } from './sections/SshSection'
import { UpdatesSection } from './sections/UpdatesSection'
import { PrivacySection } from './sections/PrivacySection'
+import { DebugSection } from './sections/DebugSection'
import { GitHubIssuesSection } from './sections/GitHubIssuesSection'
import { ModelGatewaySection } from './sections/ModelGatewaySection'
@@ -94,6 +95,7 @@ export function SettingsPage({
<SshSection isActive={active === 'ssh'} />
<UpdatesSection isActive={active === 'updates'} />
<PrivacySection isActive={active === 'privacy'} />
+ <DebugSection isActive={active === 'debug'} />
</div>
</main>
</SettingsSearchContext.Provider>
diff --git a/src/renderer/components/settings/nav.test.ts b/src/renderer/components/settings/nav.test.ts
index 0b6e6add7..60acd2e6c 100644
--- a/src/renderer/components/settings/nav.test.ts
+++ b/src/renderer/components/settings/nav.test.ts
@@ -2,10 +2,10 @@ import { describe, it, expect } from 'vitest'
import { SETTINGS_GROUPS, allSectionIds, FIRST_SECTION_ID, visibleSettingsGroups } from './nav'
describe('SETTINGS_GROUPS', () => {
- it('lists exactly 23 sections with no duplicates', () => {
+ it('lists exactly 24 sections with no duplicates', () => {
const ids = allSectionIds()
- expect(ids).toHaveLength(23)
- expect(new Set(ids).size).toBe(23)
+ expect(ids).toHaveLength(24)
+ expect(new Set(ids).size).toBe(24)
})
it('starts at a section that exists in the groups', () => {
expect(allSectionIds()).toContain(FIRST_SECTION_ID)
@@ -13,7 +13,7 @@ describe('SETTINGS_GROUPS', () => {
it('hides mac-only sections off macOS, keeps them on', () => {
const off = visibleSettingsGroups(false).flatMap((g) => g.sections.map((s) => s.id))
expect(off).not.toContain('notch')
- expect(off).toHaveLength(22)
+ expect(off).toHaveLength(23)
expect(visibleSettingsGroups(true)).toEqual(SETTINGS_GROUPS)
// No group is left empty by the filter.
expect(visibleSettingsGroups(false).every((g) => g.sections.length > 0)).toBe(true)
diff --git a/src/renderer/components/settings/nav.ts b/src/renderer/components/settings/nav.ts
index f242f3e5f..4c89a2f5a 100644
--- a/src/renderer/components/settings/nav.ts
+++ b/src/renderer/components/settings/nav.ts
@@ -22,6 +22,7 @@ export type SettingsSectionId =
| 'ssh'
| 'updates'
| 'privacy'
+ | 'debug'
export interface SettingsSectionRef {
id: SettingsSectionId
@@ -89,7 +90,8 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [
sections: [
{ id: 'license', title: 'License' },
{ id: 'updates', title: 'Updates' },
- { id: 'privacy', title: 'Privacy' }
+ { id: 'privacy', title: 'Privacy' },
+ { id: 'debug', title: 'Debug' }
]
}
]
diff --git a/src/renderer/components/settings/sections/DebugSection.tsx b/src/renderer/components/settings/sections/DebugSection.tsx
new file mode 100644
index 000000000..3346f41d0
--- /dev/null
+++ b/src/renderer/components/settings/sections/DebugSection.tsx
@@ -0,0 +1,52 @@
+import { useSettings } from '../../../state/settings'
+import { SettingsSection } from '../SettingsSection'
+import { SearchableRow } from '../SearchableRow'
+import { FieldRow } from '../FieldRow'
+import { Switch } from '@renderer/ui/Switch'
+import { Button } from '@renderer/ui/Button'
+
+const ROWS = {
+ logPanel: {
+ title: 'Debug log panel',
+ keywords: ['debug', 'log', 'logs', 'console', 'diagnostics', 'troubleshoot']
+ }
+}
+const ENTRIES = Object.values(ROWS)
+
+export function DebugSection({ isActive }: { isActive: boolean }): React.JSX.Element {
+ const debugLogPanel = useSettings((s) => s.settings.debugLogPanel)
+ const update = useSettings((s) => s.update)
+ return (
+ <SettingsSection id="debug" title="Debug" isActive={isActive} searchEntries={ENTRIES}>
+ <SearchableRow {...ROWS.logPanel}>
+ <FieldRow
+ label="Debug log panel"
+ description="Captures the app's own console into an in-memory ring (secrets redacted at capture) and unlocks the log viewer — also in the command palette as “Show debug log”. Nothing is written to disk or sent anywhere; export is manual copy."
+ control={
+ <Switch
+ checked={debugLogPanel}
+ onChange={(v) => update({ debugLogPanel: v })}
+ ariaLabel="Debug log panel"
+ />
+ }
+ />
+ {debugLogPanel && (
+ <FieldRow
+ label="Log viewer"
+ description="Live view of the ring, with level and text filters."
+ control={
+ <Button
+ onClick={() =>
+ // Canvas listens; the settings dialog closes itself so the panel is visible.
+ window.dispatchEvent(new CustomEvent('nodeterm:open-log-panel'))
+ }
+ >
+ Open
+ </Button>
+ }
+ />
+ )}
+ </SearchableRow>
+ </SettingsSection>
+ )
+}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index ce53cbbd4..ed41442c9 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -4941,6 +4941,135 @@ body,
background: rgba(10, 12, 18, 0.5);
}
+/* --- Debug log panel (issue #78) — same overlay family as the shortcuts panel ------------- */
+.logpanel {
+ width: 860px;
+ max-width: 94vw;
+ height: 70vh;
+ display: flex;
+ flex-direction: column;
+ background: rgba(var(--menu-rgb), 0.99);
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ box-shadow: 0 24px 64px rgba(0, 0, 0, calc(0.6 * var(--shadow-k)));
+ overflow: hidden;
+}
+.logpanel__head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 14px;
+ border-bottom: 1px solid var(--border);
+}
+.logpanel__head h2 {
+ margin: 0 6px 0 0;
+ font-size: 14px;
+ color: var(--text-strong);
+ white-space: nowrap;
+}
+.logpanel__chips {
+ display: flex;
+ gap: 4px;
+}
+.logpanel__chip {
+ border: 1px solid var(--border);
+ background: transparent;
+ color: var(--muted);
+ border-radius: 999px;
+ font-size: 11px;
+ padding: 2px 9px;
+ cursor: pointer;
+}
+.logpanel__chip.is-on {
+ background: rgba(var(--tint-rgb), 0.08);
+ color: var(--text);
+}
+.logpanel__chip--warn.is-on {
+ color: var(--warn);
+}
+.logpanel__chip--error.is-on {
+ color: var(--danger);
+}
+.logpanel__filter {
+ flex: 1;
+ min-width: 80px;
+ background: rgba(var(--tint-rgb), 0.06);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ color: var(--text);
+ font-size: 12px;
+ padding: 4px 9px;
+}
+.logpanel__filter:focus {
+ outline: none;
+ border-color: var(--accent);
+}
+.logpanel__act {
+ border: 1px solid var(--border);
+ background: transparent;
+ color: var(--text);
+ border-radius: 8px;
+ font-size: 12px;
+ padding: 4px 10px;
+ cursor: pointer;
+}
+.logpanel__act:hover {
+ background: rgba(var(--tint-rgb), 0.08);
+}
+.logpanel__feed {
+ flex: 1;
+ overflow-y: auto;
+ padding: 8px 0;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11.5px;
+ line-height: 1.5;
+}
+.logpanel__row {
+ display: flex;
+ gap: 8px;
+ padding: 0 14px;
+ align-items: baseline;
+}
+.logpanel__row:hover {
+ background: rgba(var(--tint-rgb), 0.04);
+}
+.logpanel__time {
+ color: var(--muted-2);
+ flex: none;
+}
+.logpanel__level {
+ flex: none;
+ width: 42px;
+ text-transform: uppercase;
+ font-size: 10px;
+ color: var(--muted);
+}
+.logpanel__level--warn {
+ color: var(--warn);
+}
+.logpanel__level--error {
+ color: var(--danger);
+}
+.logpanel__tag {
+ color: var(--accent);
+ flex: none;
+}
+.logpanel__msg {
+ color: var(--text);
+ white-space: pre-wrap;
+ word-break: break-word;
+ min-width: 0;
+}
+.logpanel__row--debug .logpanel__msg {
+ color: var(--muted);
+}
+.logpanel__empty {
+ color: var(--muted);
+ text-align: center;
+ padding: 32px 0;
+ font-family: inherit;
+}
+
.shortcuts {
width: 560px;
max-width: 92vw;
diff --git a/src/server/index.ts b/src/server/index.ts
index b58c46ed1..71c6f1f6b 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -31,6 +31,9 @@ import {
} from '../core/model-gateway-credentials'
import { DownloadTickets } from '../core/download-tickets'
import { registerBoardLogHandlers, type BoardLogRoute } from '../core/board-log-handlers'
+import { LogBuffer } from '../core/log-buffer'
+import { installLogSink } from '../core/log-sink'
+import { registerLogHandlers } from '../core/log-handlers'
import os from 'os'
import { hookServer } from '../core/agents/hook-server'
import { serverEditionControlHandler } from './control-unsupported'
@@ -283,6 +286,12 @@ export async function startServer(
}
})
+ // Debug log ring (issue #78) — same core registrar as desktop. Headless is where a swallowed
+ // console hurts most; the browser-side panel reads this process's ring over the bridge.
+ const logBuffer = new LogBuffer()
+ installLogSink(logBuffer)
+ registerLogHandlers(platform, logBuffer, () => settingsStore.get().debugLogPanel)
+
// Agent status pipeline — mirrors the desktop boot order in src/main/index.ts:
// mirror-init → wire the hook-server listeners onto the platform → install the managed hook
// scripts → start the loopback hook server. The hook server binds its own port independent of
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 656201acb..ce062078e 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -136,6 +136,16 @@ export const IPC = {
contextLinkInfo: 'context-link:info',
/** Board-log (`.nodeterm/board-log.jsonl`): request/response append + read, routed per project
* (local cwd / desktop-ssh / unsupported) in core/board-log-handlers.ts. */
+ /** Debug log panel (issue #78) — invoke: the whole ring (LogRecord[]) for the initial fill. */
+ logSnapshot: 'log:snapshot',
+ /** Fire-and-forget ref-counted subscribe/unsubscribe for the batched logBatch pushes. */
+ logSubscribe: 'log:subscribe',
+ logUnsubscribe: 'log:unsubscribe',
+ /** main→renderer push: a LogRecord[] batch. Flows only while ≥1 panel is subscribed AND the
+ * debugLogPanel setting is on; the client dedupes by seq. */
+ logBatch: 'log:batch',
+ /** Fire-and-forget: empty the ring. */
+ logClear: 'log:clear',
boardLogAppend: 'board-log:append',
boardLogRead: 'board-log:read',
/** Fire-and-forget ref-counted subscribe/unsubscribe: the first subscriber for a project starts
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 86905c2f7..495bde937 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -469,6 +469,28 @@ export interface BoardLogReadResult {
/** The board-log surface on `window.nodeTerminal`. Project-routed: the main/server side resolves
* the project to a local cwd, a desktop SSH connection, or unsupported. `append` is
* fire-and-forget-safe (resolves `false` on any failure, never throws). */
+/** One captured debug-log line (issue #78). `seq` is monotonic across the process lifetime so
+ * subscribers can dedupe batches against the snapshot they filled from. */
+export interface LogRecord {
+ seq: number
+ /** Epoch ms. */
+ ts: number
+ level: 'debug' | 'info' | 'warn' | 'error'
+ /** The `[subsystem]` prefix convention the codebase logs with; '' when absent. */
+ tag: string
+ msg: string
+}
+
+export interface LogApi {
+ /** The whole ring, oldest-first — the panel's initial fill. */
+ snapshot(): Promise<LogRecord[]>
+ /** Empty the ring (the panel's Clear button). */
+ clear(): void
+ /** Subscribe to batched pushes; returns an unsubscribe. Batches may overlap the snapshot
+ * around the subscribe edge — dedupe by `seq`. */
+ onBatch(cb: (batch: LogRecord[]) => void): () => void
+}
+
export interface BoardLogApi {
/** Append one entry. Resolves `false` on any failure (unsupported project, fs/exec error). */
append(projectId: string, entry: BoardLogEntry): Promise<boolean>
@@ -1099,6 +1121,10 @@ export interface Settings {
* (or hard-disable with DO_NOT_TRACK / NODETERM_TELEMETRY_DISABLED). Note: a lighter anonymous
* install count also rides the /v1/check call and is NOT gated on this toggle — see core/check.ts. */
telemetryEnabled: boolean
+ /** Debug log panel (issue #78): captures the app's own console into an in-memory, redacted
+ * ring and unlocks the log viewer. Default off — a debugging tool, not a daily surface.
+ * Toggle in Settings → Application → Debug. */
+ debugLogPanel: boolean
/** Keep a standing relay host connection so a paired phone can reach this Mac from anywhere
* (end-to-end encrypted). Default on — the host only admits SAS-approved, pinned devices, so
* an un-paired install just keeps an idle listener. Toggle in Settings → Phone. */
@@ -1229,6 +1255,7 @@ export const DEFAULT_SETTINGS: Settings = {
// Opt-out (default on). Existing users pick this up on hydrate ONLY if their settings.json has
// no telemetryEnabled key yet; anyone who already saved settings keeps their stored value.
telemetryEnabled: true,
+ debugLogPanel: false,
phoneAccessEnabled: true,
mobilePushEnabled: true,
mobilePushNeedsYou: true,
@@ -2352,6 +2379,7 @@ export interface NodeTerminalApi {
license: LicenseApi
contextLink: ContextLinkApi
boardLog: BoardLogApi
+ logs: LogApi
githubIssues: import('./github-issues').GitHubIssuesApi
githubControl: import('./github-issues').GitHubControlApi
usage: UsageApi