fix(adopt): never drive, write to, or answer for a session we did not start

Review items 3, 4 and the smaller ones on #510. An adopted session wraps a
process someone else launched, and its mode is whatever the probe saw — very
often `claude`. Every guard below is therefore its own `isAdopted` check rather
than a side effect of the external-CLI rule: the two ask different questions,
and merging them means the day the first loosens, Codeman starts acting on a
live conversation that is not ours.

- The boot workspace-hook sweep skipped only non-claude and `session.remote`.
  An adopted session keeps its connection on `adopt.remote` / `adopt.docker`,
  so a tab wrapping someone's in-container or over-ssh claude looked local and
  Codeman wrote `.claude/settings.local.json` into their repo on every restart.
- The workspace-trust auto-accept read the pane and pressed keys for 90s after
  `startInteractive()`. In an adopted pane that is someone else's dialog, and
  boot recovery re-opens the window on every restart.
- Auto-clear, auto-compact, auto-resume and the Ralph auto-enable in
  `POST /interactive` all drove the pane. Each now refuses with its own gate.
- The wrapper's `workingDir` was the foreign pane's cwd. That cwd can carry
  characters outside SAFE_PATH_PATTERN (`~/c++`, `Program Files (x86)`), which
  makes `createSession` throw so the tab never starts, and for a container or
  ssh candidate it is not a path on this host at all. It is now a neutral local
  `/tmp`, the same cwd `resolveMuxAttachCwd` already gives the pane; the foreign
  cwd stays on `adopt.paneCurrentPath` for display.
- The CLI signature table hardcoded ids, which CLAUDE.md forbids outside
  `stock.ts`, and had already gone stale: `omp` was missing, so a hand-started
  omp pane read as `shell`. It is now derived from each entry's
  `discovery.binaries` at call time, regex-escaped, longest name first. Stock
  entries only, since `SessionMode` is the closed union of stock ids.
- The descendant walk now passes `onTruncated`. A capped walk returns "nothing
  matched", which is byte-identical to the answer for a real shell.
- The home screen's wide scan is one-shot. Riding `docker exec` and a full ssh
  handshake per target, each with a ~12s timeout, on the 8s poll stacked
  connections on a slow host. Wide rows are kept apart and merged, because a
  local-only payload cannot contain them.
- Adoption failures report the server's own message. `_apiJson` folds a non-2xx
  to null, which collapsed "could not reach it just now" into "that session is
  gone" and reported a live remote session as deleted on every link flicker.

Tests: route tests for the refusals, the admin gate, the 404 re-resolve, the
one-wrapper-per-target reuse and the adopt round-trip; unit tests for the two
non-HTTP guards, the registry-derived signatures, truncation reporting and the
frontend's scan and error paths. Each guard was removed in turn to confirm its
own tests go red.
This commit is contained in:
d fei committed 2026-09-30 23:29:54 -07:00
1 parent aec4867821
commit 09ccffd32e
11 files changed
+954 -46

No files matched your search

+92 -1
View File
@@ -6,7 +6,7 @@
* would quietly undo. Each one has a comment naming what actually went wrong.
*/
import { describe, it, expect } from 'vitest';
import { describe, it, expect, vi } from 'vitest';
import {
buildForeignProbeScript,
parseForeignProbeOutput,
@@ -20,7 +20,11 @@ import {
buildForeignDockerAttachCommand,
buildForeignRemoteAttachCommand,
buildForeignTmuxInvocation,
foreignCliSignatures,
} from '../src/foreign-tmux.js';
import { PROC_WALK_MAX_NODES } from '../src/proc-tree.js';
import { STOCK_CLIS } from '../src/config/cli-registry/stock.js';
import { hooksAvailableForMode, sessionHookOptions } from '../src/web/session-wait-registry.js';
// A probe transcript in exactly the shape a real run produces. The pane rows use
// the LITERAL backslash-t that tmux's `-F` emits (verified on next-3.7 and 3.3a),
@@ -385,3 +389,90 @@ describe('attach command builders', () => {
});
});
});
describe('foreignCliSignatures', () => {
it('covers every stock CLI that declares a binary — including the one the hand-written table missed', () => {
// The table this replaced listed eight CLI ids by hand and had already gone
// stale: `omp` shipped without a signature, so a hand-started omp pane was
// classified `shell`. Deriving from `discovery.binaries` makes that class of
// drift impossible rather than merely fixed once.
const covered = new Set(foreignCliSignatures().map((sig) => sig.mode));
const expected = STOCK_CLIS.filter((e) => e.discovery.binaries.length > 0).map((e) => e.id as string);
expect(expected).toContain('omp');
for (const id of expected) expect(covered).toContain(id);
});
it('leaves shell out — it declares no binary and is the FALLBACK answer', () => {
expect(foreignCliSignatures().some((sig) => sig.mode === 'shell')).toBe(false);
});
it('orders longest binary name first, so a two-letter name cannot win early', () => {
// `pi` matches `(^|/)pi(\s|$)`, which is the loosest rule in the table. If it
// were tried before `opencode`'s, nothing would break on these two names, but
// the ordering is the only thing standing between a future one-letter binary
// and every pane on the machine.
const names = foreignCliSignatures().map((sig) => sig.mode);
expect(names.indexOf('pi')).toBeGreaterThan(names.indexOf('opencode'));
});
it('classifies an omp pane as omp rather than shell', () => {
const empty = { byParent: new Map(), argvByPid: new Map() };
expect(classifyForeignPaneMode({ panePid: 1, paneCurrentCommand: 'omp' }, empty).mode).toBe('omp');
});
it('still finds claude under its own dot-directory node launcher', () => {
// The derived "node launcher" shape has to reproduce what claude's hand-written
// `[/\\]\.?claude[/\\][^\s]*cli\.js` rule covered, or every claude installed
// the normal way (a `node ~/.claude/local/.../cli.js` argv) silently reads as shell.
const argv = 'node /home/u/.claude/local/node_modules/@anthropic-ai/claude-code/cli.js';
const probe = { byParent: new Map([[7, [8]]]), argvByPid: new Map([[8, argv]]) };
expect(classifyForeignPaneMode({ panePid: 7, paneCurrentCommand: 'node' }, probe).mode).toBe('claude');
});
it('does not let a binary name match inside a longer command', () => {
const empty = { byParent: new Map(), argvByPid: new Map() };
expect(classifyForeignPaneMode({ panePid: 1, paneCurrentCommand: '/usr/bin/pip install x' }, empty).mode).toBe(
'shell'
);
});
});
describe('classifyForeignPaneMode truncation reporting', () => {
it('reports a truncated descendant walk instead of silently answering shell', () => {
// A capped walk returns "nothing matched", which is byte-identical to the
// answer for a real shell. Without the warning there is nothing anywhere to
// tell a wide process tree apart from a plain bash pane.
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
const byParent = new Map<number, number[]>();
byParent.set(
1,
Array.from({ length: PROC_WALK_MAX_NODES + 10 }, (_, i) => i + 100)
);
const result = classifyForeignPaneMode(
{ panePid: 1, paneCurrentCommand: 'bash' },
{ byParent, argvByPid: new Map() }
);
expect(result.mode).toBe('shell');
expect(warn).toHaveBeenCalled();
expect(String(warn.mock.calls[0]?.[0])).toMatch(/nodes cap|-nodes/);
} finally {
warn.mockRestore();
}
});
});
describe('hooksAvailableForMode for an adopted session', () => {
it('refuses claude when the process was adopted', () => {
// Adoption asks who STARTED the process. Codeman never installed its hooks
// block in that workspace, so answering by mode would dress an infinite wait
// up as a timeout.
expect(hooksAvailableForMode('claude')).toBe(true);
expect(hooksAvailableForMode('claude', { adopted: true })).toBe(false);
});
it('derives `adopted` from the session, so every call site inherits it', () => {
expect(sessionHookOptions({ adopt: { targetSession: 'work' } }).adopted).toBe(true);
expect(sessionHookOptions({}).adopted).toBe(false);
});
});