/** * @fileoverview Runs the foreign-tmux probe at the three locations Codeman * already knows how to reach: this host, inside a container, and across ssh. * * All the judgement lives in `foreign-tmux.ts` (pure). This module is only * transport + caching + the promise that it never throws. * * ## Cost policy * * The home screen shows LOCAL results automatically, so a local scan runs on a * TTL cache: N browser tabs polling every few seconds still trigger at most one * scan per `FOREIGN_CACHE_TTL_MS`. Docker and remote are ON DEMAND only: * opening the home page must never fan out one ssh connection per saved host. * * ## ⚠️ The probe must not cross an extra shell * * The script contains `$TMUX_TMPDIR` and `$(id -u)`, which the INNER shell has to * expand. Local and docker therefore spawn with an argv array, where no outer * shell exists to eat them first. Remote is the exception: the ssh * command line is a string like every other ssh call in this codebase, so the * script is wrapped in SINGLE quotes there, which is exactly why * `buildForeignProbeScript()` may not contain one. * * This was measured, not reasoned: running the probe through `execSync` (which * spawns `sh -c`) expanded `$TMUX_TMPDIR` and `$U` in the OUTER shell, leaving the * inner loop iterating over the literal `/tmux-/*` and reporting zero sessions on * a machine that had three. * * ## A probe that goes wrong still answers * * All three transports go through `runForeignProbe`, which never rejects and hands * back what it read. A timeout has to reach the whole process tree, not just the * `sh` on top (the same rule as `runFetch` in git-fetch.ts): signalling only `sh` * left its tmux child stuck on a stopped server, one more per scan, for as long as * the home screen stayed open. And a scan cut short keeps the rows it already has, * since one bad server must not empty the list of a machine with good ones. * * @module foreign-tmux-discovery */ import { spawn, type ChildProcess } from 'node:child_process'; import { buildForeignProbeScript, classifyForeignPaneMode, createForeignSignatureMatcher, foreignRemoteShellCommand, foreignSessionId, isAdoptableSessionName, isAdoptableSocketPath, isCodemanOwnedPane, parseForeignProbeOutput, } from './foreign-tmux.js'; import { dockerEngineArgv, readDockerCases, readDockerHosts } from './docker-hosts.js'; import { buildSshConnectionArgs, readRemoteHosts, remoteSshTarget, shellescape } from './remote-hosts.js'; import { runWithRemoteSshLimit } from './remote-ssh-limiter.js'; import { resolveTmuxSocketName, getDataDir } from './config/instance.js'; import { FOREIGN_CACHE_TTL_MS, FOREIGN_PROBE_KILL_GRACE_MS, FOREIGN_PROBE_MAX_BYTES, FOREIGN_PROBE_TIMEOUT_MS, } from './config/foreign-tmux.js'; import type { ForeignDiscoveryResult, ForeignTmuxSession } from './types/foreign-tmux.js'; import type { DockerCase, DockerHost, RemoteHost, SessionDocker } from './types/session.js'; const IS_TEST_MODE = process.env.VITEST === 'true' || process.env.NODE_ENV === 'test'; /** What one probe produced, however it ended. */ export interface ForeignProbeRun { /** Everything read before it finished or was stopped. */ stdout: string; /** False when it timed out, flooded, exited non-zero or could not start. */ ok: boolean; } /** * Run one probe in its own process group. Never rejects (see @fileoverview). * * The caller is answered AT the deadline, while the group is still dying. */ export function runForeignProbe( argv: readonly string[], opts: { timeoutMs?: number; maxBytes?: number } = {} ): Promise { const { timeoutMs = FOREIGN_PROBE_TIMEOUT_MS, maxBytes = FOREIGN_PROBE_MAX_BYTES } = opts; return new Promise((resolve) => { const [file, ...args] = argv; const chunks: Buffer[] = []; let bytes = 0; let settled = false; let child: ChildProcess | undefined; let escalation: NodeJS.Timeout | undefined; const finish = (ok: boolean) => { if (settled) return; settled = true; clearTimeout(deadline); resolve({ stdout: Buffer.concat(chunks).toString('utf-8'), ok }); }; const signalGroup = (signal: NodeJS.Signals) => { try { if (child?.pid) process.kill(-child.pid, signal); } catch { /* already gone */ } }; const stop = () => { signalGroup('SIGTERM'); escalation = setTimeout(() => signalGroup('SIGKILL'), FOREIGN_PROBE_KILL_GRACE_MS); escalation.unref(); // ⚠️ Let go of the pipe by hand. A stopped tmux server can hold it open with // everything in this group dead (see foreign-tmux.ts), so waiting for its EOF // would keep one handle per scan until that server is resumed. child?.stdout?.destroy(); finish(false); }; const deadline = setTimeout(stop, timeoutMs); try { child = spawn(file ?? '', args, { stdio: ['ignore', 'pipe', 'ignore'], detached: true }); } catch { finish(false); return; } child.stdout?.on('data', (chunk: Buffer) => { if (settled) return; chunks.push(chunk.subarray(0, Math.max(0, maxBytes - bytes))); bytes += chunk.length; if (bytes > maxBytes) stop(); }); child.on('error', () => finish(false)); child.on('close', (code) => { // The group is gone, so a late SIGKILL could only reach whoever reused its id. clearTimeout(escalation); finish(code === 0); }); }); } /** The note for a probe that ended badly. Rows already read stay, so say which case this is. */ function probeFailureNote(where: string, run: ForeignProbeRun, nothing: string): string { return run.stdout ? `${where}: the scan did not finish, this list may be incomplete` : `${where}: ${nothing}`; } /** * Turn one probe's stdout into candidates. Shared by all three transports, so a * container's sessions and the host's are classified by identical rules. * * `where` opens every note this scan writes (`local`, `docker `, `remote *