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(windows): session-memory panel measures session-host sessions

reviewba2613cac5c5
diff --git a/src/core/session-memory-service.test.ts b/src/core/session-memory-service.test.ts
index e479da37a..733cf322a 100644
--- a/src/core/session-memory-service.test.ts
+++ b/src/core/session-memory-service.test.ts
@@ -5,7 +5,7 @@ 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, sshScopePredicate } from './session-memory-service'
+import { mergeLocalLegs, startSessionMemoryService, sshScopePredicate } 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
@@ -291,3 +291,96 @@ describe('startSessionMemoryService', () => {
expect(r.ok).toBe(false)
})
})
+
+describe('startSessionMemoryService — session-host leg (Windows)', () => {
+ const MEM = { availableMb: 8000, totalMb: 16000 }
+ const listing = {
+ running: true,
+ names: ['nt-a'],
+ sessions: [{ name: 'nt-a', pid: 100, subscribers: 0, lastOutputMs: 1, createdMs: 1, generation: 'gen-aaaaaaaa' }]
+ }
+ const table = async () => [{ pid: 100, ppid: 1, rssKb: 2048 }]
+
+ it('no tmux + a session host answers ok:true with its rows (was always ok:false)', async () => {
+ startSessionMemoryService({
+ tmuxBin: () => null,
+ readMem: () => MEM,
+ sessionHost: async () => listing,
+ sessionHostTable: table
+ })
+ const r = await read({ projectId: 'p1' })
+ expect(r.ok).toBe(true)
+ expect(r.rows.map((x) => [x.session, x.totalMb])).toEqual([['nt-a', 2]])
+ })
+
+ it('no host running is "no sessions", not a failure', async () => {
+ startSessionMemoryService({
+ tmuxBin: () => null,
+ readMem: () => MEM,
+ sessionHost: async () => ({ running: false, names: [], sessions: [] })
+ })
+ expect(await read({ projectId: 'p1' })).toEqual({ ok: true, rows: [], mem: MEM })
+ })
+
+ it('a session host that is not the backend (undefined) leaves the tmux path untouched', async () => {
+ startSessionMemoryService({ tmuxBin: () => null, readMem: () => MEM, sessionHost: () => undefined })
+ expect(await read({ projectId: 'p1' })).toEqual({ ok: false, rows: [], mem: MEM })
+ })
+
+ it('a failed host read is ok:false', async () => {
+ startSessionMemoryService({ tmuxBin: () => null, readMem: () => MEM, sessionHost: async () => null })
+ expect((await read({ projectId: 'p1' })).ok).toBe(false)
+ })
+
+ it('a Zellij count rides on top and drops the session-host label', async () => {
+ startSessionMemoryService({
+ tmuxBin: () => null,
+ readMem: () => MEM,
+ unmeasuredSessions: async () => 2,
+ sessionHost: async () => ({ ...listing, sessions: null })
+ })
+ const r = await read({ projectId: 'p1' })
+ expect(r.unmeasured).toBe(3)
+ expect(r).not.toHaveProperty('unmeasuredBackend')
+ })
+
+ it('an SSH scope never reaches the session host', async () => {
+ const sessionHost = vi.fn(async () => listing)
+ startSessionMemoryService({ tmuxBin: () => null, sessionHost, remote: { isRemoteProject: () => true } })
+ expect((await read({ projectId: 'ssh1', remote: true })).ok).toBe(false)
+ expect(sessionHost).not.toHaveBeenCalled()
+ })
+})
+
+describe('mergeLocalLegs', () => {
+ const r = (ok: boolean, totals: number[], extra: Partial<SessionMemoryReport> = {}): SessionMemoryReport => ({
+ ok,
+ rows: totals.map((t, i) => ({
+ session: `nt-${ok}-${i}`,
+ nodeId: `${ok}-${i}`,
+ panePid: i + 1,
+ command: '',
+ selfMb: t,
+ childrenMb: 0,
+ childCount: 0,
+ totalMb: t
+ })),
+ mem: null,
+ ...extra
+ })
+ it('a leg that answered is never overridden by one that failed', () => {
+ expect(mergeLocalLegs(r(false, []), r(true, [5])).ok).toBe(true)
+ expect(mergeLocalLegs(r(true, [5]), r(false, [])).ok).toBe(true)
+ expect(mergeLocalLegs(r(false, []), r(false, [])).ok).toBe(false)
+ })
+ it('rows from both legs, sorted by total descending', () => {
+ expect(mergeLocalLegs(r(true, [3, 1]), r(true, [2])).rows.map((x) => x.totalMb)).toEqual([3, 2, 1])
+ })
+ it('unmeasured adds up; unknown stays unknown; the label survives', () => {
+ const m = mergeLocalLegs(r(true, []), r(true, [], { unmeasured: 2, unmeasuredBackend: 'session-host' }))
+ expect(m.unmeasured).toBe(2)
+ expect(m.unmeasuredBackend).toBe('session-host')
+ expect(mergeLocalLegs(r(true, [], { unmeasured: null }), r(true, [], { unmeasured: 1 })).unmeasured).toBeNull()
+ expect(mergeLocalLegs(r(true, []), r(true, []))).not.toHaveProperty('unmeasured')
+ })
+})
diff --git a/src/core/session-memory-service.ts b/src/core/session-memory-service.ts
index bd1fc5866..abec30038 100644
--- a/src/core/session-memory-service.ts
+++ b/src/core/session-memory-service.ts
@@ -7,7 +7,8 @@
import { IPC } from '../shared/ipc'
import { platform } from './platform'
import type { MemInfo, SessionMemoryQuery, SessionMemoryReport } from '../shared/types'
-import { collectSessionMemory, readMemInfo } from './session-memory'
+import { collectSessionHostMemory, collectSessionMemory, readMemInfo, type ProcEntry } from './session-memory'
+import type { SessionHostListing } from './session-host-client'
import { fetchRemoteSessionMemory, type RemoteSessionMemoryRunner } from './session-memory-remote'
export interface SessionMemoryServiceOptions {
@@ -15,6 +16,15 @@ export interface SessionMemoryServiceOptions {
tmuxBin: () => string | null
/** Live local sessions the tmux sweep cannot measure (Zellij-backed; PtyManager answers). */
unmeasuredSessions?: () => Promise<number | null>
+ /**
+ * The session host's listing (`PtyManager.sessionHostListing()`), answering `undefined` when the
+ * session host is not this machine's backend — then nothing below changes. When it IS (Windows),
+ * its sessions are measured by `collectSessionHostMemory`; see `mergeLocalLegs` for how that leg
+ * and the tmux one combine.
+ */
+ sessionHost?: () => Promise<SessionHostListing | null> | undefined
+ /** Process-table override for the session-host leg (tests). */
+ sessionHostTable?: () => Promise<ProcEntry[] | null>
/** Host RAM reader, injectable for tests. Defaults to the real `/proc/meminfo` read. */
readMem?: () => MemInfo | null
/**
@@ -65,6 +75,26 @@ export function sshScopePredicate(sources: SshScopeSources): (projectId: string)
const EMPTY = (): SessionMemoryReport => ({ ok: false, rows: [], mem: null })
+/**
+ * Combine this machine's two sweeps (tmux and the session host). A leg that ANSWERED is never
+ * overridden by one that failed: `ok` is false only when neither answered, because then nobody
+ * looked. Rows are concatenated and re-sorted by total, the order every single leg already uses.
+ * A failed leg's sessions are invisible to the merged report, which is the same honest gap a
+ * single failed tmux socket already leaves.
+ */
+export function mergeLocalLegs(a: SessionMemoryReport, b: SessionMemoryReport): SessionMemoryReport {
+ if (!a.ok && !b.ok) return { ok: false, rows: [], mem: a.mem ?? b.mem }
+ const answered = [a, b].filter((r) => r.ok)
+ const rows = answered.flatMap((r) => r.rows).sort((x, y) => y.totalMb - x.totalMb)
+ const out: SessionMemoryReport = { ok: true, rows, mem: a.mem ?? b.mem }
+ const counts = answered.map((r) => (r.unmeasured === undefined ? 0 : r.unmeasured))
+ const unmeasured = counts.some((n) => n === null) ? null : (counts as number[]).reduce((x, y) => x + y, 0)
+ if (unmeasured !== 0) out.unmeasured = unmeasured
+ const backend = answered.find((r) => r.unmeasuredBackend)?.unmeasuredBackend
+ if (backend && unmeasured !== 0) out.unmeasuredBackend = backend
+ return out
+}
+
export function startSessionMemoryService(opts: SessionMemoryServiceOptions): { dispose(): void } {
/**
* Two independent sources say "this scope is remote", and EITHER is enough:
@@ -101,6 +131,24 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {
return p
}
+ /** The session-host leg, plus the tmux leg only when a tmux binary also exists (a no-tmux
+ * machine's tmux sweep is a guaranteed `ok:false` that must not be what the panel reports). */
+ const collectLocalWithSessionHost = async (
+ listing: Promise<SessionHostListing | null>
+ ): Promise<SessionMemoryReport> => {
+ const hostLeg = collectSessionHostMemory({
+ list: () => listing,
+ readMem: opts.readMem,
+ ...(opts.sessionHostTable ? { readTable: opts.sessionHostTable } : {})
+ })
+ if (!opts.tmuxBin()) return hostLeg
+ const [tmuxLeg, host] = await Promise.all([
+ collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem }),
+ hostLeg
+ ])
+ return mergeLocalLegs(tmuxLeg, host)
+ }
+
platform().handle(
IPC.sessionMemory,
async (q: SessionMemoryQuery = {}): Promise<SessionMemoryReport> => {
@@ -112,11 +160,17 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {
if (!run || !q.projectId) return EMPTY()
return readRemote(q.projectId, run)
}
+ const hostListing = opts.sessionHost?.()
const [report, unmeasured] = await Promise.all([
- collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem }),
+ hostListing === undefined
+ ? collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem })
+ : collectLocalWithSessionHost(hostListing),
opts.unmeasuredSessions ? opts.unmeasuredSessions().catch(() => null) : Promise.resolve(0)
])
- return unmeasured === 0 ? report : { ...report, unmeasured }
+ if (unmeasured === 0) return report
+ // Zellij sessions are now part of the count, so a session-host-only label would misname them.
+ const { unmeasuredBackend: _label, ...rest } = report
+ return { ...rest, unmeasured: addUnmeasured(report.unmeasured, unmeasured) }
}
)
@@ -136,3 +190,9 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {
// starts.
return { dispose: (): void => {} }
}
+
+/** Zellij's count on top of whatever a leg already reported unmeasured; unknown stays unknown. */
+function addUnmeasured(already: number | null | undefined, zellij: number | null): number | null {
+ if (zellij === null || already === null) return null
+ return (already ?? 0) + zellij
+}
diff --git a/src/core/session-memory-session-host.test.ts b/src/core/session-memory-session-host.test.ts
new file mode 100644
index 000000000..618381bf6
--- /dev/null
+++ b/src/core/session-memory-session-host.test.ts
@@ -0,0 +1,176 @@
+// The session-host leg of the session-memory sweep (Windows parity) and its Windows process table.
+// Runs on every CI host: the platform and the process table are injected, never read.
+import { describe, it, expect } from 'vitest'
+import {
+ collectSessionHostMemory,
+ parseWin32ProcessTable,
+ win32ProcessTable,
+ WIN32_PROCESS_TABLE_SCRIPT,
+ type ProcEntry
+} from './session-memory'
+import { cimRows, powershellArgs, POWERSHELL_EXE } from './win32-powershell'
+import type { SessionHostListing } from './session-host-client'
+import { sessionName } from './tmux-naming'
+
+const P = (pid: number, ppid: number, rssKb: number): ProcEntry => ({ pid, ppid, rssKb })
+const MEM = { availableMb: 8000, totalMb: 16000 }
+const row = (name: string, pid: number) => ({
+ name,
+ pid,
+ subscribers: 0,
+ lastOutputMs: 1,
+ createdMs: 1,
+ generation: 'gen-aaaaaaaa'
+})
+
+describe('cimRows (ConvertTo-Json shapes)', () => {
+ it('accepts an array, a bare object (one-element pipeline) and nothing (empty pipeline)', () => {
+ expect(cimRows('[{"a":1},{"a":2}]')).toEqual([{ a: 1 }, { a: 2 }])
+ expect(cimRows('{"a":1}\r\n')).toEqual([{ a: 1 }])
+ expect(cimRows(' \r\n')).toEqual([])
+ })
+ it('anything else is unreadable (null), never "no rows"', () => {
+ expect(cimRows('[{"a":1},')).toBeNull()
+ expect(cimRows('42')).toBeNull()
+ expect(cimRows('[1,2]')).toBeNull()
+ expect(cimRows('WARNING: something')).toBeNull()
+ })
+ it('argv is the unattended, profile-free form with the script as ONE element', () => {
+ expect(powershellArgs('x | y')).toEqual(['-NoProfile', '-NonInteractive', '-Command', 'x | y'])
+ })
+})
+
+describe('parseWin32ProcessTable', () => {
+ it('maps CIM rows to pid/ppid/kB, working set in BYTES', () => {
+ const json = JSON.stringify([
+ { ProcessId: 4000, ParentProcessId: 900, WorkingSetSize: 10 * 1024 * 1024 },
+ { ProcessId: 4100, ParentProcessId: 4000, WorkingSetSize: 2048 }
+ ])
+ expect(parseWin32ProcessTable(json)).toEqual([P(4000, 900, 10 * 1024), P(4100, 4000, 2)])
+ })
+ it('accepts a single object; a missing working set is 0, not a dropped process', () => {
+ expect(parseWin32ProcessTable('{"ProcessId":7,"ParentProcessId":1,"WorkingSetSize":null}')).toEqual([P(7, 1, 0)])
+ })
+ it('skips rows without numeric ids; bad JSON or an empty table is null', () => {
+ expect(parseWin32ProcessTable('[{"ProcessId":"x","ParentProcessId":1},{"ProcessId":2,"ParentProcessId":1}]')).toEqual([
+ P(2, 1, 0)
+ ])
+ expect(parseWin32ProcessTable('not json')).toBeNull()
+ expect(parseWin32ProcessTable('')).toBeNull()
+ })
+ it('the reader goes through the exec seam with the fixed script, and a failed exec is null', async () => {
+ const calls: Array<{ bin: string; args: string[] }> = []
+ const table = await win32ProcessTable(async (bin, args) => {
+ calls.push({ bin, args })
+ return '{"ProcessId":7,"ParentProcessId":1,"WorkingSetSize":1024}'
+ })
+ expect(table).toEqual([P(7, 1, 1)])
+ expect(calls).toEqual([{ bin: POWERSHELL_EXE, args: powershellArgs(WIN32_PROCESS_TABLE_SCRIPT) }])
+ await expect(
+ win32ProcessTable(async () => {
+ throw new Error('exit 1')
+ })
+ ).resolves.toBeNull()
+ })
+})
+
+describe('collectSessionHostMemory', () => {
+ const listing = (over: Partial<SessionHostListing> = {}): SessionHostListing => ({
+ running: true,
+ names: ['nt-a', 'nt-b'],
+ sessions: [row('nt-a', 100), row('nt-b', 200)],
+ ...over
+ })
+ const table = [P(100, 1, 1024), P(101, 100, 300 * 1024), P(200, 1, 2048), P(999, 1, 5000)]
+
+ it('rolls each session\'s pty pid up through its tree, sorted by total', async () => {
+ const r = await collectSessionHostMemory({
+ list: async () => listing(),
+ readTable: async () => table,
+ readMem: () => MEM
+ })
+ expect(r.ok).toBe(true)
+ expect(r.mem).toEqual(MEM)
+ expect(r.unmeasured).toBeUndefined()
+ expect(r.rows.map((x) => [x.session, x.nodeId, x.panePid, x.totalMb, x.childCount])).toEqual([
+ ['nt-a', 'a', 100, 301, 1],
+ ['nt-b', 'b', 200, 2, 0]
+ ])
+ })
+
+ it('the Windows table is read through PowerShell when the platform is win32', async () => {
+ const bins: string[] = []
+ const r = await collectSessionHostMemory({
+ list: async () => listing({ names: ['nt-a'], sessions: [row('nt-a', 100)] }),
+ readMem: () => MEM,
+ platformName: 'win32',
+ exec: async (bin) => {
+ bins.push(bin)
+ return JSON.stringify([{ ProcessId: 100, ParentProcessId: 1, WorkingSetSize: 4 * 1024 * 1024 }])
+ }
+ })
+ expect(bins).toEqual([POWERSHELL_EXE])
+ expect(r.rows[0]).toMatchObject({ session: 'nt-a', totalMb: 4 })
+ })
+
+ it('a failed host read is ok:false, and so is an unreadable process table', async () => {
+ expect(await collectSessionHostMemory({ list: async () => null, readMem: () => MEM })).toEqual({
+ ok: false,
+ rows: [],
+ mem: MEM
+ })
+ const threw = await collectSessionHostMemory({
+ list: async () => {
+ throw new Error('pipe gone')
+ },
+ readMem: () => MEM
+ })
+ expect(threw.ok).toBe(false)
+ const noTable = await collectSessionHostMemory({ list: async () => listing(), readTable: async () => null, readMem: () => MEM })
+ expect(noTable).toEqual({ ok: false, rows: [], mem: MEM })
+ })
+
+ it('no host running is an ANSWER (ok, no rows) and reads no process table', async () => {
+ let read = 0
+ const r = await collectSessionHostMemory({
+ list: async () => ({ running: false, names: [], sessions: [] }),
+ readTable: async () => {
+ read++
+ return table
+ },
+ readMem: () => MEM
+ })
+ expect(r).toEqual({ ok: true, rows: [], mem: MEM })
+ expect(read).toBe(0)
+ })
+
+ it('an older host (names only) reports every nt- session as unmeasured, never "no sessions"', async () => {
+ const r = await collectSessionHostMemory({
+ list: async () => listing({ names: ['nt-a', 'nt-b', 'other'], sessions: null }),
+ readTable: async () => table,
+ readMem: () => MEM
+ })
+ expect(r).toEqual({ ok: true, rows: [], mem: MEM, unmeasured: 2, unmeasuredBackend: 'session-host' })
+ })
+
+ it('a named session without a row is unmeasured beside the measured ones', async () => {
+ const r = await collectSessionHostMemory({
+ list: async () => listing({ sessions: [row('nt-a', 100)] }),
+ readTable: async () => table,
+ readMem: () => MEM
+ })
+ expect(r.rows.map((x) => x.session)).toEqual(['nt-a'])
+ expect(r.unmeasured).toBe(1)
+ expect(r.unmeasuredBackend).toBe('session-host')
+ })
+
+ it('a row whose session name maps back to its node id (the kill round trip)', async () => {
+ const r = await collectSessionHostMemory({
+ list: async () => listing({ names: ['nt-node-1'], sessions: [row('nt-node-1', 100)] }),
+ readTable: async () => table,
+ readMem: () => MEM
+ })
+ // The panel's × kills `transport.destroy(nodeId)`, which re-derives the name via sessionName().
+ expect(sessionName(r.rows[0].nodeId)).toBe('nt-node-1')
+ })
+})
diff --git a/src/core/session-memory.ts b/src/core/session-memory.ts
index a3da96708..197383110 100644
--- a/src/core/session-memory.ts
+++ b/src/core/session-memory.ts
@@ -15,6 +15,8 @@ import { promisify } from 'util'
import type { MemInfo, SessionMemoryRow, SessionMemoryReport } from '../shared/types'
import { TMUX_SOCKET } from './tmux-naming'
import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'
+import type { SessionHostListing } from './session-host-client'
+import { cimRows, powershellArgs, POWERSHELL_EXE } from './win32-powershell'
export type { MemInfo, SessionMemoryRow, SessionMemoryReport }
@@ -438,6 +440,138 @@ export function isNoServerError(message: string): boolean {
return /no server running|error connecting to [^\n]*\(no such file or directory\)/i.test(message)
}
+/**
+ * Non-Linux (or an unreadable /proc): `ps` for the whole table, through the injectable exec seam —
+ * nothing in this file may reach a subprocess around it. Null when it could not run.
+ *
+ * On darwin a SECOND call is merged in: `top` carries phys_footprint, which is what Activity
+ * Monitor shows and what the pill's `vm_stat` reading already counts. `ps`'s own `rss` drops an
+ * idle process's compressed pages and understated a six-hour-idle session by about half — exactly
+ * the population this panel exists to describe. See parseTopFootprint.
+ */
+async function psProcessTable(
+ exec: (bin: string, args: string[]) => Promise<string>,
+ platformName: NodeJS.Platform
+): Promise<ProcEntry[] | null> {
+ try {
+ const rows = parseProcessTable(await exec('ps', ['-eo', 'pid,ppid,rss']))
+ if (platformName !== 'darwin') return rows
+ const fp = parseTopFootprint(await exec('top', ['-l', '1', '-stats', 'pid,mem']))
+ // A pid `top` did not list keeps its `rss`. The two snapshots are a moment apart, so a miss is
+ // a process that came or went between them — not a reason to report nothing.
+ return rows.map((e) => ({ ...e, rssKb: fp.get(e.pid) ?? e.rssKb }))
+ } catch {
+ return null
+ }
+}
+
+/** The PowerShell the Windows table comes from: one CIM query, compressed JSON on one line. */
+export const WIN32_PROCESS_TABLE_SCRIPT =
+ 'Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,WorkingSetSize | ConvertTo-Json -Compress'
+
+/**
+ * Parse `WIN32_PROCESS_TABLE_SCRIPT`'s output. `ConvertTo-Json` prints a bare OBJECT for a
+ * one-element pipeline and an array otherwise; both are accepted. `WorkingSetSize` is BYTES — the
+ * Windows counterpart of RSS (resident pages, shared ones included), and what Task Manager's
+ * "Working set" column shows. Rows without a numeric pid/ppid are skipped; a missing working set
+ * reads as 0 rather than dropping the process, so the tree walk still reaches its children.
+ * Unparseable JSON, or a table with no process at all (a machine always has some), is null.
+ */
+export function parseWin32ProcessTable(json: string): ProcEntry[] | null {
+ const rows = cimRows(json)
+ if (rows === null) return null
+ const out: ProcEntry[] = []
+ for (const r of rows) {
+ const pid = Number(r.ProcessId)
+ const ppid = Number(r.ParentProcessId)
+ if (!Number.isSafeInteger(pid) || !Number.isSafeInteger(ppid)) continue
+ const bytes = Number(r.WorkingSetSize)
+ out.push({ pid, ppid, rssKb: Number.isFinite(bytes) && bytes > 0 ? bytes / 1024 : 0 })
+ }
+ return out.length > 0 ? out : null
+}
+
+/** The Windows process table through the exec seam, or null when PowerShell could not answer. */
+export async function win32ProcessTable(
+ exec: (bin: string, args: string[]) => Promise<string>
+): Promise<ProcEntry[] | null> {
+ try {
+ return parseWin32ProcessTable(await exec(POWERSHELL_EXE, powershellArgs(WIN32_PROCESS_TABLE_SCRIPT)))
+ } catch {
+ return null
+ }
+}
+
+export interface SessionHostMemoryDeps {
+ /** The host's listing (`PtyManager.sessionHostListing()`); null = the read failed. */
+ list: () => Promise<SessionHostListing | null>
+ /** Process-table override for tests. Default: by platform (CIM on Windows, /proc, else ps). */
+ readTable?: () => Promise<ProcEntry[] | null>
+ readMem?: () => MemInfo | null
+ exec?: (bin: string, args: string[]) => Promise<string>
+ platformName?: NodeJS.Platform
+}
+
+/**
+ * The session-host leg of the sweep: the host names each session and its pty's pid (the pane's
+ * shell — `PaneRef.panePid`), and the same `buildReport`/`rollupTree` then do what they do for
+ * tmux. Failure rules, mirroring the tmux leg:
+ * - a failed host read, or an unreadable process table → `ok: false`, no rows;
+ * - no host running → `ok: true` with no rows — an ANSWER (there are no sessions), not a failure,
+ * and no process table is read for it;
+ * - a session the host names but does not describe (a host older than `sessionDetails`, a row
+ * dropped as malformed) is counted in `unmeasured` — never silently dropped, so the panel cannot
+ * say "no sessions" over live ones.
+ */
+export async function collectSessionHostMemory(deps: SessionHostMemoryDeps): Promise<SessionMemoryReport> {
+ const mem = (deps.readMem ?? readMemInfo)()
+ let listing: SessionHostListing | null
+ try {
+ listing = await deps.list()
+ } catch {
+ listing = null
+ }
+ if (!listing) return { ok: false, rows: [], mem }
+ const ours = listing.names.filter((n) => n.startsWith('nt-'))
+ const described = new Map((listing.sessions ?? []).map((row) => [row.name, row]))
+ const panes: PaneRef[] = []
+ let unmeasured = 0
+ for (const name of ours) {
+ const row = described.get(name)
+ if (row) panes.push({ session: name, panePid: row.pid, command: '' })
+ else unmeasured++
+ }
+ const withUnmeasured = (report: SessionMemoryReport): SessionMemoryReport =>
+ unmeasured === 0 ? report : { ...report, unmeasured, unmeasuredBackend: 'session-host' }
+ if (panes.length === 0) return withUnmeasured({ ok: true, rows: [], mem })
+
+ const platformName = deps.platformName ?? process.platform
+ const exec =
+ deps.exec ??
+ (async (b: string, args: string[]): Promise<string> => {
+ const { stdout } = await runAsync(b, args, {
+ timeout: 15_000,
+ maxBuffer: 16 * 1024 * 1024,
+ windowsHide: true
+ })
+ return stdout
+ })
+ const readTable =
+ deps.readTable ??
+ (async (): Promise<ProcEntry[] | null> => {
+ if (platformName === 'win32') return win32ProcessTable(exec)
+ return defaultProcessTableReader() ?? (await psProcessTable(exec, platformName))
+ })
+ let table: ProcEntry[] | null
+ try {
+ table = await readTable()
+ } catch {
+ table = null
+ }
+ if (table === null) return { ok: false, rows: [], mem }
+ return withUnmeasured(buildReport(panes, table, mem))
+}
+
/**
* One sweep. Failure rules (CLAUDE.md: a failed read is never evidence of absence):
* - no tmux binary, or an unreadable process table → `ok: false`, no rows;
@@ -465,28 +599,7 @@ export async function collectSessionMemory(
const readTable = deps.readTable ?? defaultProcessTableReader
let table = readTable()
- if (table === null && !deps.readTable) {
- // Non-Linux (or an unreadable /proc): `ps` for the whole table, through the same injectable
- // seam as tmux — nothing in this file may reach a subprocess around it.
- //
- // On darwin a SECOND call is merged in: `top` carries phys_footprint, which is what Activity
- // Monitor shows and what the pill's `vm_stat` reading already counts. `ps`'s own `rss` drops
- // an idle process's compressed pages and understated a six-hour-idle session by about half —
- // exactly the population this panel exists to describe. See parseTopFootprint.
- try {
- const rows = parseProcessTable(await exec('ps', ['-eo', 'pid,ppid,rss']))
- if (process.platform === 'darwin') {
- const fp = parseTopFootprint(await exec('top', ['-l', '1', '-stats', 'pid,mem']))
- // A pid `top` did not list keeps its `rss`. The two snapshots are a moment apart, so a miss
- // is a process that came or went between them — not a reason to report nothing.
- table = rows.map((e) => ({ ...e, rssKb: fp.get(e.pid) ?? e.rssKb }))
- } else {
- table = rows
- }
- } catch {
- table = null
- }
- }
+ if (table === null && !deps.readTable) table = await psProcessTable(exec, process.platform)
if (table === null) return { ok: false, rows: [], mem }
const sockets = deps.sockets ?? [TMUX_SOCKET, RMT_TMUX_SOCKET]
diff --git a/src/core/win32-powershell.ts b/src/core/win32-powershell.ts
new file mode 100644
index 000000000..f5dd49971
--- /dev/null
+++ b/src/core/win32-powershell.ts
@@ -0,0 +1,36 @@
+// The one way core asks Windows a question through PowerShell (session memory's process table,
+// dev-server ports' listeners). Pure argv + parsing; the subprocess itself always runs through the
+// caller's injectable exec seam, so every consumer stays testable on any CI host.
+
+/** Windows PowerShell 5.1 ships with every supported Windows; `pwsh` is optional and not assumed. */
+export const POWERSHELL_EXE = 'powershell.exe'
+
+/**
+ * Argv for one unattended script. `-NoProfile`: a user profile can take seconds and print into the
+ * stdout we parse (the same reason session-host/process-tree.ts passes it). `-NonInteractive`: a
+ * prompt would hang until the exec timeout instead of failing. The script is ONE argv element —
+ * never a shell-interpolated string — and is a constant written in this repo, never user input.
+ */
+export function powershellArgs(script: string): string[] {
+ return ['-NoProfile', '-NonInteractive', '-Command', script]
+}
+
+/**
+ * Parse `ConvertTo-Json -Compress` output into rows. `ConvertTo-Json` prints a bare OBJECT for a
+ * one-element pipeline, an ARRAY for several, and NOTHING for an empty one, so all three are
+ * accepted (`''` → `[]`). Anything else — truncated or non-JSON text, a scalar — is `null`: a reply
+ * we cannot read is never "no rows".
+ */
+export function cimRows(text: string): Record<string, unknown>[] | null {
+ const trimmed = text.trim()
+ if (trimmed === '') return []
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(trimmed)
+ } catch {
+ return null
+ }
+ const list = Array.isArray(parsed) ? parsed : [parsed]
+ if (!list.every((r) => r !== null && typeof r === 'object' && !Array.isArray(r))) return null
+ return list as Record<string, unknown>[]
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 5f5b475bf..b830d9c83 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -3281,6 +3281,8 @@ app.whenReady().then(async () => {
tmuxBin: () => ptyManager.getTmuxBin(),
// Zellij-backed sessions are not in the tmux sweep; the panel says how many it did not measure.
unmeasuredSessions: () => ptyManager.zellijSessionCount(),
+ // Windows (no tmux): the session host's sessions; undefined where it is not the backend.
+ sessionHost: () => ptyManager.sessionHostListing(),
remote: {
// Identity, not liveness: a DISCONNECTED SSH project is still someone else's machine, and
// `connectedHosts()` alone would answer "local" for it — exactly the window the service's
diff --git a/src/renderer/components/SessionMemoryPanel.tsx b/src/renderer/components/SessionMemoryPanel.tsx
index 20817f360..9e1f5523e 100644
--- a/src/renderer/components/SessionMemoryPanel.tsx
+++ b/src/renderer/components/SessionMemoryPanel.tsx
@@ -79,6 +79,7 @@ export function SessionMemoryPanel({
const ok = useSessionMemory((s) => s.ok)
const rows = useSessionMemory((s) => s.rows)
const unmeasured = useSessionMemory((s) => s.unmeasured)
+ const unmeasuredBackend = useSessionMemory((s) => s.unmeasuredBackend)
const loading = useSessionMemory((s) => s.loading)
const loadedScope = useSessionMemory((s) => s.loadedScope)
const refreshFull = useSessionMemory((s) => s.refreshFull)
@@ -144,9 +145,10 @@ export function SessionMemoryPanel({
} else if (!measured) {
body = <div className="sessmem-panel__note">Measuring…</div>
} else if (views.length === 0 && unmeasured !== 0) {
- // The sweep reads tmux; Zellij-backed sessions are alive and simply not in it. "No sessions"
+ // The sweep reads tmux (and, on Windows, the session host); Zellij-backed sessions, and those
+ // of a session host too old to describe them, are alive and simply not in it. "No sessions"
// here would be the ok:true-with-no-rows lie this panel exists to avoid.
- body = <div className="sessmem-panel__note">{unmeasuredNote(unmeasured)}</div>
+ body = <div className="sessmem-panel__note">{unmeasuredNote(unmeasured, unmeasuredBackend)}</div>
} else if (views.length === 0) {
// We looked, and there really is nothing — a different sentence from the two above.
body = <div className="sessmem-panel__note">No sessions are running here.</div>
@@ -237,7 +239,7 @@ export function SessionMemoryPanel({
body = (
<>
{body}
- <div className="sessmem-panel__note">{unmeasuredNote(unmeasured)}</div>
+ <div className="sessmem-panel__note">{unmeasuredNote(unmeasured, unmeasuredBackend)}</div>
</>
)
}
diff --git a/src/renderer/components/sessionBackendNote.test.ts b/src/renderer/components/sessionBackendNote.test.ts
index 249350a01..d2d8e864b 100644
--- a/src/renderer/components/sessionBackendNote.test.ts
+++ b/src/renderer/components/sessionBackendNote.test.ts
@@ -41,4 +41,10 @@ describe('review of #1067 — sentences that must not over-claim', () => {
expect(unmeasuredNote(3)).toMatch(/^3 Zellij sessions are running here/)
expect(unmeasuredNote(null)).toMatch(/could not be counted/)
})
+ it('session-host sessions an older host could not describe are named as such, not as Zellij', () => {
+ expect(unmeasuredNote(1, 'session-host')).toMatch(/^1 session is running here and not measured/)
+ expect(unmeasuredNote(2, 'session-host')).toMatch(/^2 sessions are running here.*session host predates/)
+ expect(unmeasuredNote(2, 'session-host')).not.toMatch(/Zellij/)
+ expect(unmeasuredNote(null, 'session-host')).toMatch(/could not be counted/)
+ })
})
diff --git a/src/renderer/lib/sessionMemoryNote.ts b/src/renderer/lib/sessionMemoryNote.ts
index a2d219bc2..7d9adf9a1 100644
--- a/src/renderer/lib/sessionMemoryNote.ts
+++ b/src/renderer/lib/sessionMemoryNote.ts
@@ -1,5 +1,12 @@
-/** The sentence for live sessions the tmux sweep could not measure (Zellij-backed). */
-export function unmeasuredNote(n: number | null): string {
+/** The sentence for live sessions the sweep could not measure: Zellij-backed ones (the sweep reads
+ * tmux), or — `backend: 'session-host'` — sessions of a running session host older than this app,
+ * which can name its sessions but not describe their processes. */
+export function unmeasuredNote(n: number | null, backend?: 'session-host'): string {
+ if (backend === 'session-host') {
+ if (n === null) return 'Some sessions could not be counted; only the measured ones are listed here.'
+ const what = n === 1 ? '1 session is' : `${n} sessions are`
+ return `${what} running here and not measured — the running session host predates this app version. They are measured once it restarts.`
+ }
if (n === null) return 'Zellij sessions could not be counted; only tmux sessions are measured here.'
return n === 1
? '1 Zellij session is running here and is not measured (the sweep reads tmux).'
diff --git a/src/renderer/state/sessionMemory.ts b/src/renderer/state/sessionMemory.ts
index cf807a52a..c7c75cdaf 100644
--- a/src/renderer/state/sessionMemory.ts
+++ b/src/renderer/state/sessionMemory.ts
@@ -21,6 +21,8 @@ interface SessionMemoryState {
rows: SessionMemoryRow[]
/** Live sessions the sweep could not measure (Zellij); 0 = none, null = could not tell. */
unmeasured: number | null
+ /** Whose sessions `unmeasured` counts — absent = Zellij (see SessionMemoryReport). */
+ unmeasuredBackend?: 'session-host'
mem: MemInfo | null
loading: boolean
/** Scope key the current rows belong to; null before the first successful load. */
@@ -86,12 +88,12 @@ export const useSessionMemory = create<SessionMemoryState>((set, get) => ({
if (scopeKey !== activeScope) return
// `ok:false` is carried through untouched: the panel renders "could not measure", never an
// empty session list.
- set({ ok: r.ok, rows: r.rows, mem: r.mem, unmeasured: r.unmeasured ?? 0, loadedScope: scopeKey })
+ set({ ok: r.ok, rows: r.rows, mem: r.mem, unmeasured: r.unmeasured ?? 0, unmeasuredBackend: r.unmeasuredBackend, loadedScope: scopeKey })
} catch {
// A rejected call (dead WS bridge, no session yet) is the same fact as `ok:false` — the sweep
// could not run. It is emphatically not "there are no sessions".
if (scopeKey !== activeScope) return
- set({ ok: false, rows: [], unmeasured: 0 })
+ set({ ok: false, rows: [], unmeasured: 0, unmeasuredBackend: undefined })
} finally {
// A response for a scope we have left owns nothing here — `enterScope` already cleared the
// spinner when it switched.
@@ -133,5 +135,5 @@ function enterScope(scopeKey: string, set: SetState): void {
activeScope = scopeKey
// `loading:false` too: whatever was in flight now belongs to a scope we have left, so its
// `finally` will (correctly) not clear the spinner it set.
- set({ ok: true, rows: [], unmeasured: 0, mem: null, loading: false, loadedScope: null })
+ set({ ok: true, rows: [], unmeasured: 0, unmeasuredBackend: undefined, mem: null, loading: false, loadedScope: null })
}
diff --git a/src/server/index.ts b/src/server/index.ts
index b9d193e95..9edb87fe8 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -926,6 +926,8 @@ export async function startServer(
tmuxBin: () => ptyManager.getTmuxBin(),
// Zellij-backed sessions are not in the tmux sweep; the panel says how many it did not measure.
unmeasuredSessions: () => ptyManager.zellijSessionCount(),
+ // Windows (no tmux): the session host's sessions; undefined where it is not the backend.
+ sessionHost: () => ptyManager.sessionHostListing(),
remote: {
isRemoteProject: sshScopePredicate({ sshProjectIds: () => workspaceStore.sshProjectIds() })
}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 679d2e87a..75fee35e2 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -3035,6 +3035,10 @@ export interface SessionMemoryReport {
* panel must never say "no sessions are running" while this is non-zero or unknown.
*/
unmeasured?: number | null
+ /** Which backend the `unmeasured` sessions belong to, for the panel's sentence. Absent = Zellij
+ * (the original and, off Windows, only case); `'session-host'` = a running session host older
+ * than this app, which names its sessions but cannot describe their processes. */
+ unmeasuredBackend?: 'session-host'
}
/**