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.

fix(core): an SSH project is a remote scope while DISCONNECTED too

enesdf16163bf7da
diff --git a/src/core/session-memory-service.test.ts b/src/core/session-memory-service.test.ts
index 3d0886758..a5814d24e 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 } from './session-memory-service'
+import { 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
@@ -73,15 +73,80 @@ describe('startSessionMemoryService', () => {
// 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.
+ const readMem = vi.fn(() => ({ availableMb: 11, totalMb: 22 }))
const run = vi.fn(async () => null)
startSessionMemoryService({
tmuxBin: () => '/usr/bin/tmux',
+ readMem,
remote: { run, isRemoteProject: () => false }
})
const r = await read({ projectId: 'ssh1', remote: true })
expect(run).toHaveBeenCalledOnce()
- expect(r.ok).toBe(false)
- expect(r.rows).toEqual([])
+ expect(r).toEqual({ ok: false, rows: [], mem: null })
+ expect(readMem).not.toHaveBeenCalled()
+ })
+
+ it('treats a DISCONNECTED ssh project as remote (identity, not liveness)', async () => {
+ // The desktop's `isRemoteProject`. `connectedHosts()` answers "is the master up right now",
+ // which is false for a project that is reconnecting, just dropped, or not opened yet — and a
+ // "no" there used to mean the LOCAL sweep answered under the remote host's name. The workspace
+ // index is the connection-independent source, so an SSH project counts while offline.
+ const isRemoteProject = sshScopePredicate({
+ sshProjectIds: () => ['ssh1'],
+ connectedProjectIds: () => [] // nothing connected: every master is down
+ })
+ expect(isRemoteProject('ssh1')).toBe(true)
+ expect(isRemoteProject('local1')).toBe(false)
+
+ // And end-to-end through the service, with the renderer's flag ABSENT — the shell's answer is
+ // the only thing standing between this query and a local sweep (the renderer flag is Task 5/7).
+ const readMem = vi.fn(() => ({ availableMb: 11, totalMb: 22 }))
+ const run = vi.fn(async () => null)
+ startSessionMemoryService({ tmuxBin: () => '/usr/bin/tmux', readMem, remote: { run, isRemoteProject } })
+ const r = await read({ projectId: 'ssh1' })
+ expect(run).toHaveBeenCalledOnce()
+ expect(r).toEqual({ ok: false, rows: [], mem: null })
+ expect(readMem).not.toHaveBeenCalled()
+ })
+
+ it('counts a connected project the index has not listed', async () => {
+ // The other direction: an index that has not loaded (or an entry added by another machine)
+ // must not make a project with a LIVE master read as local. Neither source can veto the other.
+ const isRemoteProject = sshScopePredicate({
+ sshProjectIds: () => [],
+ connectedProjectIds: () => ['ssh2']
+ })
+ expect(isRemoteProject('ssh2')).toBe(true)
+ })
+
+ 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.
+ let release: (() => void) | undefined
+ const gate = new Promise<void>((res) => {
+ release = res
+ })
+ const run = vi.fn(async () => {
+ await gate
+ return OK_REPLY
+ })
+ startSessionMemoryService({
+ tmuxBin: () => '/usr/bin/tmux',
+ remote: { run, isRemoteProject: () => true }
+ })
+ const both = Promise.all([read({ projectId: 'ssh1' }), host({ projectId: 'ssh1' })])
+ release?.()
+ const [report] = await both
+ expect(run).toHaveBeenCalledOnce()
+ expect(report.ok).toBe(true)
+
+ // Not a cache: once settled, the next read runs again.
+ await read({ projectId: 'ssh1' })
+ expect(run).toHaveBeenCalledTimes(2)
})
it('never runs the local sweep for a remote scope with no projectId', async () => {
diff --git a/src/core/session-memory-service.ts b/src/core/session-memory-service.ts
index 14328aed8..e19a33413 100644
--- a/src/core/session-memory-service.ts
+++ b/src/core/session-memory-service.ts
@@ -22,22 +22,67 @@ export interface SessionMemoryServiceOptions {
}
}
-const EMPTY = (mem: MemInfo | null): SessionMemoryReport => ({ ok: false, rows: [], mem })
+/** The facts a shell can offer about which projects are somebody else's machine. */
+export interface SshScopeSources {
+ /** Every project the workspace index calls an SSH project — the IDENTITY question. */
+ sshProjectIds: () => string[]
+ /** Projects whose ControlMaster is up right now — a LIVENESS question, and only a supplement. */
+ connectedProjectIds?: () => string[]
+}
+
+/**
+ * Build the shell's `isRemoteProject`. This must answer "is this project someone else's machine?",
+ * which is a property of the PROJECT, not of its connection: a disconnected SSH project is still a
+ * remote scope. Asking `connectedHosts()` alone votes "local" for a project that is reconnecting,
+ * just dropped, or not connected yet — precisely the window the refusal below exists for, and the
+ * one where a local sweep would be published under the remote host's name.
+ *
+ * Connectedness is still OR-ed in as a second source: a project the index has not (yet) listed —
+ * a stale/unloaded index, an entry added by another machine — but which has a live master is
+ * unambiguously remote too. Neither source can veto the other; either one alone is enough.
+ *
+ * Both getters are called per query (projects connect and disconnect under us) and must not throw.
+ */
+export function sshScopePredicate(sources: SshScopeSources): (projectId: string) => boolean {
+ return (projectId: string): boolean =>
+ sources.sshProjectIds().includes(projectId) ||
+ (sources.connectedProjectIds?.() ?? []).includes(projectId)
+}
+
+const EMPTY = (): SessionMemoryReport => ({ ok: false, rows: [], mem: null })
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.
+ * - the shell's `isRemoteProject` (see `sshScopePredicate`).
+ * They are OR-ed, not AND-ed, on purpose. A source that answers "no" because it is momentarily
+ * uninformed — an index not loaded, a master that 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))
+ /**
+ * 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.
+ */
+ const inFlight = new Map<string, Promise<SessionMemoryReport>>()
+ const readRemote = (projectId: string, run: RemoteSessionMemoryRunner): Promise<SessionMemoryReport> => {
+ const pending = inFlight.get(projectId)
+ if (pending) return pending
+ const p = fetchRemoteSessionMemory(projectId, run).finally(() => {
+ inFlight.delete(projectId)
+ })
+ inFlight.set(projectId, p)
+ return p
+ }
+
platform().handle(
IPC.sessionMemory,
async (q: SessionMemoryQuery = {}): Promise<SessionMemoryReport> => {
@@ -45,8 +90,8 @@ 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(null)
- return fetchRemoteSessionMemory(q.projectId, opts.remote.run)
+ if (!opts.remote || !q.projectId) return EMPTY()
+ return readRemote(q.projectId, opts.remote.run)
}
return collectSessionMemory({ tmuxBin: opts.tmuxBin, readMem: opts.readMem })
}
@@ -58,11 +103,12 @@ export function startSessionMemoryService(opts: SessionMemoryServiceOptions): {
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
+ return (await readRemote(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.
+ // Nothing to tear down: both handlers are pull-only, with no timer and no cache (`inFlight` holds
+ // only unsettled promises). `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 325117db0..7686d17ed 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -69,7 +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 { startSessionMemoryService, sshScopePredicate } 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'
@@ -1511,8 +1511,15 @@ app.whenReady().then(async () => {
startSessionMemoryService({
tmuxBin: () => ptyManager.getTmuxBin(),
remote: {
- isRemoteProject: (projectId) =>
- (sshProjectManager?.connectedHosts() ?? []).some((h) => h.projectId === projectId),
+ // 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
+ // refusal exists for. The workspace index is the connection-independent source; the live
+ // masters are OR-ed in for a project the index has not (yet) listed. See sshScopePredicate.
+ isRemoteProject: sshScopePredicate({
+ sshProjectIds: () => workspaceStore.sshProjectIds(),
+ connectedProjectIds: () =>
+ (sshProjectManager?.connectedHosts() ?? []).map((h) => h.projectId)
+ }),
run: async (projectId, command) => {
const mgr = sshProjectManager
const ref = mgr?.refForProject(projectId)