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(core): session-memory RPC, booted by both shells

enesfa913ec58cec
diff --git a/src/core/session-memory-service.test.ts b/src/core/session-memory-service.test.ts
new file mode 100644
index 000000000..3d0886758
--- /dev/null
+++ b/src/core/session-memory-service.test.ts
@@ -0,0 +1,127 @@
+// What the RPC surface DECIDES: which machine a query is answered from. The sweeps themselves are
+// covered by session-memory.test.ts / session-memory-remote.test.ts — here the only question is
+// routing, and the only dangerous answer is attributing one host's memory to another.
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { IPC } from '../shared/ipc'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { startSessionMemoryService } from './session-memory-service'
+import type { MemInfo, SessionMemoryReport, SessionMemoryQuery } from '../shared/types'
+
+// The repo's own platform fake (src/core/platform-fake.ts) — a plain recording object whose
+// `handlers` map holds whatever the service registered. Same setup as usage-service.remote.test.ts.
+let platform: FakePlatform
+
+const read = (q: SessionMemoryQuery): Promise<SessionMemoryReport> =>
+ platform.handlers[IPC.sessionMemory](q) as Promise<SessionMemoryReport>
+const host = (q: SessionMemoryQuery): Promise<MemInfo | null> =>
+ platform.handlers[IPC.sessionMemoryHost](q) as Promise<MemInfo | null>
+
+/** A remote reply the parser accepts: all three markers, in order, with one process row. */
+const OK_REPLY = '##MEM\n##PANES\n##PROCS\n100 1 1024\n'
+
+beforeEach(() => {
+ resetPlatformForTests()
+ platform = fakePlatform()
+ initPlatform(platform)
+})
+
+afterEach(() => resetPlatformForTests())
+
+describe('startSessionMemoryService', () => {
+ it('routes a LOCAL project to the local sweep', async () => {
+ const run = vi.fn()
+ startSessionMemoryService({
+ // The local sweep short-circuits to ok:false with no tmux binary, which is enough to prove
+ // routing without touching the host's real tmux.
+ tmuxBin: () => null,
+ remote: { run, isRemoteProject: () => false }
+ })
+ const r = await read({ projectId: 'p1' })
+ expect(run).not.toHaveBeenCalled()
+ expect(r.ok).toBe(false)
+ })
+
+ it('routes an SSH project to the remote runner', async () => {
+ const run = vi.fn(async () => OK_REPLY)
+ startSessionMemoryService({
+ tmuxBin: () => '/usr/bin/tmux',
+ remote: { run, isRemoteProject: (id) => id === 'ssh1' }
+ })
+ const r = await read({ projectId: 'ssh1' })
+ expect(run).toHaveBeenCalledOnce()
+ expect(r.ok).toBe(true)
+ })
+
+ it('answers ok:false for an SSH project when no remote deps were injected', async () => {
+ // The Server Edition case: no ControlMaster to run on. It must not silently answer with the
+ // LOCAL machine's sessions, which belong to a different host entirely.
+ //
+ // `readMem` is the mutation detector: a local sweep always reads it, a refusal never does. The
+ // ok/rows assertions alone would survive the guard's deletion on a host whose tmux happens to
+ // be missing (every socket errors ⇒ ok:false either way) — a green test proving nothing.
+ const readMem = vi.fn(() => ({ availableMb: 11, totalMb: 22 }))
+ startSessionMemoryService({ tmuxBin: () => '/usr/bin/tmux', readMem })
+ const r = await read({ projectId: 'ssh1', remote: true })
+ expect(r.ok).toBe(false)
+ expect(r.rows).toEqual([])
+ expect(r.mem).toBeNull()
+ expect(readMem).not.toHaveBeenCalled()
+ })
+
+ it('refuses a remote:true query the shell does not recognise as remote', async () => {
+ // The two sources disagree — the renderer says SSH, the manager has no such project (not yet
+ // connected, or already gone). Trusting the manager here would sweep THIS machine and label
+ // the rows as the host's. The claim of remoteness is what decides; only its ANSWER is doubted.
+ const run = vi.fn(async () => null)
+ startSessionMemoryService({
+ tmuxBin: () => '/usr/bin/tmux',
+ remote: { run, isRemoteProject: () => false }
+ })
+ const r = await read({ projectId: 'ssh1', remote: true })
+ expect(run).toHaveBeenCalledOnce()
+ expect(r.ok).toBe(false)
+ expect(r.rows).toEqual([])
+ })
+
+ it('never runs the local sweep for a remote scope with no projectId', async () => {
+ // `remote: true` with nothing to run against is still not an invitation to read this machine.
+ const readMem = vi.fn(() => ({ availableMb: 1, totalMb: 2 }))
+ const run = vi.fn()
+ startSessionMemoryService({
+ tmuxBin: () => '/usr/bin/tmux',
+ readMem,
+ remote: { run, isRemoteProject: () => true }
+ })
+ const r = await read({ remote: true })
+ expect(run).not.toHaveBeenCalled()
+ expect(r).toEqual({ ok: false, rows: [], mem: null })
+ // Not even the local RAM number: it describes the wrong machine.
+ expect(readMem).not.toHaveBeenCalled()
+ })
+
+ it('reads the local RAM for a local scope and the host RAM for a remote one', async () => {
+ const readMem = vi.fn(() => ({ availableMb: 11, totalMb: 22 }))
+ const run = vi.fn(async () => ['##MEM', 'MemAvailable: 2097152 kB', 'MemTotal: 4194304 kB', '##PANES', '##PROCS', '100 1 1024'].join('\n'))
+ startSessionMemoryService({
+ tmuxBin: () => '/usr/bin/tmux',
+ readMem,
+ remote: { run, isRemoteProject: (id) => id === 'ssh1' }
+ })
+ expect(await host({ projectId: 'p1' })).toEqual({ availableMb: 11, totalMb: 22 })
+ expect(await host({ projectId: 'ssh1' })).toEqual({ availableMb: 2048, totalMb: 4096 })
+ })
+
+ it('answers a null host RAM for an SSH scope with no remote deps', async () => {
+ const readMem = vi.fn(() => ({ availableMb: 11, totalMb: 22 }))
+ startSessionMemoryService({ tmuxBin: () => '/usr/bin/tmux', readMem })
+ expect(await host({ projectId: 'ssh1', remote: true })).toBeNull()
+ expect(readMem).not.toHaveBeenCalled()
+ })
+
+ it('tolerates a query-less call (a bare read is this machine)', async () => {
+ startSessionMemoryService({ tmuxBin: () => null })
+ const r = await (platform.handlers[IPC.sessionMemory]() as Promise<SessionMemoryReport>)
+ expect(r.ok).toBe(false)
+ })
+})
diff --git a/src/core/session-memory-service.ts b/src/core/session-memory-service.ts
new file mode 100644
index 000000000..14328aed8
--- /dev/null
+++ b/src/core/session-memory-service.ts
@@ -0,0 +1,68 @@
+// RPC surface for session memory. Registered by BOTH shells (src/main and src/server) exactly as
+// the usage service is: core owns the reading and the parsing, the shell injects the ControlMaster.
+//
+// The one decision made here is WHICH MACHINE answers. Everything else is delegated:
+// `collectSessionMemory` for this host, `fetchRemoteSessionMemory` for an SSH project's host.
+
+import { IPC } from '../shared/ipc'
+import { platform } from './platform'
+import type { MemInfo, SessionMemoryQuery, SessionMemoryReport } from '../shared/types'
+import { collectSessionMemory, readMemInfo } from './session-memory'
+import { fetchRemoteSessionMemory, type RemoteSessionMemoryRunner } from './session-memory-remote'
+
+export interface SessionMemoryServiceOptions {
+ /** Lazy tmux resolver (PtyManager resolves after init; null = tmux unavailable). */
+ tmuxBin: () => string | null
+ /** Host RAM reader, injectable for tests. Defaults to the real `/proc/meminfo` read. */
+ readMem?: () => MemInfo | null
+ /** Absent ⇒ SSH scopes answer `ok:false` — see the handler. */
+ remote?: {
+ run: RemoteSessionMemoryRunner
+ isRemoteProject: (projectId: string) => boolean
+ }
+}
+
+const EMPTY = (mem: MemInfo | null): SessionMemoryReport => ({ ok: false, rows: [], mem })
+
+export function startSessionMemoryService(opts: SessionMemoryServiceOptions): { dispose(): void } {
+ /**
+ * Two independent sources say "this scope is remote", and EITHER is enough:
+ * - the renderer's own `remote` flag (it already knows from `usageScope` which project is an
+ * SSH one), and
+ * - the shell's project manager.
+ * They are OR-ed, not AND-ed, on purpose. A manager that has not (yet) registered a project as
+ * connected — reconnecting, just dropped — would otherwise turn a remote query into a LOCAL
+ * sweep, and the panel would label this machine's sessions as the host's. A claim of remoteness
+ * is trusted; only its answer can fail.
+ */
+ const isRemote = (q: SessionMemoryQuery): boolean =>
+ q.remote === true || (!!q.projectId && !!opts.remote?.isRemoteProject(q.projectId))
+
+ platform().handle(
+ IPC.sessionMemory,
+ async (q: SessionMemoryQuery = {}): Promise<SessionMemoryReport> => {
+ if (isRemote(q)) {
+ // No ControlMaster injected (Server Edition), or nothing to run against: answering with
+ // the LOCAL machine's sessions would attribute one host's memory to another. Refuse — and
+ // with a null `mem` too, since even the RAM number would describe the wrong machine.
+ if (!opts.remote || !q.projectId) return EMPTY(null)
+ return fetchRemoteSessionMemory(q.projectId, opts.remote.run)
+ }
+ return collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem })
+ }
+ )
+
+ platform().handle(
+ IPC.sessionMemoryHost,
+ async (q: SessionMemoryQuery = {}): Promise<MemInfo | null> => {
+ if (!isRemote(q)) return (opts.readMem ?? readMemInfo)()
+ if (!opts.remote || !q.projectId) return null
+ // One round trip serves both numbers; the pill uses only `mem`.
+ return (await fetchRemoteSessionMemory(q.projectId, opts.remote.run)).mem
+ }
+ )
+
+ // Nothing to tear down: both handlers are pull-only, with no timer and no cache. `dispose` exists
+ // so a shell can treat this like the other services it starts.
+ return { dispose: (): void => {} }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 8091e78d7..325117db0 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -69,6 +69,7 @@ import { createGrantsAccessor, type PushGrant } from '../core/push-grants'
import { createRemoteGrantsCache } from '../core/remote-push-grants'
import { createAckSweeper } from '../core/ack-sweep'
import { createSessionReaper } from '../core/session-budget'
+import { startSessionMemoryService } from '../core/session-memory-service'
import { getDeviceId } from '../core/device-id'
import { initRemoteStatusPush } from './remote-ssh/remote-status-push'
import { initCanvasSync } from '../core/canvas-sync'
@@ -1501,6 +1502,37 @@ app.whenReady().then(async () => {
// Local sockets only — a remote SSH host's sessions are reaped by that host's own
// nodeterm-server, never across the wire. Timer is unref'd; no explicit stop needed.
createSessionReaper({ tmuxBin: () => ptyManager.getTmuxBin() }).start()
+ // Session memory (docs/superpowers/specs/2026-08-10-session-memory-panel-design.md): the pill's
+ // cheap RAM read plus the on-demand per-session breakdown. An SSH project's sessions live on ITS
+ // host, so they are read THERE over the project's ControlMaster — the same injection Context Link
+ // and remote usage use (core owns the command + the parsing, main owns the master).
+ // `sshProjectManager` is assigned far below, so both closures resolve it lazily; they only ever
+ // run after a project has connected.
+ startSessionMemoryService({
+ tmuxBin: () => ptyManager.getTmuxBin(),
+ remote: {
+ isRemoteProject: (projectId) =>
+ (sshProjectManager?.connectedHosts() ?? []).some((h) => h.projectId === projectId),
+ run: async (projectId, command) => {
+ const mgr = sshProjectManager
+ const ref = mgr?.refForProject(projectId)
+ if (!mgr || !ref) return null
+ try {
+ const { code, stdout } = await mgr.sshRun(childArgs(ref.conn, ref.controlPath, command))
+ // Gated on the exit code, unlike the usage runner: every command in the generated script
+ // ends `|| true`, so a completed read exits 0 unconditionally. A non-zero code therefore
+ // means ssh itself could not run it — a dead ControlMaster reports exactly that, with an
+ // EMPTY stdout ("Control socket connect(…): No such file or directory" goes to stderr).
+ // Passing that empty string on would leave "the host answered nothing" to be inferred
+ // from a missing marker; `null` says "we could not look" outright.
+ if (code !== 0) return null
+ return stdout
+ } catch {
+ return null
+ }
+ }
+ }
+ })
const ackSweeper = createAckSweeper({
handlers: { ackDone, onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id) }
})
diff --git a/src/server/index.ts b/src/server/index.ts
index fd950867e..79772b051 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -50,6 +50,7 @@ import { createPushNotify, createLiveUpdatePush } from '../core/push-notify'
import { createGrantsAccessor } from '../core/push-grants'
import { createAckSweeper } from '../core/ack-sweep'
import { createSessionReaper } from '../core/session-budget'
+import { startSessionMemoryService } from '../core/session-memory-service'
import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'
import { claudeConfigDirFor } from '../core/claude-config-dir'
import { presenceHub } from '../core/presence/hub'
@@ -443,6 +444,13 @@ export async function startServer(
const sessionReaper = createSessionReaper({ tmuxBin: () => ptyManager.getTmuxBin() })
sessionReaper.start()
+ // Session memory: the pill's RAM read plus the on-demand per-session breakdown. No remote deps —
+ // the Server Edition runs ON the host whose sessions it reports and has no SSH-project manager.
+ // An SSH scope therefore answers ok:false rather than mis-attributing this machine's sessions to
+ // another host. Registered here (not in handlers/index.ts) because this is where `ptyManager`
+ // lives — the same call site as the reaper above, mirroring src/main/index.ts.
+ startSessionMemoryService({ tmuxBin: () => ptyManager.getTmuxBin() })
+
// Headless notification host: every core service above (incl. the loopback hook server, which
// is its own listener and MUST run) is booted, but we bind NO public HTTP/WS listener — no
// renderer serving, no auth surface, no open port. The granted push senders reach the phone over
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 2f0912fec..76f18bf3c 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -115,6 +115,13 @@ export const IPC = {
usageSetProviderCookie: 'usage:set-provider-cookie',
/** Which cookie providers have one stored — lets the UI show state without handling secrets. */
usageCookieProviders: 'usage:cookie-providers',
+ /** Per-session memory breakdown for the scoped machine. On demand only — never polled: the
+ * local sweep walks the whole process table, and the SSH one is an exec on someone else's
+ * host. */
+ sessionMemory: 'session-memory:read',
+ /** The scoped machine's RAM (available/total) — the cheap read behind the system-resource
+ * pill. Safe to poll locally; NOT polled for an SSH scope. */
+ sessionMemoryHost: 'session-memory:host',
contextUpdate: 'context:update',
contextEnsure: 'context:ensure',
// Team presence (docs/team-presence.md). `presence:hello` is a REQUEST: its response tells the
diff --git a/src/shared/types.ts b/src/shared/types.ts
index d9034d55e..bb06f1661 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1488,6 +1488,18 @@ export interface SessionMemoryReport {
mem: MemInfo | null
}
+/**
+ * What the renderer asks for: the machine a project runs ON, never "this machine" implicitly.
+ * `remote: true` is the renderer saying it already knows (from `usageScope`) that the active
+ * project is an SSH one; the shell's own `isRemoteProject` is a second, independent confirmation,
+ * so a project the shell has not (yet) registered as connected still cannot be answered with the
+ * local machine's sessions.
+ */
+export interface SessionMemoryQuery {
+ projectId?: string
+ remote?: boolean
+}
+
/** Claude Code subscription usage snapshot for the bottom-left indicator. */
export interface ClaudeUsage {
/**