From b855a4ca420ea555a8d80348c8254920e942971e Mon Sep 17 00:00:00 2001 From: Vincenzo Favara Date: Fri, 13 Nov 2026 09:06:53 +0100 Subject: [PATCH] Add a Task Manager that shows how much RAM each session uses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit More → Task Manager lists every running session and task, heaviest first, with the memory, CPU and process count of its whole process tree: the CLI plus its MCP servers, dev servers and builds. A row opens into its processes, and each child can be killed on its own while the session goes on. Stop ends a session the usual way, then terminates whatever of its tree outlived the hangup (SIGTERM, then SIGKILL), so a child that ignores SIGHUP is not left behind as an invisible orphan. Pids are always resolved in main from the session or task itself, and a kill only reaches a process that is still in that tree. --- main.js | 97 ++++++++ preload.js | 5 + process-monitor.js | 254 +++++++++++++++++++ public/app.js | 7 +- public/grid-view.js | 3 +- public/icons.js | 2 + public/index.html | 11 + public/plans-memory-view.js | 5 +- public/process-viewer.js | 433 +++++++++++++++++++++++++++++++++ public/settings-panel.js | 1 + public/style.css | 460 +++++++++++++++++++++++++++++++++++ task-manager.js | 17 ++ test/process-monitor.test.js | 173 +++++++++++++ test/task-manager.test.js | 21 ++ 14 files changed, 1485 insertions(+), 4 deletions(-) create mode 100644 process-monitor.js create mode 100644 public/process-viewer.js create mode 100644 test/process-monitor.test.js diff --git a/main.js b/main.js index d09bceba2..58c92164f 100644 --- a/main.js +++ b/main.js @@ -44,6 +44,7 @@ const { resolveTerminalFiles } = require('./terminal-file-links'); const { PREVIEW_SCHEME, PREVIEW_SCHEMES, handlePreviewAssetRequest } = require('./preview-assets'); protocol.registerSchemesAsPrivileged(PREVIEW_SCHEMES); const { createTaskManager } = require('./task-manager'); +const { createProcessMonitor } = require('./process-monitor'); const { lastAssistantMessage } = require('./session-preview'); @@ -1165,6 +1166,102 @@ ipcMain.handle('stop-session', (_event, sessionId) => { return { ok: true }; }); +// --- IPC: RAM task manager --- +// What each live session and running task costs, measured over its whole +// process tree (the CLI, its MCP servers, whatever it started), so the heavy +// ones can be found and stopped. Root pids are always looked up here, never +// taken from the renderer. +const processMonitor = createProcessMonitor(); + +/** The live session behind an id, also under the real id a fork or plan-accept gave it. */ +function ownedSession(sessionId) { + let session = activeSessions.get(sessionId); + if (!session) session = [...activeSessions.values()].find(s => s.realSessionId === sessionId); + return session && !session.exited ? session : null; +} + +/** One entry per live session and per running task, each with the pid its tree hangs from. */ +function processOwners() { + const owners = []; + const seen = new Set(); + for (const [key, session] of activeSessions) { + if (seen.has(session) || session.exited) continue; + seen.add(session); + owners.push({ + kind: 'session', + id: session.realSessionId || key, + pid: session.pty?.pid || null, + type: session.isPlainTerminal ? 'terminal' : 'cli', + runtime: session.isPlainTerminal ? null : session.runtime || null, + projectPath: session.projectPath || null, + startedAt: session._openedAt || null, + busy: !!session._cliBusy, + stopRequested: !!session.stopRequested, + }); + } + for (const task of taskManager.listProcesses()) { + owners.push({ kind: 'task', id: `${task.projectPath}\0${task.label}`, type: 'task', ...task }); + } + return owners; +} + +function ownerRootPid(owner) { + if (owner?.kind === 'session') return ownedSession(owner.id)?.pty?.pid || null; + if (owner?.kind === 'task') { + return taskManager.listProcesses().find(t => t.projectPath === owner.projectPath && t.label === owner.label)?.pid || null; + } + return null; +} + +ipcMain.handle('get-process-usage', async () => { + const owners = await processMonitor.measure(processOwners()); + // Switchboard's own Electron processes (main, window, GPU), for scale. + const metrics = app.getAppMetrics(); + let appBytes = 0; + let appCpu = 0; + for (const metric of metrics) { + appBytes += (metric.memory?.workingSetSize || 0) * 1024; + appCpu += metric.cpu?.percentCPUUsage || 0; + } + return { + platform: process.platform, + totalMemBytes: os.totalmem(), + app: { rssBytes: appBytes, cpu: Math.round(appCpu * 10) / 10, processCount: metrics.length }, + owners, + sampledAt: Date.now(), + }; +}); + +// The Task Manager's Stop: the usual stop, then nothing of the tree left behind, +// not even a child that ignored the hangup (see stopTree). +ipcMain.handle('stop-owner', async (_event, owner) => { + const rootPid = ownerRootPid(owner); + if (!rootPid) return { ok: false, error: 'Not running' }; + return processMonitor.stopTree(rootPid, () => { + if (owner.kind === 'task') return taskManager.stopTask(owner.projectPath, owner.label); + const session = ownedSession(owner.id); + if (!session) return null; + session.stopRequested = true; + return session.pty.kill(); + }); +}); + +// One process inside a session's or task's tree: SIGTERM, or SIGKILL when forced. +ipcMain.handle('kill-owned-process', async (_event, owner, pid, force) => { + const rootPid = ownerRootPid(owner); + if (!rootPid) return { ok: false, error: 'Not running' }; + return processMonitor.killInTree(rootPid, Number(pid), force ? 'SIGKILL' : 'SIGTERM'); +}); + +// The way out when Stop is not enough: SIGKILL the whole tree, still counted as stopped by the user. +ipcMain.handle('force-stop-owner', async (_event, owner) => { + const rootPid = ownerRootPid(owner); + if (!rootPid) return { ok: false, error: 'Not running' }; + if (owner.kind === 'session') ownedSession(owner.id).stopRequested = true; + else taskManager.stopTask(owner.projectPath, owner.label); + return processMonitor.killTree(rootPid); +}); + // --- IPC: toggle-star --- ipcMain.handle('toggle-star', (_event, sessionId) => { const starred = toggleStar(sessionId); diff --git a/preload.js b/preload.js index f98e36c73..aa17b7086 100644 --- a/preload.js +++ b/preload.js @@ -18,6 +18,11 @@ contextBridge.exposeInMainWorld('api', { getActiveSessions: () => ipcRenderer.invoke('get-active-sessions'), getActiveTerminals: () => ipcRenderer.invoke('get-active-terminals'), stopSession: (id) => ipcRenderer.invoke('stop-session', id), + // RAM task manager: memory per session/task tree, and the ways to end one + getProcessUsage: () => ipcRenderer.invoke('get-process-usage'), + stopOwner: (owner) => ipcRenderer.invoke('stop-owner', owner), + killOwnedProcess: (owner, pid, force) => ipcRenderer.invoke('kill-owned-process', owner, pid, force), + forceStopOwner: (owner) => ipcRenderer.invoke('force-stop-owner', owner), toggleStar: (id) => ipcRenderer.invoke('toggle-star', id), renameSession: (id, name) => ipcRenderer.invoke('rename-session', id, name), archiveSession: (id, archived) => ipcRenderer.invoke('archive-session', id, archived), diff --git a/process-monitor.js b/process-monitor.js new file mode 100644 index 000000000..32395c092 --- /dev/null +++ b/process-monitor.js @@ -0,0 +1,254 @@ +// How much memory each live session (and each running task) costs. +// +// A session is a PTY whose pid is a shell or the CLI itself; what it really +// costs is that process plus everything under it: the CLI, its MCP servers, +// the dev servers and builds it starts. So each owner is measured as the sum +// over its whole process tree, from one process-table snapshot per refresh. + +const { execFile } = require('child_process'); +const path = require('path'); + +// Interpreters whose own name says little: "node" is more useful as "node claude". +const SCRIPT_HOSTS = new Set(['node', 'bun', 'deno', 'python', 'python3', 'ruby', 'perl', 'php', 'java']); +// Flags after which an interpreter runs inline code, not a file. +const INLINE_CODE_FLAGS = new Set(['-e', '--eval', '-p', '--print', '-c']); + +/** + * The table `ps -A -o pid=,ppid=,rss=,pcpu=,stat=,comm=` prints, as pid → process. + * rss is in KiB; the command name is last because it may contain spaces. + * Zombies (state Z) have already exited and hold no memory, so they are left out. + */ +function parsePsTable(stdout) { + const table = new Map(); + for (const line of String(stdout || '').split('\n')) { + const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+([\d.,]+)\s+(\S+)\s+(.+?)\s*$/.exec(line); + if (!match || match[5].startsWith('Z')) continue; + const pid = Number(match[1]); + table.set(pid, { + pid, + ppid: Number(match[2]), + rssBytes: Number(match[3]) * 1024, + cpu: Number(match[4].replace(',', '.')) || 0, + name: path.basename(match[6]), + }); + } + return table; +} + +/** The tab-separated table the Windows query prints: pid, ppid, working set in bytes, name. */ +function parseWindowsTable(stdout) { + const table = new Map(); + for (const line of String(stdout || '').split(/\r?\n/)) { + const [pid, ppid, rss, ...name] = line.split('\t'); + if (!/^\d+$/.test(pid || '') || !/^\d+$/.test(ppid || '')) continue; + table.set(Number(pid), { + pid: Number(pid), + ppid: Number(ppid), + rssBytes: Number(rss) || 0, + cpu: null, + name: name.join('\t').trim(), + }); + } + return table; +} + +/** `ps -o pid=,args=` output, as pid → full command line. */ +function parseCommandLines(stdout) { + const lines = new Map(); + for (const line of String(stdout || '').split('\n')) { + const match = /^\s*(\d+)\s+(.*?)\s*$/.exec(line); + if (match) lines.set(Number(match[1]), match[2]); + } + return lines; +} + +/** + * The process at `rootPid` and every descendant, root first, each with its + * depth below the root. Empty when the root is gone. + */ +function collectTree(table, rootPid) { + if (!rootPid || !table.has(rootPid)) return []; + const children = new Map(); + for (const proc of table.values()) { + if (proc.pid === proc.ppid) continue; + if (!children.has(proc.ppid)) children.set(proc.ppid, []); + children.get(proc.ppid).push(proc); + } + const out = []; + const seen = new Set(); + const visit = (proc, depth) => { + if (seen.has(proc.pid)) return; + seen.add(proc.pid); + out.push({ ...proc, depth }); + const kids = (children.get(proc.pid) || []).slice().sort((a, b) => b.rssBytes - a.rssBytes); + for (const kid of kids) visit(kid, depth + 1); + }; + visit(table.get(rootPid), 0); + return out; +} + +/** "node" alone hides which program it runs; name the script too when there is one. */ +function friendlyName(name, commandLine) { + const base = String(name || '').replace(/\.exe$/i, ''); + if (!SCRIPT_HOSTS.has(base.toLowerCase()) || !commandLine) return name || ''; + // The first argument that looks like a file, skipping flags; inline code (-e, -c) has none. + for (const arg of String(commandLine).split(/\s+/).slice(1)) { + if (INLINE_CODE_FLAGS.has(arg)) return name; + if (!arg || arg.startsWith('-')) continue; + if (/[/.]/.test(arg) || /^[A-Za-z]:\\/.test(arg)) return `${base} ${path.win32.basename(arg)}`; + } + return name; +} + +/** Total memory, CPU and process count of one tree. */ +function summarizeTree(procs) { + let rssBytes = 0; + let cpu = 0; + let hasCpu = false; + for (const proc of procs) { + rssBytes += proc.rssBytes || 0; + if (typeof proc.cpu === 'number') { cpu += proc.cpu; hasCpu = true; } + } + return { rssBytes, cpu: hasCpu ? Math.round(cpu * 10) / 10 : null, processCount: procs.length }; +} + +/** Deepest first, so nothing gets a chance to respawn or be reparented midway. */ +function killOrder(procs) { + return procs.slice().sort((a, b) => b.depth - a.depth); +} + +function run(file, args, options = {}) { + return new Promise((resolve, reject) => { + execFile(file, args, { maxBuffer: 16 * 1024 * 1024, timeout: 10000, windowsHide: true, ...options }, (err, stdout) => { + if (err) { err.stdout = stdout; reject(err); } else resolve(stdout); + }); + }); +} + +/** + * @param {object} [options] + * @param {string} [options.platform] process.platform by default + * @param {Function} [options.exec] (file, args, options) → Promise, for tests + * @param {Function} [options.kill] (pid, signal) → void, for tests + * @param {Function} [options.sleep] ms → Promise, for tests + */ +function createProcessMonitor(options = {}) { + const platform = options.platform || process.platform; + const exec = options.exec || run; + const kill = options.kill || ((pid, signal) => process.kill(pid, signal)); + const sleep = options.sleep || (ms => new Promise(resolve => setTimeout(resolve, ms))); + // Numbers printed the C way, whatever the user's locale. + const env = { ...process.env, LC_ALL: 'C' }; + + async function snapshot() { + if (platform === 'win32') { + const script = 'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId)`t$($_.ParentProcessId)`t$($_.WorkingSetSize)`t$($_.Name)" }'; + return parseWindowsTable(await exec('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script])); + } + return parsePsTable(await exec('ps', ['-A', '-o', 'pid=,ppid=,rss=,pcpu=,stat=,comm='], { env })); + } + + /** Full command lines, only for the processes on screen. Best effort. */ + async function commandLines(pids) { + if (!pids.length) return new Map(); + if (platform === 'win32') { + const filter = pids.map(pid => `ProcessId=${Number(pid)}`).join(' OR '); + const script = `Get-CimInstance Win32_Process -Filter "${filter}" | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }`; + try { return parseCommandLines(await exec('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script])); } catch { return new Map(); } + } + try { + return parseCommandLines(await exec('ps', ['-o', 'pid=,args=', '-p', pids.map(Number).join(',')], { env })); + } catch (err) { + // ps exits 1 when one of the pids ended in between, but still prints the rest. + return parseCommandLines(err?.stdout || ''); + } + } + + /** + * Measure each owner ({ pid, ...anything }) as the sum over its process tree. + * Owners come back with rssBytes, cpu, processCount and their processes, + * heaviest first. An owner whose pid is unknown or gone measures zero. + */ + async function measure(owners) { + const table = await snapshot(); + const measured = owners.map(owner => { + const procs = collectTree(table, owner.pid); + return { ...owner, ...summarizeTree(procs), processes: procs, found: procs.length > 0 }; + }); + const pids = measured.flatMap(owner => owner.processes.map(proc => proc.pid)); + const lines = await commandLines(pids); + for (const owner of measured) { + for (const proc of owner.processes) { + proc.command = lines.get(proc.pid) || null; + proc.label = friendlyName(proc.name, proc.command); + } + } + return measured.sort((a, b) => b.rssBytes - a.rssBytes); + } + + /** + * Signal one process, but only one that is still under `rootPid` right now: + * a pid from an older snapshot may since have been reused by anything. + */ + async function killInTree(rootPid, pid, signal = 'SIGTERM') { + const tree = collectTree(await snapshot(), rootPid); + if (!tree.some(proc => proc.pid === pid)) return { ok: false, error: 'That process is no longer part of this session' }; + try { + kill(pid, signal); + return { ok: true }; + } catch (err) { + return { ok: false, error: err.message }; + } + } + + /** SIGKILL the whole tree under `rootPid`, root included. */ + async function killTree(rootPid) { + const tree = collectTree(await snapshot(), rootPid); + if (!tree.length) return { ok: false, error: 'The process has already ended' }; + let killed = 0; + for (const proc of killOrder(tree)) { + try { kill(proc.pid, 'SIGKILL'); killed++; } catch {} + } + return { ok: true, killed }; + } + + /** + * Stop an owner and make sure nothing of it is left behind. `stop` is its + * own way out (the PTY hangup, the task stop); a child that ignores the + * hangup, or runs in the background, would otherwise outlive the session as + * an orphan nobody sees. So whatever of the tree taken before the stop is + * still there after `graceMs` gets SIGTERM, and after `termMs` more SIGKILL. + * A survivor must still carry its name, so a reused pid is never hit. + */ + async function stopTree(rootPid, stop, { graceMs = 2500, termMs = 1500 } = {}) { + const tree = collectTree(await snapshot(), rootPid); + await stop(); + if (!tree.length) return { ok: true, terminated: 0, killed: 0 }; + const survivors = async () => { + const now = await snapshot(); + return tree.filter(proc => now.get(proc.pid)?.name === proc.name); + }; + await sleep(graceMs); + let left = await survivors(); + for (const proc of killOrder(left)) { try { kill(proc.pid, 'SIGTERM'); } catch {} } + const terminated = left.length; + if (!left.length) return { ok: true, terminated: 0, killed: 0 }; + await sleep(termMs); + left = await survivors(); + for (const proc of killOrder(left)) { try { kill(proc.pid, 'SIGKILL'); } catch {} } + return { ok: true, terminated, killed: left.length }; + } + + return { snapshot, measure, killInTree, killTree, stopTree }; +} + +module.exports = { + createProcessMonitor, + parsePsTable, + parseWindowsTable, + parseCommandLines, + collectTree, + friendlyName, + summarizeTree, + killOrder, +}; diff --git a/public/app.js b/public/app.js index ac6c34ead..0febfd028 100644 --- a/public/app.js +++ b/public/app.js @@ -38,6 +38,7 @@ const memoryPanel = new ViewerPanel(memoryViewer, { }); const terminalArea = document.getElementById('terminal-area'); const settingsViewer = document.getElementById('settings-viewer'); +const processViewer = document.getElementById('process-viewer'); const globalSettingsBtn = document.getElementById('global-settings-btn'); const addProjectBtn = document.getElementById('add-project-btn'); const projectsContent = document.getElementById('projects-content'); @@ -552,8 +553,8 @@ globalSettingsBtn.addEventListener('click', () => { openSettingsViewer('global'); }); -// --- "More" button: Plans, Agent Files, Stats and Global settings share one -// menu so the tab strip stays short. The tab buttons stay in the DOM, hidden, +// --- "More" button: Plans, Agent Files, Stats, the Task Manager and Global +// settings share one menu so the tab strip stays short. The tab buttons stay in the DOM, hidden, // so everything that clicks them (shortcuts, the quota gauge) keeps working. const sidebarMoreBtn = document.getElementById('sidebar-more-btn'); const MORE_TABS = ['plans', 'memory', 'stats']; @@ -578,6 +579,7 @@ sidebarMoreBtn.addEventListener('click', (e) => { showContextMenu([ ...MORE_TABS.map(tabItem), { sep: true }, + { label: 'Task Manager', icon: ICONS.memory(14), onClick: () => openProcessViewer() }, { label: 'Global settings', icon: ICONS.gear(14), onClick: () => globalSettingsBtn.click() }, { label: 'Join Slack', icon: slackLink.querySelector('svg').outerHTML, onClick: () => window.api.openExternal(slackLink.href) }, ], { anchor: e.currentTarget }); @@ -1264,6 +1266,7 @@ document.querySelectorAll('.sidebar-tab').forEach(tab => { planViewer.style.display = 'none'; memoryViewer.style.display = 'none'; settingsViewer.style.display = 'none'; + processViewer.style.display = 'none'; statsViewer.style.display = 'flex'; loadStats(); } else if (tabName === 'memory') { diff --git a/public/grid-view.js b/public/grid-view.js index f11896609..c5f8ce09e 100644 --- a/public/grid-view.js +++ b/public/grid-view.js @@ -5,7 +5,7 @@ // Depends on globals from app.js: openSessions, activeSessionId, sessionMap, activePtyIds, // sortedOrder, sidebarContent, terminalsEl, gridViewActive, gridViewer, gridViewerCount, // placeholder, terminalHeader, planViewer, statsViewer, memoryViewer, settingsViewer, -// jsonlViewer, terminalArea, cachedProjects, isMac +// processViewer, jsonlViewer, terminalArea, cachedProjects, isMac // Depends on: cleanDisplayName, formatDate (utils.js), fitAndScroll, showSession (terminal-manager.js) let gridCards = new Map(); // sessionId → card wrapper element @@ -179,6 +179,7 @@ function showGridView() { statsViewer.style.display = 'none'; memoryViewer.style.display = 'none'; settingsViewer.style.display = 'none'; + processViewer.style.display = 'none'; jsonlViewer.style.display = 'none'; if (typeof jsonlSearch !== 'undefined') jsonlSearch?.close(false); terminalArea.style.display = ''; diff --git a/public/icons.js b/public/icons.js index 5d04c2d68..d597d22f9 100644 --- a/public/icons.js +++ b/public/icons.js @@ -9,5 +9,7 @@ window.ICONS = { terminal: (size = 14, cls = '') => ``, // OpenAI's mark, for Codex sessions. codex: (size = 16, cls = '') => ``, + // A RAM module, for the Task Manager. + memory: (size = 14) => ``, gear: (size = 14) => ``, }; diff --git a/public/index.html b/public/index.html index c299a08d9..2a6a81742 100644 --- a/public/index.html +++ b/public/index.html @@ -70,6 +70,16 @@
+