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.

test(server): pin the SSH refusal end to end, and the index load it needs

enesec7e5d7ebc0d
diff --git a/src/core/session-memory-service.test.ts b/src/core/session-memory-service.test.ts
index 08e21c3be..8b43a36c6 100644
--- a/src/core/session-memory-service.test.ts
+++ b/src/core/session-memory-service.test.ts
@@ -110,9 +110,12 @@ describe('startSessionMemoryService', () => {
// 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.
+ // `tmuxBin: () => null`, like the other local-routing test: a unit test must not shell out, and
+ // the local leg below only needs to be DISTINGUISHABLE from the refusal, not successful.
+ // (`collectSessionMemory` reads memory before it looks at tmux, so `readMem` still fires.)
const readMem = vi.fn(() => ({ availableMb: 11, totalMb: 22 }))
startSessionMemoryService({
- tmuxBin: () => '/usr/bin/tmux',
+ tmuxBin: () => null,
readMem,
remote: { isRemoteProject: (id) => id === 'ssh1' }
})
diff --git a/src/core/session-memory-service.ts b/src/core/session-memory-service.ts
index 6d35884c0..8736764f8 100644
--- a/src/core/session-memory-service.ts
+++ b/src/core/session-memory-service.ts
@@ -16,16 +16,21 @@ export interface SessionMemoryServiceOptions {
/** Host RAM reader, injectable for tests. Defaults to the real `/proc/meminfo` read. */
readMem?: () => MemInfo | null
/**
- * 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.
+ * The two remote facts, in a deliberately ASYMMETRIC pair: knowing which projects are somebody
+ * else's machine is required, being able to read them is not.
+ * - `run` absent ⇒ a remote scope is REFUSED (`ok:false`), never swept locally. This is the
+ * Server Edition: 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. Knowing-without-reading is coherent.
+ * - `isRemoteProject` is NOT optional, because reading-without-knowing is not coherent: a shell
+ * that can run the command but cannot say which projects need it would route every UNFLAGGED
+ * SSH query to the LOCAL sweep — the misattribution this whole surface exists to prevent. It
+ * stays type-illegal rather than merely discouraged.
+ * Omit `remote` entirely and only the renderer's `remote` flag marks a scope as remote — which
+ * is why no shell should do that (both ship an `isRemoteProject`).
*/
remote?: {
run?: RemoteSessionMemoryRunner
- isRemoteProject?: (projectId: string) => boolean
+ isRemoteProject: (projectId: string) => boolean
}
}
@@ -70,20 +75,19 @@ 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
* whole process table on somebody else's machine, and the panel legitimately wants both the RAM
* number and the rows — which is two identical execs back to back unless they are coalesced.
- * 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.
+ * 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, because that is the only thing deciding which host
+ * the command lands on. A key shared across projects would hand one host's report to another
+ * host's caller — the same misattribution the refusal below exists to prevent, arriving by a
+ * different door, and invisible to any test that uses a single project.
*/
- //
- // 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)
diff --git a/src/server/index.ts b/src/server/index.ts
index 6aa472c8d..67ba61602 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -456,6 +456,12 @@ export async function startServer(
// 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.
+ //
+ // DEPENDENCY, and one that breaks silently: `sshProjectIds()` reads the IN-MEMORY index, which is
+ // populated only by the `await workspaceStore.load(...)` above — a line documented there as being
+ // for context-link. Move it below this point, or drop it, and every SSH project reads as local
+ // here: the refusal quietly degrades to renderer-flag-only routing, which is the misattribution
+ // bug itself. `test/server/session-memory-e2e.test.ts` exists to fail if that happens.
startSessionMemoryService({
tmuxBin: () => ptyManager.getTmuxBin(),
remote: {
diff --git a/test/server/session-memory-e2e.test.ts b/test/server/session-memory-e2e.test.ts
new file mode 100644
index 000000000..bcfeb1828
--- /dev/null
+++ b/test/server/session-memory-e2e.test.ts
@@ -0,0 +1,138 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import WebSocket from 'ws'
+import { startServer } from '../../src/server/index'
+import { IPC } from '../../src/shared/ipc'
+import type { MemInfo, SessionMemoryReport } from '../../src/shared/types'
+
+/**
+ * The Server Edition's session-memory refusal, end to end.
+ *
+ * The property under test is a SAFETY one: this server has no ControlMaster, so it can never read
+ * an SSH project's host — and answering such a query with its OWN sessions would publish one
+ * machine's memory under another machine's name. It must refuse instead, and it must do so from
+ * its own knowledge (the workspace index), NOT from a `remote: true` flag the renderer sends —
+ * which is why every request below deliberately omits that flag.
+ *
+ * Two couplings this pins that no unit test can:
+ * 1. the shell actually passes `isRemoteProject` (booting with no `remote` deps at all was the
+ * original bug), and
+ * 2. `sshProjectIds()` has real data by the time a query arrives — i.e. the boot-time
+ * `workspaceStore.load(...)`, whose comment attributes it to context-link, is load-bearing for
+ * this refusal too.
+ *
+ * No network and no sshd: the ssh entry is only ever READ from the index here. `loadV3`'s ssh
+ * branch is offline (a cached project, else an `unavailable` placeholder) and `sshProjectIds()`
+ * returns the entry's id in either case.
+ */
+describe('server e2e: session memory refuses an SSH scope', () => {
+ let dataDir: string, close: () => Promise<void>, port: number, cookie: string
+
+ const SSH_ID = 'ssh-e2e'
+ const LOCAL_ID = 'local-e2e'
+
+ beforeAll(async () => {
+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-sessmem-e2e-'))
+ // Written BEFORE boot: the index is read once at startup, and the refusal depends on it.
+ fs.writeFileSync(
+ path.join(dataDir, 'workspace.json'),
+ JSON.stringify({
+ version: 3,
+ activeProjectId: SSH_ID,
+ entries: [
+ {
+ id: SSH_ID,
+ name: 'ssh project',
+ color: '#888888',
+ ssh: { server: { host: 'example.invalid', user: 'nobody' }, remoteCwd: '/srv/x' }
+ },
+ { id: LOCAL_ID, name: 'local project', color: '#888888', project: { id: LOCAL_ID, name: 'local project', color: '#888888', nodes: [] } }
+ ]
+ })
+ )
+ const srv = await startServer({
+ port: 0,
+ host: '127.0.0.1',
+ dataDir,
+ rendererDir: path.join(dataDir, 'no-renderer'),
+ insecureHttp: false,
+ passwordSeed: 'e2e-password-123',
+ // Never touch the developer's real ~/.claude — see server-e2e.test.ts.
+ installHooks: false
+ })
+ port = srv.port
+ close = srv.close
+ const res = await fetch(`http://127.0.0.1:${port}/auth/login`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ body: 'password=e2e-password-123',
+ redirect: 'manual'
+ })
+ expect(res.status).toBe(303)
+ cookie = res.headers.get('set-cookie')!.split(';')[0]
+ }, 30_000)
+
+ afterAll(async () => {
+ await close?.()
+ fs.rmSync(dataDir, { recursive: true, force: true })
+ })
+
+ /** One WS connection, several RPC calls, results keyed by request id. */
+ async function rpc(calls: { method: string; args: unknown[] }[]): Promise<unknown[]> {
+ const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`, { headers: { cookie } })
+ await new Promise<void>((res, rej) => {
+ ws.on('open', () => res())
+ ws.on('error', rej)
+ })
+ try {
+ const results = new Map<number, unknown>()
+ await new Promise<void>((resolve, reject) => {
+ ws.on('message', (d, isBinary) => {
+ if (isBinary) return
+ const m = JSON.parse(d.toString())
+ if (m.t !== 'res') return
+ if (!m.ok) return reject(new Error(`${calls[m.id - 1]?.method} rejected: ${m.error}`))
+ results.set(m.id, m.result)
+ if (results.size === calls.length) resolve()
+ })
+ calls.forEach((c, i) => ws.send(JSON.stringify({ t: 'req', id: i + 1, method: c.method, args: c.args })))
+ setTimeout(() => reject(new Error('session-memory rpc timed out')), 20_000)
+ })
+ return calls.map((_, i) => results.get(i + 1))
+ } finally {
+ ws.close()
+ }
+ }
+
+ it('answers ok:false for an ssh project — with no renderer flag to help it', async () => {
+ const [report, mem] = (await rpc([
+ { method: IPC.sessionMemory, args: [{ projectId: SSH_ID }] },
+ { method: IPC.sessionMemoryHost, args: [{ projectId: SSH_ID }] }
+ ])) as [SessionMemoryReport, MemInfo | null]
+
+ // Not merely "no rows": `ok:false` is what tells the panel it could not look, and a null `mem`
+ // is what stops the pill printing THIS machine's RAM under the remote host's name.
+ expect(report.ok).toBe(false)
+ expect(report.rows).toEqual([])
+ expect(report.mem).toBeNull()
+ expect(mem).toBeNull()
+ }, 30_000)
+
+ it('still serves a LOCAL project from this machine', async () => {
+ // The refusal must be scoped to the ssh entry, not a blanket "the server answers nothing".
+ const [report, mem] = (await rpc([
+ { method: IPC.sessionMemory, args: [{ projectId: LOCAL_ID }] },
+ { method: IPC.sessionMemoryHost, args: [{ projectId: LOCAL_ID }] }
+ ])) as [SessionMemoryReport, MemInfo | null]
+
+ // `ok` depends on whether this machine has a usable tmux, so both values are correct here; what
+ // must differ from the ssh case is that a local scope is answered from the local reader at all.
+ expect(typeof report.ok).toBe('boolean')
+ expect(Array.isArray(report.rows)).toBe(true)
+ // /proc/meminfo (or the os fallback) always answers on a machine that can run this suite.
+ expect(mem).not.toBeNull()
+ expect(Number.isFinite(mem?.totalMb)).toBe(true)
+ }, 30_000)
+})