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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(core): pin the coalescing key, and refuse SSH scopes on the server too
enes41cc230c1554
diff --git a/src/core/session-memory-service.test.ts b/src/core/session-memory-service.test.tsindex a5814d24e..08e21c3be 100644--- a/src/core/session-memory-service.test.ts+++ b/src/core/session-memory-service.test.ts@@ -20,6 +20,19 @@ const host = (q: SessionMemoryQuery): 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'+/** The same, carrying the HOST's RAM — so an answer says positively which machine produced it.+ * `totalMb` comes back as `totalKb / 1024`, i.e. 4096 MB for the default. */+const hostReply = (totalMb = 4096): string =>+ [+ '##MEM',+ `MemAvailable: ${(totalMb / 2) * 1024} kB`,+ `MemTotal: ${totalMb * 1024} kB`,+ '##PANES',+ '##PROCS',+ '100 1 1024'+ ].join('\n')+const HOST_REPLY = hostReply()+beforeEach(() => {resetPlatformForTests()platform = fakePlatform()@@ -69,16 +82,17 @@ describe('startSessionMemoryService', () => {expect(readMem).not.toHaveBeenCalled()})- it('refuses a remote:true query the shell does not recognise as remote', async () => {+ it('honours 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.- // `run` returns a VALID reply, so `ok:false` can no longer be true by accident: it would be- // `true` if the read were routed remotely and `true` (locally swept) if it were not — the only- // way to get a refusal here is the disagreement being resolved towards the remote host and the- // runner reporting it could not look. `readMem` catches a local sweep whatever tmux does.+ //+ // `run` returns a VALID reply carrying the HOST's RAM, so the result says positively which+ // machine answered: 4096 MB total can only have come from the remote reply, and the injected+ // local reader (22 MB) is never consulted. An `ok:false` assertion would have been decorative+ // here — with a stub that reports "could not look", a refusal proves nothing about routing.const readMem = vi.fn(() => ({ availableMb: 11, totalMb: 22 }))- const run = vi.fn(async () => null)+ const run = vi.fn(async () => HOST_REPLY)startSessionMemoryService({tmuxBin: () => '/usr/bin/tmux',readMem,@@ -86,8 +100,29 @@ describe('startSessionMemoryService', () => {})const r = await read({ projectId: 'ssh1', remote: true })expect(run).toHaveBeenCalledOnce()- expect(r).toEqual({ ok: false, rows: [], mem: null })+ expect(r.ok).toBe(true)+ expect(r.mem).toEqual({ availableMb: 2048, totalMb: 4096 })+ expect(readMem).not.toHaveBeenCalled()+ })++ it('refuses an SSH scope when the shell knows it is remote but cannot read it', async () => {+ // The SERVER EDITION's shape: `isRemoteProject` (it has the workspace index) and NO `run` (no+ // ControlMaster). Booting with neither — as the server did before this round — let an SSH query+ // WITHOUT the renderer's flag fall through to the local sweep and publish this machine's+ // sessions under the remote host's name.+ const readMem = vi.fn(() => ({ availableMb: 11, totalMb: 22 }))+ startSessionMemoryService({+ tmuxBin: () => '/usr/bin/tmux',+ readMem,+ remote: { isRemoteProject: (id) => id === 'ssh1' }+ })+ // No `remote: true` flag: the shell's knowledge is the only thing routing this.+ expect(await read({ projectId: 'ssh1' })).toEqual({ ok: false, rows: [], mem: null })+ expect(await host({ projectId: 'ssh1' })).toBeNull()expect(readMem).not.toHaveBeenCalled()+ // …while a local project on the same shell is still swept normally.+ await read({ projectId: 'local1' })+ expect(readMem).toHaveBeenCalled()})it('treats a DISCONNECTED ssh project as remote (identity, not liveness)', async () => {@@ -123,6 +158,14 @@ describe('startSessionMemoryService', () => {expect(isRemoteProject('ssh2')).toBe(true)})+ it('works with the index alone — the no-manager shape the Server Edition uses', async () => {+ // `connectedProjectIds` is optional, and the shell that omits it is a production path (the+ // Server Edition has a workspace index and no SSH-project manager), not a hypothetical.+ const isRemoteProject = sshScopePredicate({ sshProjectIds: () => ['ssh1'] })+ expect(isRemoteProject('ssh1')).toBe(true)+ expect(isRemoteProject('local1')).toBe(false)+ })+it('coalesces the two channels onto ONE remote round trip', async () => {// A remote read is a whole-process-table `ps` on somebody else's machine, and the panel wants// both the rows and the RAM number. Firing them concurrently must not cost two ssh execs.@@ -149,6 +192,32 @@ describe('startSessionMemoryService', () => {expect(run).toHaveBeenCalledTimes(2)})+ it('coalesces PER PROJECT — two hosts in flight never share a report', async () => {+ // The coalescer is the one place in this service that can hand one scope's report to another+ // host's caller, and the only thing preventing it is the key. A single-project test cannot see+ // that: two concurrent reads for DIFFERENT hosts must stay two round trips with two answers.+ let release: (() => void) | undefined+ const gate = new Promise<void>((res) => {+ release = res+ })+ // Each host reports its own RAM, so the two answers are distinguishable by content, not just+ // by call count — a shared key would give one caller the other machine's numbers.+ const run = vi.fn(async (projectId: string) => {+ await gate+ return hostReply(projectId === 'ssh1' ? 4096 : 8192)+ })+ startSessionMemoryService({+ tmuxBin: () => '/usr/bin/tmux',+ remote: { run, isRemoteProject: () => true }+ })+ const both = Promise.all([read({ projectId: 'ssh1' }), read({ projectId: 'ssh2' })])+ release?.()+ const [a, b] = await both+ expect(run).toHaveBeenCalledTimes(2)+ expect(a.mem?.totalMb).toBe(4096)+ expect(b.mem?.totalMb).toBe(8192)+ })+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 }))diff --git a/src/core/session-memory-service.ts b/src/core/session-memory-service.tsindex e19a33413..6d35884c0 100644--- a/src/core/session-memory-service.ts+++ b/src/core/session-memory-service.ts@@ -15,10 +15,17 @@ export interface SessionMemoryServiceOptions {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. */+ /**+ * The two remote facts, INDEPENDENTLY optional — a shell can know which projects are somebody+ * else's machine without being able to read them:+ * - `isRemoteProject` absent ⇒ only the renderer's `remote` flag marks a scope as remote;+ * - `run` absent ⇒ a remote scope is REFUSED (`ok:false`), never swept locally.+ * The Server Edition supplies the first and not the second: it has the workspace index, so it+ * KNOWS a project is an SSH one, and it has no ControlMaster, so it cannot answer for that host.+ */remote?: {- run: RemoteSessionMemoryRunner- isRemoteProject: (projectId: string) => boolean+ run?: RemoteSessionMemoryRunner+ isRemoteProject?: (projectId: string) => boolean}}@@ -63,7 +70,7 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {* 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))+ q.remote === true || (!!q.projectId && !!opts.remote?.isRemoteProject?.(q.projectId))/*** One in-flight remote read per project, shared by both channels. A remote read is a `ps` of the@@ -72,6 +79,11 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {* Keyed by projectId (the only thing the command depends on) and cleared on settle, so this is a* concurrency guard, never a cache: a later read always re-runs.*/+ //+ // The key is the projectId and nothing else: it is the ONLY thing that decides which host the+ // command lands on, so a shared key across projects would hand one host's report to another+ // host's caller — the same misattribution the refusal above exists to prevent, arriving by a+ // different door.const inFlight = new Map<string, Promise<SessionMemoryReport>>()const readRemote = (projectId: string, run: RemoteSessionMemoryRunner): Promise<SessionMemoryReport> => {const pending = inFlight.get(projectId)@@ -90,8 +102,9 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {// 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()- return readRemote(q.projectId, opts.remote.run)+ const run = opts.remote?.run+ if (!run || !q.projectId) return EMPTY()+ return readRemote(q.projectId, run)}return collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem })}@@ -101,9 +114,10 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {IPC.sessionMemoryHost,async (q: SessionMemoryQuery = {}): Promise<MemInfo | null> => {if (!isRemote(q)) return (opts.readMem ?? readMemInfo)()- if (!opts.remote || !q.projectId) return null+ const run = opts.remote?.run+ if (!run || !q.projectId) return null// One round trip serves both numbers; the pill uses only `mem`.- return (await readRemote(q.projectId, opts.remote.run)).mem+ return (await readRemote(q.projectId, run)).mem})diff --git a/src/server/index.ts b/src/server/index.tsindex 79772b051..6aa472c8d 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -50,7 +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 { startSessionMemoryService, sshScopePredicate } 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'@@ -444,12 +444,24 @@ 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() })+ // Session memory: the pill's RAM read plus the on-demand per-session breakdown. The Server+ // Edition runs ON the host whose sessions it reports and has no SSH-project manager, so it passes+ // no `run` — an SSH scope is REFUSED (ok:false), never swept locally.+ //+ // It does supply `isRemoteProject`, because knowing which projects are somebody else's machine+ // and being able to READ them are different capabilities: the workspace index answers the first+ // right here (the same source as the SSH check in the agentAnswerPermission handler above).+ // Without it, an SSH query arriving WITHOUT the renderer's `remote` flag would fall through to+ // the local sweep and publish this server's own sessions under the remote host's name — the exact+ // misattribution the refusal exists to prevent. 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(),+ remote: {+ isRemoteProject: sshScopePredicate({ sshProjectIds: () => workspaceStore.sshProjectIds() })+ }+ })// 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