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(renderer): session-memory store, polled locally and on demand over SSH

enescb9f7f1d6927
diff --git a/src/renderer/state/sessionMemory.test.ts b/src/renderer/state/sessionMemory.test.ts
new file mode 100644
index 000000000..36e8479b0
--- /dev/null
+++ b/src/renderer/state/sessionMemory.test.ts
@@ -0,0 +1,155 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { useSessionMemory, HOST_POLL_MS } from './sessionMemory'
+import { createSession, resetSessionsForTest, setActiveSession } from '../session/session'
+import type { NodeTerminalApi } from '@shared/types'
+
+const host = vi.fn()
+const read = vi.fn()
+
+/** Let the pending microtasks (an awaited api call) settle without advancing the clock. */
+const flush = async (): Promise<void> => {
+ await vi.advanceTimersByTimeAsync(0)
+}
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ host.mockReset().mockResolvedValue({ availableMb: 1000, totalMb: 64000 })
+ read.mockReset().mockResolvedValue({ ok: true, rows: [], mem: null })
+ // The store reads through the ACTIVE SESSION's api (the same route state/worktrees.ts takes), so
+ // register a session whose api carries the mocks. Store construction touches no wire.
+ resetSessionsForTest()
+ setActiveSession(
+ createSession('local', { sessionMemory: { host, read } } as unknown as NodeTerminalApi, 'test')
+ .id
+ )
+ useSessionMemory.setState({ ok: true, rows: [], mem: null, loading: false, loadedScope: null })
+})
+
+afterEach(() => {
+ useSessionMemory.getState().stopHostPoll()
+ vi.useRealTimers()
+})
+
+describe('host poll cadence', () => {
+ it('polls repeatedly for a LOCAL scope', async () => {
+ useSessionMemory.getState().startHostPoll('', 'p1')
+ await vi.advanceTimersByTimeAsync(HOST_POLL_MS * 2 + 10)
+ // one immediate read + two ticks
+ expect(host.mock.calls.length).toBeGreaterThanOrEqual(3)
+ })
+
+ it('reads ONCE and schedules nothing for an SSH scope', async () => {
+ useSessionMemory.getState().startHostPoll('user@host', 'p1')
+ await vi.advanceTimersByTimeAsync(HOST_POLL_MS * 3)
+ // Each read is an ssh exec on someone else's machine — never on a timer.
+ expect(host).toHaveBeenCalledTimes(1)
+ })
+
+ it('stops the local timer when the scope becomes an SSH host', async () => {
+ useSessionMemory.getState().startHostPoll('', 'p1')
+ await vi.advanceTimersByTimeAsync(HOST_POLL_MS + 10)
+ host.mockClear()
+ useSessionMemory.getState().startHostPoll('user@host', 'ssh1')
+ await vi.advanceTimersByTimeAsync(HOST_POLL_MS * 3)
+ // Only the one immediate read the switch itself performed — the local interval must be gone.
+ expect(host).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('the query the shell is handed', () => {
+ it('tells the shell an SSH scope is remote, with the project that names the host', async () => {
+ useSessionMemory.getState().startHostPoll('user@host', 'ssh1')
+ await flush()
+ await useSessionMemory.getState().refreshFull('user@host', 'ssh1')
+ // `remote` is one of the two independent sources the service routes on — dropping it would let
+ // an SSH scope be answered with the local machine's sessions.
+ expect(host).toHaveBeenCalledWith({ projectId: 'ssh1', remote: true })
+ expect(read).toHaveBeenCalledWith({ projectId: 'ssh1', remote: true })
+ })
+
+ it('marks a local scope not-remote', async () => {
+ await useSessionMemory.getState().refreshFull('', 'p1')
+ expect(read).toHaveBeenCalledWith({ projectId: 'p1', remote: false })
+ })
+})
+
+describe('scope guarding', () => {
+ it('discards a response whose scope we have since left', async () => {
+ let release: (v: unknown) => void = () => {}
+ read.mockReturnValueOnce(new Promise((r) => (release = r)))
+ const p = useSessionMemory.getState().refreshFull('user@host', 'ssh1')
+ // Switch to the local machine while the SSH read is still in flight.
+ useSessionMemory.getState().startHostPoll('', 'p1')
+ release({ ok: true, rows: [{ nodeId: 'ghost' }], mem: null })
+ await p
+ expect(useSessionMemory.getState().rows).toEqual([])
+ expect(useSessionMemory.getState().loadedScope).not.toBe('user@host')
+ })
+
+ it('discards a HOST reading from a scope we have since left', async () => {
+ let release: (v: unknown) => void = () => {}
+ host.mockReturnValueOnce(new Promise((r) => (release = r)))
+ useSessionMemory.getState().startHostPoll('user@host', 'ssh1')
+ // Back to this machine; its own read answers with the default 64 GB fixture.
+ useSessionMemory.getState().startHostPoll('', 'p1')
+ await flush()
+ release({ availableMb: 7, totalMb: 7 })
+ await flush()
+ // The host's 7 MB must never be shown under the local machine's label.
+ expect(useSessionMemory.getState().mem).toEqual({ availableMb: 1000, totalMb: 64000 })
+ })
+
+ it('drops the previous scope´s rows the moment the scope changes', async () => {
+ read.mockResolvedValueOnce({
+ ok: true,
+ rows: [{ nodeId: 'remote-node' }],
+ mem: { availableMb: 5, totalMb: 10 }
+ })
+ await useSessionMemory.getState().refreshFull('user@host', 'ssh1')
+ expect(useSessionMemory.getState().rows).toHaveLength(1)
+ useSessionMemory.getState().startHostPoll('', 'p1')
+ // Not "stale rows under a new label" — no rows at all until the local machine answers.
+ expect(useSessionMemory.getState().rows).toEqual([])
+ expect(useSessionMemory.getState().loadedScope).toBeNull()
+ })
+})
+
+describe('failure semantics', () => {
+ it('keeps ok:false and no rows — never an empty success', async () => {
+ read.mockResolvedValueOnce({ ok: false, rows: [], mem: null })
+ await useSessionMemory.getState().refreshFull('', 'p1')
+ expect(useSessionMemory.getState().ok).toBe(false)
+ expect(useSessionMemory.getState().rows).toEqual([])
+ })
+
+ it('reports a rejected read as ok:false, not as an empty session list', async () => {
+ read.mockRejectedValueOnce(new Error('bridge down'))
+ await useSessionMemory.getState().refreshFull('', 'p1')
+ expect(useSessionMemory.getState().ok).toBe(false)
+ })
+
+ it('leaves mem null when the host read throws, rather than reporting zero', async () => {
+ // Start from a KNOWN reading, so "still null" cannot pass just because null is the initial
+ // state — the assertion has to prove the failure actually cleared it.
+ await useSessionMemory.getState().refreshHost('', 'p1')
+ expect(useSessionMemory.getState().mem).toEqual({ availableMb: 1000, totalMb: 64000 })
+ host.mockRejectedValueOnce(new Error('nope'))
+ await useSessionMemory.getState().refreshHost('', 'p1')
+ expect(useSessionMemory.getState().mem).toBeNull()
+ })
+
+ it('clears loading after refreshFull', async () => {
+ await useSessionMemory.getState().refreshFull('', 'p1')
+ expect(useSessionMemory.getState().loading).toBe(false)
+ })
+
+ it('leaves no spinner behind when the scope changes mid-read', async () => {
+ let release: (v: unknown) => void = () => {}
+ read.mockReturnValueOnce(new Promise((r) => (release = r)))
+ const p = useSessionMemory.getState().refreshFull('user@host', 'ssh1')
+ useSessionMemory.getState().startHostPoll('', 'p1')
+ release({ ok: true, rows: [], mem: null })
+ await p
+ expect(useSessionMemory.getState().loading).toBe(false)
+ })
+})
diff --git a/src/renderer/state/sessionMemory.ts b/src/renderer/state/sessionMemory.ts
new file mode 100644
index 000000000..d6c5f8747
--- /dev/null
+++ b/src/renderer/state/sessionMemory.ts
@@ -0,0 +1,134 @@
+// Session-memory store. Two cadences, because the two reads cost wildly different things:
+// - `refreshHost` is one file read locally → safe to poll (the pill's number).
+// - `refreshFull` walks the whole process table, and over SSH it is an exec on someone else's
+// machine → on demand only (panel open, refresh button). Never on a timer.
+//
+// Scope changes are guarded the way state/worktrees.ts guards project switches, except the stamp
+// here is the SCOPE ITSELF rather than a counter: a response stamped with a scope we have since
+// left is DISCARDED, so an SSH host's rows (or its RAM number) can never land under the local
+// machine's label. A counter alone is not enough — `refreshFull` and `startHostPoll` can be called
+// for different scopes without any intervening bump, which is exactly the switch this must catch.
+
+import { create } from 'zustand'
+import type { MemInfo, SessionMemoryApi, SessionMemoryQuery, SessionMemoryRow } from '@shared/types'
+import { activeSessionApi, sessionForProject } from '../session/session'
+
+/** How often the pill re-reads the LOCAL machine's RAM. Local only — see `startHostPoll`. */
+export const HOST_POLL_MS = 30_000
+
+interface SessionMemoryState {
+ ok: boolean
+ rows: SessionMemoryRow[]
+ mem: MemInfo | null
+ loading: boolean
+ /** Scope key the current rows belong to; null before the first successful load. */
+ loadedScope: string | null
+ refreshHost(scopeKey: string, projectId?: string): Promise<void>
+ refreshFull(scopeKey: string, projectId?: string): Promise<void>
+ startHostPoll(scopeKey: string, projectId?: string): void
+ stopHostPoll(): void
+}
+
+let timer: ReturnType<typeof setInterval> | null = null
+
+/**
+ * The scope every in-flight request is measured against. `null` before the first request. Module
+ * level, not store state, because a stale response must be judged against the scope that is CURRENT
+ * when it resolves — reading it out of a store snapshot captured before the await would defeat the
+ * whole guard.
+ */
+let activeScope: string | null = null
+
+const query = (scopeKey: string, projectId?: string): SessionMemoryQuery => ({
+ projectId,
+ // The renderer's half of the routing decision: it already knows from `usageScope` whether the
+ // active project runs on an SSH host. The shell confirms it independently; dropping it here would
+ // leave a not-yet-registered SSH project to be answered with the local machine's sessions.
+ remote: scopeKey !== ''
+})
+
+/**
+ * The api of the session that owns this project — NOT `window.nodeTerminal`. A relay tab's renderer
+ * runs on the guest while its sessions live on the host, and its api deliberately answers
+ * `ok:false` / `null` ("could not measure") rather than describing the wrong machine; reading the
+ * global would silently hand it this machine's sessions instead.
+ */
+const api = (projectId?: string): SessionMemoryApi =>
+ projectId ? sessionForProject(projectId).api.sessionMemory : activeSessionApi().sessionMemory
+
+export const useSessionMemory = create<SessionMemoryState>((set, get) => ({
+ ok: true,
+ rows: [],
+ mem: null,
+ loading: false,
+ loadedScope: null,
+
+ async refreshHost(scopeKey, projectId) {
+ enterScope(scopeKey, set)
+ let mem: MemInfo | null = null
+ try {
+ mem = await api(projectId).host(query(scopeKey, projectId))
+ } catch {
+ mem = null // could not read — the pill says "unknown"; it must not claim 0.
+ }
+ if (scopeKey !== activeScope) return
+ set({ mem })
+ },
+
+ async refreshFull(scopeKey, projectId) {
+ enterScope(scopeKey, set)
+ set({ loading: true })
+ try {
+ const r = await api(projectId).read(query(scopeKey, projectId))
+ 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, 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: [] })
+ } finally {
+ // A response for a scope we have left owns nothing here — `enterScope` already cleared the
+ // spinner when it switched.
+ if (scopeKey === activeScope) set({ loading: false })
+ }
+ },
+
+ startHostPoll(scopeKey, projectId) {
+ if (timer) {
+ clearInterval(timer)
+ timer = null
+ }
+ void get().refreshHost(scopeKey, projectId)
+ // SSH scope: one read, no timer. Every tick would be an ssh exec plus a `ps` of somebody else's
+ // whole process table — the same rule CLAUDE.md sets for remote usage ("on demand, never
+ // polled").
+ if (scopeKey !== '') return
+ timer = setInterval(() => void get().refreshHost(scopeKey, projectId), HOST_POLL_MS)
+ },
+
+ stopHostPoll() {
+ if (timer) {
+ clearInterval(timer)
+ timer = null
+ }
+ }
+}))
+
+type SetState = (partial: Partial<SessionMemoryState>) => void
+
+/**
+ * Adopt `scopeKey` as the scope every in-flight response is judged against, and — when it actually
+ * changed — drop the previous machine's facts. Keeping them would leave one host's rows on screen
+ * under another's label for as long as the new machine takes to answer, which is the same
+ * misattribution the stamp check exists to prevent, just visible for a shorter while.
+ */
+function enterScope(scopeKey: string, set: SetState): void {
+ if (activeScope === scopeKey) return
+ 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: [], mem: null, loading: false, loadedScope: null })
+}