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(ssh): generated remote shell for Share with team (probe, install, team CLI, kill-verify)

reviewfbabafdb1d2f
diff --git a/src/core/remote-ssh/share-team-remote.test.ts b/src/core/remote-ssh/share-team-remote.test.ts
new file mode 100644
index 000000000..256928dc5
--- /dev/null
+++ b/src/core/remote-ssh/share-team-remote.test.ts
@@ -0,0 +1,244 @@
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import {
+ shareProbeCommand, parseShareProbe, teamCliCommand, parseTeamCliOutput,
+ killVerifyCommand, parseKillVerify, paneCommandsByNode, SHARE_INSTALL_SCRIPT, SERVER_INSTALL_URL
+} from './share-team-remote'
+
+const run = promisify(execFile)
+let dir: string, home: string, bin: string, state: string
+
+const write = (p: string, body: string, mode = 0o644): void => {
+ fs.mkdirSync(path.dirname(p), { recursive: true })
+ fs.writeFileSync(p, body, { mode })
+}
+
+beforeAll(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-share-'))
+ home = path.join(dir, 'home')
+ bin = path.join(dir, 'bin')
+ state = path.join(dir, 'tmux-state')
+ fs.mkdirSync(state, { recursive: true })
+ fs.mkdirSync(path.join(home, 'proj'), { recursive: true })
+ write(path.join(bin, 'uname'), '#!/bin/sh\necho Linux\n', 0o755)
+ write(path.join(bin, 'id'), '#!/bin/sh\ncase "$1" in -u) echo 1000;; -un) echo alice;; esac\n', 0o755)
+ write(path.join(bin, 'git'), '#!/bin/sh\nexit 0\n', 0o755)
+ // A fake tmux: sessions are files in $STATE; a "*.stuck" one survives kill-session. Like real
+ // tmux, a target WITHOUT the leading `=` that matches no session exactly falls back to a prefix
+ // match, so a missing `=` in the generated command would kill a longer id's session.
+ write(
+ path.join(bin, 'tmux'),
+ [
+ '#!/bin/sh',
+ `S=${JSON.stringify(state)}`,
+ 'cmd=""; target=""',
+ 'while [ $# -gt 0 ]; do case "$1" in -L) shift;; -t) shift; target="$1";; kill-session|has-session|list-panes) cmd="$1";; esac; shift; done',
+ 'name="${target#=}"',
+ 'exact=0; [ "$name" != "$target" ] && exact=1',
+ 'resolve() {',
+ ' { [ -e "$S/$name" ] || [ -e "$S/$name.stuck" ]; } && return 0',
+ ' [ "$exact" = 1 ] && return 1',
+ ' for f in "$S/$name"*; do [ -e "$f" ] || continue; b=$(basename "$f"); name="${b%.stuck}"; return 0; done',
+ ' return 1',
+ '}',
+ 'case "$cmd" in',
+ ' list-panes) for f in "$S"/*; do [ -e "$f" ] || continue; b=$(basename "$f"); b="${b%.stuck}"; echo "$b|$(cat "$f")"; done; exit 0;;',
+ ' kill-session) resolve || exit 1; [ -e "$S/$name.stuck" ] && exit 0; rm -f "$S/$name"; exit 0;;',
+ ' has-session) resolve && exit 0; exit 1;;',
+ 'esac',
+ 'exit 1'
+ ].join('\n'),
+ 0o755
+ )
+ // A fake node that answers `team --help`, `team … status --json` and echoes argv + stdin for other verbs.
+ write(
+ path.join(bin, 'node'),
+ [
+ '#!/bin/sh',
+ 'shift', // main.cjs
+ 'case "$*" in',
+ ` "team --help") printf 'usage: team <command>\\n init create\\n bootstrap --owner-key <key> set up\\n';;`,
+ ` *" status --json") printf '{\\n "enabled": true,\\n "off": null\\n}\\n';;`,
+ ` *" --no-newline") printf '{"a":1}';;`,
+ ` *) printf '{"argv":"%s","stdin":"%s"}\\n' "$*" "$(cat | tr -d '\\n"')";;`,
+ 'esac'
+ ].join('\n'),
+ 0o755
+ )
+ const main = path.join(home, '.nodeterm-server-app', 'out', 'server', 'main.cjs')
+ write(main, '')
+ write(
+ path.join(home, '.config', 'systemd', 'user', 'nodeterm-server.service'),
+ `[Service]\nEnvironment=NODETERM_HEADLESS=1\nExecStart=${path.join(bin, 'node')} ${main}\n`
+ )
+ write(path.join(home, '.nodeterm-server', 'install-meta.json'), '{"commit":"abc1234","installedAt":"x","version":"0.4.0"}\n')
+})
+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }))
+
+const sh = async (command: string, stdin?: string): Promise<string> => {
+ const p = run('/bin/sh', ['-c', command], { env: { HOME: home, PATH: `${bin}:/usr/bin:/bin` } })
+ if (stdin !== undefined) p.child.stdin?.end(stdin)
+ return (await p).stdout
+}
+
+describe.skipIf(process.platform === 'win32')('share-team remote shell (real /bin/sh, fake host)', () => {
+ it('probes a user install: unit, node, main, data dir, meta, bootstrap verb, status, real cwd, panes', async () => {
+ fs.writeFileSync(path.join(state, 'nt-term-a'), 'claude')
+ fs.writeFileSync(path.join(state, 'nt-term-b'), 'bash')
+ const p = parseShareProbe(await sh(shareProbeCommand('~/proj')))
+ if ('error' in p) throw new Error(p.error)
+ expect(p).toMatchObject({
+ os: 'Linux', uid: 1000, user: 'alice', home, unit: 'user', node: path.join(bin, 'node'),
+ dataDir: path.join(home, '.nodeterm-server'), meta: { version: '0.4.0', commit: 'abc1234' },
+ hasBootstrap: true, statusRc: 0, teamExists: true, adoptCwd: fs.realpathSync(path.join(home, 'proj')),
+ have: { git: true, curl: expect.any(Boolean) } // curl is whatever /usr/bin holds on the test machine
+ })
+ expect(p.panes).toEqual(expect.arrayContaining([{ session: 'nt-term-a', command: 'claude' }, { session: 'nt-term-b', command: 'bash' }]))
+ fs.rmSync(path.join(state, 'nt-term-a'))
+ fs.rmSync(path.join(state, 'nt-term-b'))
+ })
+ // The system unit is an absolute host path, and a test machine may well run nodeterm-server as a
+ // system service itself, so these point the check into the fake tree.
+ it('a host with nothing installed and a missing folder', async () => {
+ const bare = path.join(dir, 'bare-home')
+ fs.mkdirSync(bare, { recursive: true })
+ const cmd = shareProbeCommand('~/nope', path.join(dir, 'etc', 'no-such.service'))
+ const out = (await run('/bin/sh', ['-c', cmd], { env: { HOME: bare, PATH: `${bin}:/usr/bin:/bin` } })).stdout
+ const p = parseShareProbe(out)
+ if ('error' in p) throw new Error(p.error)
+ expect(p).toMatchObject({ unit: 'none', node: '', main: '', hasBootstrap: false, statusRc: null, adoptCwd: null, meta: null })
+ })
+ it('a system unit with no user unit is reported as system', async () => {
+ const bare = path.join(dir, 'sys-home')
+ fs.mkdirSync(bare, { recursive: true })
+ const unit = path.join(dir, 'etc', 'nodeterm-server.service')
+ write(unit, '[Service]\nExecStart=/usr/bin/node /opt/nodeterm/out/server/main.cjs\n')
+ const out = (await run('/bin/sh', ['-c', shareProbeCommand('~', unit)], { env: { HOME: bare, PATH: `${bin}:/usr/bin:/bin` } })).stdout
+ const p = parseShareProbe(out)
+ if ('error' in p) throw new Error(p.error)
+ expect(p).toMatchObject({ unit: 'system', node: '', main: '', adoptCwd: fs.realpathSync(bare) })
+ })
+ it('a cut-off probe is an error, never a half-filled probe', () => {
+ expect(parseShareProbe("##NTP 1\n##OS Linux\n")).toMatchObject({ error: expect.any(String) })
+ expect(parseShareProbe('')).toMatchObject({ error: expect.any(String) })
+ // Cut after the unit line, and cut inside a block: neither reached ##END.
+ expect(parseShareProbe('##NTP 1\n##OS Linux\n##UNIT none\n##CWD /p\n')).toMatchObject({ error: expect.any(String) })
+ expect(parseShareProbe('##NTP 1\n##UNIT none\n##CWD /p\n##PANES\nnt-a|bash\n')).toMatchObject({ error: expect.any(String) })
+ expect(parseShareProbe('##NTP 1\n##UNIT bogus\n##END\n')).toMatchObject({ error: expect.any(String) })
+ })
+ it('a hostile folder name cannot inject shell', async () => {
+ const out = await sh(shareProbeCommand("~/x'; touch /tmp/nt-pwned-$$; '"))
+ expect('error' in parseShareProbe(out)).toBe(false)
+ expect(fs.readdirSync('/tmp').some((f) => f.startsWith('nt-pwned-'))).toBe(false)
+ // Unquoted breakouts too: a separator and a command substitution in the folder name.
+ for (const [name, marker] of [
+ [`~/x; touch ${path.join(dir, 'pwned-a')}`, 'pwned-a'],
+ [`/x$(touch ${path.join(dir, 'pwned-b')})`, 'pwned-b'],
+ ['~/x`touch ' + path.join(dir, 'pwned-c') + '`', 'pwned-c']
+ ]) {
+ const p = parseShareProbe(await sh(shareProbeCommand(name)))
+ expect(p).toMatchObject({ adoptCwd: null })
+ expect(fs.existsSync(path.join(dir, marker))).toBe(false)
+ }
+ })
+ it('runs the team CLI with argv quoted and stdin passed, fenced so login noise cannot corrupt it', async () => {
+ const cmd = teamCliCommand({ node: path.join(bin, 'node'), main: '/x/main.cjs', dataDir: '/d d' }, ['resume', '--project', "p'1", '--json'])
+ const r = parseTeamCliOutput('motd line\n' + (await sh(cmd, '[{"a":1}]')))
+ if ('error' in r) throw new Error(r.error)
+ expect(r.rc).toBe(0)
+ expect(r.body).toEqual({ argv: "team --data-dir /d d resume --project p'1 --json", stdin: '[{a:1}]' })
+ })
+ it('a non-JSON CLI reply is an error that quotes it (bounded)', () => {
+ expect(parseTeamCliOutput("##NTB\nboom\n##NTRC 1\n")).toMatchObject({ error: expect.stringContaining('boom') })
+ const long = parseTeamCliOutput(`##NTB\n${'x'.repeat(5000)}\n##NTRC 1\n`)
+ expect('error' in long && long.error.length < 400).toBe(true)
+ })
+ it('a quoted reply carries no control or text-direction characters', () => {
+ const r = parseTeamCliOutput('##NTB\nab\u202Ecd\u001b[31m\n##NTRC 1\n')
+ if (!('error' in r)) throw new Error('expected an error')
+ expect(r.error).toContain('ab cd [31m')
+ })
+ it('a pretty-printed multi-line success parses as one value; a reply without a final newline keeps its rc', async () => {
+ expect(parseTeamCliOutput('##NTB\n{\n "ok": true\n}\n\n##NTRC 0\n')).toEqual({ rc: 0, body: { ok: true } })
+ // The fake CLI prints its reply with no trailing newline: the rc marker must still land on its own line.
+ const cmd = teamCliCommand({ node: path.join(bin, 'node'), main: '/x/main.cjs', dataDir: '/d' }, ['info', '--no-newline'])
+ expect(parseTeamCliOutput(await sh(cmd))).toEqual({ rc: 0, body: { a: 1 } })
+ })
+ it('kills exactly the named sessions on nodeterm-rmt and verifies each; a dotted id maps through sessionName', async () => {
+ for (const s of ['nt-term-1', 'nt-term-a_1', 'nt-term-12', 'nt-term-stuck.stuck']) fs.writeFileSync(path.join(state, s), 'x')
+ const ids = ['term-1', 'term-a.1', 'term-stuck', 'term-never']
+ const r = parseKillVerify(await sh(killVerifyCommand(ids)), ids)
+ expect(r).toEqual([
+ { nodeId: 'term-1', state: 'gone' },
+ { nodeId: 'term-a.1', state: 'gone' },
+ { nodeId: 'term-stuck', state: 'alive' },
+ { nodeId: 'term-never', state: 'gone' }
+ ])
+ expect(fs.existsSync(path.join(state, 'nt-term-12'))).toBe(true) // exact target: a longer id is untouched
+ for (const f of fs.readdirSync(state)) fs.rmSync(path.join(state, f))
+ })
+ it('a node with no session is gone without touching a session whose name it prefixes', async () => {
+ fs.writeFileSync(path.join(state, 'nt-term-9x'), 'x')
+ const r = parseKillVerify(await sh(killVerifyCommand(['term-9'])), ['term-9'])
+ expect(r).toEqual([{ nodeId: 'term-9', state: 'gone' }])
+ expect(fs.existsSync(path.join(state, 'nt-term-9x'))).toBe(true)
+ fs.rmSync(path.join(state, 'nt-term-9x'))
+ })
+ it('a host where tmux cannot run reports every node unknown, never gone', async () => {
+ const noTmux = path.join(dir, 'bin-notmux')
+ fs.mkdirSync(noTmux, { recursive: true })
+ write(path.join(noTmux, 'tmux'), '#!/bin/sh\nexit 127\n', 0o755)
+ const out = (await run('/bin/sh', ['-c', killVerifyCommand(['term-1'])], { env: { HOME: home, PATH: `${noTmux}:/usr/bin:/bin` } })).stdout
+ expect(parseKillVerify(out, ['term-1'])).toEqual([{ nodeId: 'term-1', state: 'unknown' }])
+ })
+ it('a kill reply missing a node is unknown for that node; a cut-off reply is an error', () => {
+ expect(parseKillVerify("##NTK\n##K nt-a gone\n##NTKEND\n", ['a', 'b'])).toEqual([
+ { nodeId: 'a', state: 'gone' }, { nodeId: 'b', state: 'unknown' }
+ ])
+ expect(parseKillVerify("##NTK\n##K nt-a gone\n", ['a'])).toMatchObject({ error: expect.any(String) })
+ })
+ it('maps panes to node ids through sessionName', () => {
+ expect(paneCommandsByNode([{ session: 'nt-term-a_1', command: 'npm' }], ['term-a.1', 'term-b'])).toEqual({ 'term-a.1': 'npm' })
+ })
+ it('the install script downloads to a temp file (a curl failure is an error, not an empty bash run)', () => {
+ expect(SHARE_INSTALL_SCRIPT).toContain(SERVER_INSTALL_URL)
+ expect(SHARE_INSTALL_SCRIPT).not.toMatch(/\|\s*bash/)
+ })
+ it('the install script runs the download, passes its exit code through and removes the temp file', async () => {
+ const curlBin = path.join(dir, 'bin-curl')
+ const tmp = path.join(dir, 'install-tmp')
+ fs.mkdirSync(tmp, { recursive: true })
+ write(
+ path.join(curlBin, 'curl'),
+ [
+ '#!/bin/sh',
+ 'out=""; url=""',
+ 'while [ $# -gt 0 ]; do case "$1" in -o) shift; out="$1";; -*) ;; *) url="$1";; esac; shift; done',
+ '[ -n "$FAKE_CURL_FAIL" ] && exit 22',
+ `printf 'echo "installer from %s"; exit 3\\n' "$url" > "$out"`
+ ].join('\n'),
+ 0o755
+ )
+ const runInstall = async (fail: boolean): Promise<{ code: number; stdout: string; stderr: string }> => {
+ const env = { HOME: home, TMPDIR: tmp, PATH: `${curlBin}:/usr/bin:/bin`, ...(fail ? { FAKE_CURL_FAIL: '1' } : {}) }
+ try {
+ const r = await run('/bin/sh', ['-c', SHARE_INSTALL_SCRIPT], { env })
+ return { code: 0, stdout: r.stdout, stderr: r.stderr }
+ } catch (e) {
+ const err = e as { code: number; stdout: string; stderr: string }
+ return { code: err.code, stdout: err.stdout, stderr: err.stderr }
+ }
+ }
+ const ok = await runInstall(false)
+ expect(ok).toMatchObject({ code: 3, stdout: `installer from ${SERVER_INSTALL_URL}\n` })
+ const failed = await runInstall(true)
+ expect(failed.code).toBe(1)
+ expect(failed.stdout).toBe('')
+ expect(failed.stderr).toContain('could not download the installer')
+ expect(fs.readdirSync(tmp)).toEqual([])
+ })
+})
diff --git a/src/core/remote-ssh/share-team-remote.ts b/src/core/remote-ssh/share-team-remote.ts
new file mode 100644
index 000000000..c74f15740
--- /dev/null
+++ b/src/core/remote-ssh/share-team-remote.ts
@@ -0,0 +1,302 @@
+// The remote half of the desktop's "Share with team": every command it runs on the SSH host,
+// generated here and run over the project's ControlMaster by src/main. Generated shell no compiler
+// checks, so share-team-remote.test.ts runs each one under a real /bin/sh against a fake host.
+// Rules:
+// - every script runs under `sh -c '…'`, never the login shell, which may be zsh or fish;
+// - fence markers are printed QUOTED, because an unquoted `#` starts a comment;
+// - paths are quoted;
+// - session names come only from `sessionName`;
+// - kills target `=nt-<id>` exactly, on `nodeterm-rmt` ONLY. That is this desktop's socket. The
+// server core's `node-terminal` sessions are the ones being resumed, so the every-socket kill
+// used elsewhere would stop exactly the sessions the handover exists to start.
+import { posixQuote, quoteRemotePath, remoteTmuxPathPrologue } from '../../shared/ssh'
+import type { ShareProbe } from '../../shared/share-team'
+import { RMT_TMUX_SOCKET } from './control-master'
+import { sessionName } from '../tmux-naming'
+import { CONTROL_RE } from '../relay/team-admin'
+
+export const SERVER_INSTALL_URL = 'https://raw.githubusercontent.com/eneskirca/nodeterm/main/scripts/install-server.sh'
+/** Where a root-installed nodeterm-server's unit lives (the installer's system mode). */
+const SYSTEM_UNIT_PATH = '/etc/systemd/system/nodeterm-server.service'
+/** The most of `team status --json` the probe carries back; the reply is a few hundred bytes. */
+const STATUS_MAX = 65536
+/** The most of a non-JSON team reply quoted in an error. */
+const SHOWN_MAX = 300
+const CONTROL_G = new RegExp(CONTROL_RE.source, 'gu')
+const sh = (script: string): string => `sh -c ${posixQuote(script)}`
+
+/** The official installer, downloaded first: `curl … | bash` runs an EMPTY script and exits 0 when
+ * the download fails (no pipefail), so a failed download would look like a successful install. */
+export const SHARE_INSTALL_SCRIPT = [
+ 'f=$(mktemp) || exit 1',
+ `if ! curl -fsSL ${posixQuote(SERVER_INSTALL_URL)} -o "$f"; then rm -f "$f"; echo 'nodeterm: could not download the installer.' >&2; exit 1; fi`,
+ 'bash "$f"; rc=$?',
+ 'rm -f "$f"',
+ 'exit $rc'
+].join('\n')
+
+/**
+ * One round trip that tells `sharePlan` everything: the OS and login, whether git/curl exist, which
+ * unit runs nodeterm-server and with which node + main.cjs + data dir, the install meta, whether
+ * that build knows `team bootstrap`, whether the CLI answers `team status`, the project folder's
+ * real path, and the live panes on this desktop's remote tmux socket. Read by `parseShareProbe`.
+ *
+ * `systemUnit` exists so a test can point the system-unit check at a fake host tree; the only
+ * production value is the default.
+ */
+export function shareProbeCommand(remoteCwd: string, systemUnit: string = SYSTEM_UNIT_PATH): string {
+ return sh(
+ [
+ // `set -- $X` below splits the unit's ExecStart into words; it must never glob them.
+ 'set -f',
+ "echo '##NTP 1'",
+ `printf '##OS %s\\n' "$(uname -s 2>/dev/null)"`,
+ `printf '##UID %s\\n' "$(id -u 2>/dev/null)"`,
+ `printf '##USER %s\\n' "$(id -un 2>/dev/null)"`,
+ `printf '##HOME %s\\n' "$HOME"`,
+ `for t in git curl; do if command -v "$t" >/dev/null 2>&1; then printf '##HAVE %s yes\\n' "$t"; else printf '##HAVE %s no\\n' "$t"; fi; done`,
+ 'U="$HOME/.config/systemd/user/nodeterm-server.service"',
+ "NODE=''; MAIN=''; DD=''",
+ 'if [ -r "$U" ]; then',
+ " echo '##UNIT user'",
+ ` X=$(sed -n 's/^ExecStart=//p' "$U" | head -n 1)`,
+ ' set -- $X',
+ ' NODE=${1:-}; MAIN=${2:-}',
+ ` DD=$(sed -n 's/^Environment=NODETERM_DATA_DIR=//p' "$U" | head -n 1)`,
+ `elif [ -e ${posixQuote(systemUnit)} ]; then`,
+ " echo '##UNIT system'",
+ 'else',
+ " echo '##UNIT none'",
+ 'fi',
+ '[ -n "$DD" ] || DD="$HOME/.nodeterm-server"',
+ `printf '##NODE %s\\n' "$NODE"`,
+ `printf '##MAIN %s\\n' "$MAIN"`,
+ `printf '##DATADIR %s\\n' "$DD"`,
+ `if [ -r "$DD/install-meta.json" ]; then echo '##META'; head -c 4096 "$DD/install-meta.json"; echo; echo '##METAEND'; fi`,
+ 'if [ -n "$NODE" ] && [ -x "$NODE" ] && [ -r "$MAIN" ]; then',
+ ` if "$NODE" "$MAIN" team --help 2>/dev/null | grep -q '^ bootstrap '; then echo '##BOOTSTRAP yes'; else echo '##BOOTSTRAP no'; fi`,
+ ' S=$("$NODE" "$MAIN" team --data-dir "$DD" status --json 2>/dev/null); RC=$?',
+ ` printf '##STATUSRC %s\\n' "$RC"`,
+ ` echo '##STATUS'; printf '%s\\n' "$S" | head -c ${STATUS_MAX}; echo; echo '##STATUSEND'`,
+ 'else',
+ " echo '##BOOTSTRAP no'",
+ 'fi',
+ `if cd ${quoteRemotePath(remoteCwd)} 2>/dev/null; then printf '##CWD %s\\n' "$(pwd -P)"; else echo '##CWD'; fi`,
+ `${remoteTmuxPathPrologue()}echo '##PANES'; tmux -L ${RMT_TMUX_SOCKET} list-panes -a -F '#{session_name}|#{pane_current_command}' 2>/dev/null; echo '##PANESEND'`,
+ "echo '##END'"
+ ].join('\n')
+ )
+}
+
+const PROBE_CUT = 'The host did not finish the probe.'
+const PANE_SESSION_RE = /^nt-[A-Za-z0-9_-]+$/
+type ProbeBlock = 'meta' | 'status' | 'panes'
+const BLOCK_START: Record<string, ProbeBlock> = { '##META': 'meta', '##STATUS': 'status', '##PANES': 'panes' }
+const BLOCK_END: Record<ProbeBlock, string> = { meta: '##METAEND', status: '##STATUSEND', panes: '##PANESEND' }
+
+const parseJson = (text: string): unknown => {
+ try {
+ return JSON.parse(text)
+ } catch {
+ return undefined
+ }
+}
+const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
+
+/** Read `shareProbeCommand`'s reply. Login noise before `##NTP 1` is skipped; a reply that never
+ * reaches `##END` (a dropped channel, a timeout) is an error, never a half-filled probe that
+ * `sharePlan` would read as "nothing installed". */
+export function parseShareProbe(stdout: string): ShareProbe | { error: string } {
+ const lines = stdout.split('\n')
+ const start = lines.indexOf('##NTP 1')
+ if (start < 0) return { error: PROBE_CUT }
+ const probe: ShareProbe = {
+ os: '',
+ uid: null,
+ user: '',
+ home: '',
+ have: { git: false, curl: false },
+ unit: 'none',
+ node: '',
+ main: '',
+ dataDir: '',
+ meta: null,
+ hasBootstrap: false,
+ statusRc: null,
+ teamExists: false,
+ adoptCwd: null,
+ panes: []
+ }
+ let unitSeen = false
+ let done = false
+ let block: ProbeBlock | null = null
+ let body: string[] = []
+ for (const line of lines.slice(start + 1)) {
+ if (block) {
+ if (line !== BLOCK_END[block]) {
+ body.push(line)
+ continue
+ }
+ if (block === 'meta') {
+ const m = parseJson(body.join('\n'))
+ probe.meta =
+ isRecord(m) && typeof m.version === 'string' && typeof m.commit === 'string'
+ ? { version: m.version, commit: m.commit }
+ : null
+ } else if (block === 'status') {
+ const s = parseJson(body.join('\n').trim())
+ const off = isRecord(s) && isRecord(s.off) ? s.off : null
+ probe.teamExists = isRecord(s) && (s.enabled === true || (off !== null && off.reason !== undefined && off.reason !== 'no-team'))
+ } else {
+ for (const row of body) {
+ const bar = row.indexOf('|')
+ if (bar < 0) continue
+ const session = row.slice(0, bar)
+ if (PANE_SESSION_RE.test(session)) probe.panes.push({ session, command: row.slice(bar + 1) })
+ }
+ }
+ block = null
+ body = []
+ continue
+ }
+ if (line === '##END') {
+ done = true
+ break
+ }
+ if (BLOCK_START[line]) {
+ block = BLOCK_START[line]
+ continue
+ }
+ const space = line.indexOf(' ')
+ const tag = space < 0 ? line : line.slice(0, space)
+ const value = space < 0 ? '' : line.slice(space + 1)
+ switch (tag) {
+ case '##OS':
+ probe.os = value
+ break
+ case '##UID': {
+ const n = Number.parseInt(value, 10)
+ probe.uid = Number.isNaN(n) ? null : n
+ break
+ }
+ case '##USER':
+ probe.user = value
+ break
+ case '##HOME':
+ probe.home = value
+ break
+ case '##HAVE': {
+ const m = /^(git|curl) (yes|no)$/.exec(value)
+ if (m) probe.have[m[1] as 'git' | 'curl'] = m[2] === 'yes'
+ break
+ }
+ case '##UNIT':
+ if (value !== 'user' && value !== 'system' && value !== 'none') return { error: `The host reported an unknown service kind: ${shown(value)}` }
+ probe.unit = value
+ unitSeen = true
+ break
+ case '##NODE':
+ probe.node = value
+ break
+ case '##MAIN':
+ probe.main = value
+ break
+ case '##DATADIR':
+ probe.dataDir = value
+ break
+ case '##BOOTSTRAP':
+ probe.hasBootstrap = value === 'yes'
+ break
+ case '##STATUSRC': {
+ const n = Number.parseInt(value, 10)
+ probe.statusRc = Number.isNaN(n) ? null : n
+ break
+ }
+ case '##CWD':
+ probe.adoptCwd = value === '' ? null : value
+ break
+ }
+ }
+ // `##UNIT` is printed unconditionally, so a reply without it was cut short however it ended.
+ if (!done || !unitSeen) return { error: PROBE_CUT }
+ return probe
+}
+
+/** Run `main.cjs team --data-dir <dir> <args…>` with every word quoted. Anything the caller pipes
+ * in reaches the CLI's stdin (the resume list travels there, never on argv). The reply is fenced
+ * so a login banner cannot be mistaken for it; the exit code rides its own marker line, after a
+ * newline so a reply without a trailing one cannot swallow it. */
+export function teamCliCommand(p: Pick<ShareProbe, 'node' | 'main' | 'dataDir'>, args: readonly string[]): string {
+ const argv = [p.node, p.main, 'team', '--data-dir', p.dataDir, ...args].map(posixQuote).join(' ')
+ return sh(`echo '##NTB'; ${argv}; rc=$?; printf '\\n##NTRC %s\\n' "$rc"`)
+}
+
+/** Strip what must never reach the screen (controls, text-direction overrides) and bound it. */
+const shown = (text: string): string => text.replace(CONTROL_G, ' ').slice(0, SHOWN_MAX)
+
+/** Read `teamCliCommand`'s reply. The body is everything between the fences, parsed as ONE JSON
+ * value: a refusal is a single line, a success is pretty-printed over several. */
+export function parseTeamCliOutput(stdout: string): { rc: number; body: unknown } | { error: string } {
+ const lines = stdout.split('\n')
+ const start = lines.indexOf('##NTB')
+ const end = start < 0 ? -1 : lines.findIndex((l, i) => i > start && l.startsWith('##NTRC '))
+ if (start < 0 || end < 0) return { error: 'The host did not finish running the team command.' }
+ const rc = Number.parseInt(lines[end].slice('##NTRC '.length), 10)
+ const text = lines.slice(start + 1, end).join('\n').trim()
+ try {
+ return { rc: Number.isNaN(rc) ? 1 : rc, body: JSON.parse(text) }
+ } catch {
+ return { error: `The server answered something that is not JSON: ${shown(text) || '(nothing)'}` }
+ }
+}
+
+/**
+ * Stop each node's session on this desktop's remote tmux socket and check that it is gone. Every
+ * target is exact (`=nt-<id>`): without `=` tmux falls back to prefix matching on a miss, and
+ * `nt-…-1` is a prefix of `nt-…-12`. `has-session` exiting 1 means "gone" — tmux answers 1 both
+ * for "can't find session" and for "no server running", and either way nothing is running there.
+ * Any other code (126/127: tmux could not run) is "unknown", and only a `gone` node is resumed.
+ */
+export function killVerifyCommand(nodeIds: readonly string[]): string {
+ const body = nodeIds.map((id) => {
+ const t = posixQuote(`=${sessionName(id)}`)
+ const n = posixQuote(sessionName(id))
+ return [
+ `tmux -L ${RMT_TMUX_SOCKET} kill-session -t ${t} >/dev/null 2>&1`,
+ `tmux -L ${RMT_TMUX_SOCKET} has-session -t ${t} >/dev/null 2>&1; r=$?`,
+ `case $r in 0) s=alive;; 1) s=gone;; *) s=unknown;; esac; printf '##K %s %s\\n' ${n} "$s"`
+ ].join('\n')
+ })
+ return sh([`${remoteTmuxPathPrologue()}echo '##NTK'`, ...body, "echo '##NTKEND'"].join('\n'))
+}
+
+export type KillVerifyState = 'gone' | 'alive' | 'unknown'
+
+/** Read `killVerifyCommand`'s reply: one state per requested node, in request order. A node the
+ * reply does not mention is `unknown`; a reply that never reaches its end marker is an error. */
+export function parseKillVerify(
+ stdout: string,
+ nodeIds: readonly string[]
+): Array<{ nodeId: string; state: KillVerifyState }> | { error: string } {
+ const lines = stdout.split('\n')
+ const start = lines.indexOf('##NTK')
+ const end = start < 0 ? -1 : lines.indexOf('##NTKEND', start + 1)
+ if (start < 0 || end < 0) return { error: 'The host did not finish stopping the sessions.' }
+ const states = new Map<string, KillVerifyState>()
+ for (const l of lines.slice(start + 1, end)) {
+ const m = /^##K (\S+) (gone|alive|unknown)$/.exec(l)
+ if (m) states.set(m[1], m[2] as KillVerifyState)
+ }
+ return nodeIds.map((nodeId) => ({ nodeId, state: states.get(sessionName(nodeId)) ?? 'unknown' }))
+}
+
+/** Map probe panes onto node ids (session names come only from `sessionName`). */
+export function paneCommandsByNode(panes: ShareProbe['panes'], nodeIds: readonly string[]): Record<string, string> {
+ const bySession = new Map(panes.map((p) => [p.session, p.command]))
+ const out: Record<string, string> = {}
+ for (const id of nodeIds) {
+ const c = bySession.get(sessionName(id))
+ if (c !== undefined) out[id] = c
+ }
+ return out
+}
diff --git a/src/shared/share-team.test.ts b/src/shared/share-team.test.ts
index b7775a8ac..efba9dd4c 100644
--- a/src/shared/share-team.test.ts
+++ b/src/shared/share-team.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { parseResumeSessions, RESUME_MAX_SESSIONS } from './share-team'
+import { parseResumeSessions, RESUME_MAX_SESSIONS, sharePlan, SHARE_REFUSAL, type ShareProbe } from './share-team'
describe('parseResumeSessions', () => {
it('accepts a list of entries and keeps only the known string fields', () => {
@@ -16,3 +16,31 @@ describe('parseResumeSessions', () => {
expect(parseResumeSessions(many)).toMatch(/at most/)
})
})
+
+const probe = (o: Partial<ShareProbe> = {}): ShareProbe => ({
+ os: 'Linux', uid: 1000, user: 'u', home: '/home/u', have: { git: true, curl: true }, unit: 'user',
+ node: '/usr/bin/node', main: '/home/u/.nodeterm-server-app/out/server/main.cjs', dataDir: '/home/u/.nodeterm-server',
+ meta: { version: '0.4.0', commit: 'abc' }, hasBootstrap: true, statusRc: 0, teamExists: false,
+ adoptCwd: '/home/u/proj', panes: [], ...o
+})
+
+describe('sharePlan', () => {
+ it('ready when installed, new enough and answering', () => expect(sharePlan(probe())).toEqual({ kind: 'ready' }))
+ it('refusals come first, in this order: non-Linux, root, system install, missing folder', () => {
+ expect(sharePlan(probe({ os: 'Darwin', uid: 0 }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.nonLinux })
+ expect(sharePlan(probe({ uid: 0, unit: 'system' }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.root })
+ expect(sharePlan(probe({ unit: 'system' }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.system })
+ expect(sharePlan(probe({ adoptCwd: null }))).toEqual({ kind: 'refuse', reason: SHARE_REFUSAL.noFolder })
+ })
+ it('install when missing, outdated (no bootstrap verb) or not running', () => {
+ expect(sharePlan(probe({ unit: 'none', node: '', main: '' }))).toEqual({ kind: 'install', reason: 'missing' })
+ expect(sharePlan(probe({ hasBootstrap: false }))).toEqual({ kind: 'install', reason: 'outdated' })
+ expect(sharePlan(probe({ statusRc: 1 }))).toEqual({ kind: 'install', reason: 'not-running' })
+ })
+ it('an install that needs git or curl the host lacks is a refusal naming them', () => {
+ expect(sharePlan(probe({ unit: 'none', node: '', main: '', have: { git: false, curl: false } }))).toEqual({
+ kind: 'refuse', reason: 'Installing nodeterm-server needs git and curl on the host (missing: git, curl).'
+ })
+ expect(sharePlan(probe({ have: { git: false, curl: true } }))).toEqual({ kind: 'ready' }) // a ready host needs neither
+ })
+})
diff --git a/src/shared/share-team.ts b/src/shared/share-team.ts
index 11a19d6ca..e53aec1d2 100644
--- a/src/shared/share-team.ts
+++ b/src/shared/share-team.ts
@@ -69,3 +69,68 @@ export function parseResumeSessions(raw: unknown): ResumeEntry[] | string {
}
return out
}
+
+/** What the desktop learns about the SSH host before it shares a project there, read by one
+ * generated probe script (`core/remote-ssh/share-team-remote.ts`). */
+export interface ShareProbe {
+ os: string
+ uid: number | null
+ user: string
+ home: string
+ have: { git: boolean; curl: boolean }
+ /** Which systemd unit runs nodeterm-server: the user's own, a root system service, or none. */
+ unit: 'user' | 'system' | 'none'
+ /** The node binary and `main.cjs` the user unit runs ('' when there is no user unit). */
+ node: string
+ main: string
+ dataDir: string
+ meta: { version: string; commit: string } | null
+ /** The installed server knows `team bootstrap` (an older one must be updated first). */
+ hasBootstrap: boolean
+ /** `team status --json` exit code; null = the CLI could not be run at all. */
+ statusRc: number | null
+ teamExists: boolean
+ /** realpath of the SSH project's remoteCwd on the host; null = it does not exist. */
+ adoptCwd: string | null
+ /** Live panes on this desktop's own remote tmux socket (`nt-*` sessions only; a session with
+ * several panes appears once per pane). */
+ panes: Array<{ session: string; command: string }>
+}
+export type SharePlan =
+ | { kind: 'ready' }
+ | { kind: 'install'; reason: 'missing' | 'outdated' | 'not-running' }
+ | { kind: 'refuse'; reason: string }
+
+/** The most terminal nodes one share hands over. */
+export const SHARE_MAX_TERMINALS = 200
+
+export const SHARE_REFUSAL = Object.freeze({
+ root: 'This SSH login is root. Share with team runs nodeterm-server as your own user, so log in to the project as a regular user and try again.',
+ system: 'This host runs nodeterm-server as a system service (root). Share with team needs a per-user install; see docs/hosted-team-relay.md.',
+ nonLinux: 'Share with team needs a Linux host (nodeterm-server runs on Linux).',
+ noFolder: 'The project folder does not exist on the host.'
+})
+
+/** Decide from a probe whether the host can take the share now, needs the installer first, or
+ * cannot take it at all. Refusals come first: installing on a host we would refuse anyway is
+ * wasted minutes. git and curl matter only when the installer has to run. */
+export function sharePlan(p: ShareProbe): SharePlan {
+ if (p.os !== 'Linux') return { kind: 'refuse', reason: SHARE_REFUSAL.nonLinux }
+ if (p.uid === 0) return { kind: 'refuse', reason: SHARE_REFUSAL.root }
+ if (p.unit === 'system') return { kind: 'refuse', reason: SHARE_REFUSAL.system }
+ if (p.adoptCwd === null) return { kind: 'refuse', reason: SHARE_REFUSAL.noFolder }
+ const reason: 'missing' | 'outdated' | 'not-running' | null =
+ p.unit === 'none' || !p.node || !p.main
+ ? 'missing'
+ : !p.hasBootstrap
+ ? 'outdated'
+ : p.statusRc !== 0
+ ? 'not-running'
+ : null
+ if (reason === null) return { kind: 'ready' }
+ const missing = [...(p.have.git ? [] : ['git']), ...(p.have.curl ? [] : ['curl'])]
+ if (missing.length) {
+ return { kind: 'refuse', reason: `Installing nodeterm-server needs git and curl on the host (missing: ${missing.join(', ')}).` }
+ }
+ return { kind: 'install', reason }
+}