fix(sessions): orphan cleanup was reading the wrong tmux clock

Adversarial review of the previous commit found ten defects. The critical one
would have destroyed exactly the work this feature exists to protect.

CRITICAL — `#{session_activity}` is a CLIENT clock, not an output clock.
It advances on attach and on keypresses, and never moves for a detached session
however much its shell is printing. Measured on tmux 3.6a: a detached session
running `while true; do echo tick; sleep 1; done` still reported
session_activity == session_created after 6 s, while `#{window_activity}` tracked
the output exactly. So "idle for 7 days" was really "nobody has typed for 7 days",
and `Clean up idle 7d+` would have killed long-running unattended sessions that
were busy working — the walk-away case the whole app is built around.
Measured against this host's 69 sessions: the old clock condemned 36, the new one
condemns 33, so three sessions doing real work were one click from deletion.
Now reads window_activity, with a test that fails if the format string regresses.

HIGH — no timeout on any tmux call. maxBuffer bounds a flood but nothing bounded
the wait, and a synchronous exec cannot be interrupted by the event loop, so a
tmux server stopped mid-syscall hung the whole server permanently. All five calls
(including the three that predate this feature) now carry one.

HIGH — listSessions and capturePane were synchronous on a POLLED path. Measured
73 ms and 58 ms per call on this host; every home screen on every device refreshes
on a 5 s timer, and each of those was 73 ms with the event loop stopped, i.e.
73 ms in which no PTY byte reached any terminal anywhere. Both are async now, so
the manager's listOrphans/captureOrphan/killOrphansIdleSince are too. The server
is a byte-shuttle first: nothing polled may block it.

HIGH — GET /orphan-sessions had no rate limiter although, unlike every other read
route, it spawns a subprocess. It shares the preview bucket now.

HIGH — the cleanup confirmation counted CARDS, and the grid is capped at 24 while
the cleanup matches across every session the server enumerates. On this host it
would have said "24" and ended 33 shells. New GET /orphan-sessions/count-idle
answers the real question, and the dialog states that number, or refuses to
proceed if it cannot be determined.

MEDIUM — fetchOrphanSessions collapsed every failure into [], so one 429 or 500
read as "all recovered sessions are gone", tearing down every mounted xterm and
rebuilding it on the next success. It returns null for failure now, and the
refresh leaves the section untouched.

MEDIUM — the preview latch was "card was created", not "preview succeeded", so a
card that lost its single request stayed blank forever. Latches on success.

MEDIUM — overlapping refreshes. refresh() is entered from a 5 s timer, from
killOrphan and from cleanup, with awaits inside and no guard, so a slow poll could
resurrect cards for sessions already killed or re-mount them into a root that
setVisible(false) had just cleared. A generation counter, bumped on teardown and
checked after every await, invalidates stale runs.

MEDIUM — renderPreview could write to a disposed xterm (it throws "Object has
been disposed"). PreviewCard carries an explicit `disposed` flag set by a new
disposeCard() helper, so no caller can dispose a terminal and forget the flag.
Deliberately NOT el.isConnected: a card not yet appended is alive, and two
existing preview-grid tests correctly caught that conflation.

LOW — kill and cleanup discarded their results, so a refusal (403 behind a proxy
whose Origin differs, 404 on a lost race) looked like a dead button. Both report.

Tests: 2209 unit, 27 e2e, 8 orphan integration. Verified live against all 69 real
sessions with none harmed; the window_activity fix confirmed on an isolated tmux
socket (-L) so the developer's sessions were never involved.
This commit is contained in:
Yaojia Wang
2026-07-30 11:28:39 +02:00
parent 4892fa7b49
commit f6ef19ebf6
8 changed files with 330 additions and 120 deletions

View File

@@ -8,8 +8,15 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
const mockExec = vi.fn()
// promisify(execFile) reads the custom symbol, so give it one that returns our mock.
const mockExecAsync = vi.fn()
const fakeExecFile = Object.assign(
(...a: unknown[]) => mockExecAsync(...a),
{ [Symbol.for('nodejs.util.promisify.custom')]: (...a: unknown[]) => mockExecAsync(...a) },
)
vi.mock('node:child_process', () => ({
execFileSync: (...a: unknown[]) => mockExec(...a),
execFile: fakeExecFile,
}))
const { tmuxAvailable, tmuxName, hasSession, killSession, parseSessionList, listSessions, capturePane } =
@@ -17,6 +24,7 @@ const { tmuxAvailable, tmuxName, hasSession, killSession, parseSessionList, list
beforeEach(() => {
mockExec.mockReset()
mockExecAsync.mockReset()
})
describe('tmuxName', () => {
@@ -29,7 +37,7 @@ describe('tmuxAvailable', () => {
it('returns true when `tmux -V` succeeds', () => {
mockExec.mockReturnValue(Buffer.from('tmux 3.4'))
expect(tmuxAvailable()).toBe(true)
expect(mockExec).toHaveBeenCalledWith('tmux', ['-V'], { stdio: 'ignore' })
expect(mockExec).toHaveBeenCalledWith('tmux', ['-V'], expect.objectContaining({ stdio: 'ignore' }))
})
it('returns false when tmux is missing (exec throws)', () => {
@@ -44,7 +52,11 @@ describe('hasSession', () => {
it('returns true when has-session exits 0', () => {
mockExec.mockReturnValue(Buffer.from(''))
expect(hasSession('web_x')).toBe(true)
expect(mockExec).toHaveBeenCalledWith('tmux', ['has-session', '-t', 'web_x'], { stdio: 'ignore' })
expect(mockExec).toHaveBeenCalledWith(
'tmux',
['has-session', '-t', 'web_x'],
expect.objectContaining({ stdio: 'ignore' }),
)
})
it('returns false when has-session throws (no such session)', () => {
@@ -59,7 +71,11 @@ describe('killSession', () => {
it('invokes tmux kill-session for the name', () => {
mockExec.mockReturnValue(Buffer.from(''))
killSession('web_x')
expect(mockExec).toHaveBeenCalledWith('tmux', ['kill-session', '-t', 'web_x'], { stdio: 'ignore' })
expect(mockExec).toHaveBeenCalledWith(
'tmux',
['kill-session', '-t', 'web_x'],
expect.objectContaining({ stdio: 'ignore' }),
)
})
it('swallows errors when the session is already gone', () => {
@@ -123,28 +139,46 @@ describe('parseSessionList', () => {
})
describe('listSessions', () => {
it('asks tmux for a machine-readable list', () => {
mockExec.mockReturnValue(`web_${U1}\t100\t100\t0\t80\t24\n`)
expect(listSessions().map((s) => s.id)).toEqual([U1])
const [file, args] = mockExec.mock.calls[0] as [string, string[]]
it('asks tmux for a machine-readable list', async () => {
mockExecAsync.mockResolvedValue({ stdout: `web_${U1}\t100\t100\t0\t80\t24\n`, stderr: '' })
expect((await listSessions()).map((s) => s.id)).toEqual([U1])
const [file, args] = mockExecAsync.mock.calls[0] as [string, string[]]
expect(file).toBe('tmux')
expect(args[0]).toBe('list-sessions')
expect(args).toContain('-F')
})
it('returns [] when there is no tmux server (exec throws)', () => {
mockExec.mockImplementation(() => {
throw new Error('no server running')
})
expect(listSessions()).toEqual([])
it('asks for window_activity, NOT session_activity', async () => {
// session_activity is a CLIENT clock: it never advances for a detached session
// however much its shell prints. Using it would make idle-cleanup kill exactly
// the unattended, actively-working sessions this feature exists to protect.
mockExecAsync.mockResolvedValue({ stdout: '', stderr: '' })
await listSessions()
const [, args] = mockExecAsync.mock.calls[0] as [string, string[]]
const fmt = args[args.indexOf('-F') + 1]!
expect(fmt).toContain('#{window_activity}')
expect(fmt).not.toContain('#{session_activity}')
})
it('bounds the call so a wedged tmux cannot hang the server', async () => {
mockExecAsync.mockResolvedValue({ stdout: '', stderr: '' })
await listSessions()
const opts = mockExecAsync.mock.calls[0]![2] as { timeout?: number; maxBuffer?: number }
expect(opts.timeout).toBeGreaterThan(0)
expect(opts.maxBuffer).toBeGreaterThan(0)
})
it('returns [] when there is no tmux server (exec rejects)', async () => {
mockExecAsync.mockRejectedValue(new Error('no server running'))
expect(await listSessions()).toEqual([])
})
})
describe('capturePane', () => {
it('captures the current screen WITHOUT attaching', () => {
mockExec.mockReturnValue('hello\n')
expect(capturePane('web_x')).toBe('hello\n')
const [file, args] = mockExec.mock.calls[0] as [string, string[]]
it('captures the current screen WITHOUT attaching', async () => {
mockExecAsync.mockResolvedValue({ stdout: 'hello\n', stderr: '' })
expect(await capturePane('web_x')).toBe('hello\n')
const [file, args] = mockExecAsync.mock.calls[0] as [string, string[]]
expect(file).toBe('tmux')
expect(args[0]).toBe('capture-pane')
expect(args).toContain('-p') // print to stdout — read-only, no client
@@ -154,10 +188,15 @@ describe('capturePane', () => {
expect(args).not.toContain('attach-session')
})
it('returns null when the session is gone', () => {
mockExec.mockImplementation(() => {
throw new Error("can't find session")
})
expect(capturePane('web_gone')).toBeNull()
it('returns null when the session is gone', async () => {
mockExecAsync.mockRejectedValue(new Error("can't find session"))
expect(await capturePane('web_gone')).toBeNull()
})
it('bounds the call', async () => {
mockExecAsync.mockResolvedValue({ stdout: '', stderr: '' })
await capturePane('web_x')
const opts = mockExecAsync.mock.calls[0]![2] as { timeout?: number }
expect(opts.timeout).toBeGreaterThan(0)
})
})