mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-16 11:19:33 +01:00
Merge #510 feat(adopt): adopt tmux sessions a human started, in all three locations
The attach line now takes the rule #770 gave remote and docker launches: bashCArg() single-quotes it at both respawn-pane sites, so it reaches bash verbatim. quoteAdoptLaunch is retired, since its double quotes kept the same $ and backtick safety but lost a real newline. #510's no-cd condition stays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
c65706a3e4
64 files changed
+5321
-103
No files matched your search
+167
-28
@@ -23,6 +23,13 @@
|
||||
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { collectDescendants } from './proc-tree.js';
|
||||
import {
|
||||
foreignViewSessionName,
|
||||
buildForeignDockerViewKillCommand,
|
||||
buildForeignAttachCommand,
|
||||
buildForeignDockerAttachCommand,
|
||||
buildForeignRemoteAttachCommand,
|
||||
} from './foreign-tmux.js';
|
||||
import { execSync, exec, execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
@@ -58,6 +65,7 @@ import {
|
||||
type OmpConfig,
|
||||
type SessionRemote,
|
||||
type SessionDocker,
|
||||
type SessionAdopt,
|
||||
type DockerCommandMode,
|
||||
type PaneExit,
|
||||
type StatusLineExporter,
|
||||
@@ -468,9 +476,10 @@ export function derivePaneCurrentPaths(
|
||||
*
|
||||
* Mirrors `Session.paneExitApplies`, which is where the rule is enforced. A
|
||||
* remote session's local pane holds the ssh client, a docker case's holds a
|
||||
* `docker exec` into the container's own tmux, and a record rebuilt from the
|
||||
* socket carries no provenance at all, so the session end forces all three to
|
||||
* UNKNOWN whatever tmux reports. A tick that sees only those has nothing to
|
||||
* `docker exec` into the container's own tmux, an ADOPTED session's holds a
|
||||
* `tmux attach` to a session a human started rather than the agent itself, and
|
||||
* a record rebuilt from the socket carries no provenance at all, so the session
|
||||
* end forces all four to UNKNOWN whatever tmux reports. A tick that sees only those has nothing to
|
||||
* learn, and `refreshPaneExits()` skips its tmux read rather than paying for
|
||||
* the answer.
|
||||
*
|
||||
@@ -483,6 +492,7 @@ export function hasObservablePaneSession(sessions: Iterable<MuxSession>): boolea
|
||||
for (const session of sessions) {
|
||||
if (session.remote) continue;
|
||||
if (session.docker) continue;
|
||||
if (session.adopt) continue;
|
||||
if (session.discovered === true) continue;
|
||||
return true;
|
||||
}
|
||||
@@ -1907,6 +1917,45 @@ function buildRemoteSessionCommand(options: {
|
||||
return buildRemoteLaunchCommand(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* ADOPTION — the pane command for a wrapper session around a tmux session a
|
||||
* human started. Sibling of `buildRemoteSessionCommand` and
|
||||
* `buildDockerLaunchCommand`, and the same shape of decision: the wrapper is an
|
||||
* ordinary `codeman-<8hex>` session on OUR socket, and only what runs INSIDE its
|
||||
* pane differs per location.
|
||||
*
|
||||
* That indirection is what makes adoption safe by construction rather than by
|
||||
* discipline: `killSession` only ever kills the wrapper on our own socket, so
|
||||
* there is no shape of caller bug that reaches the foreign server with a
|
||||
* `kill-session`. It is the same reasoning that keeps a non-owned REMOTE session
|
||||
* safe (see the detach-not-kill early return in `killSession`).
|
||||
*/
|
||||
export function buildAdoptSessionCommand(adopt: SessionAdopt, sessionId: string): string {
|
||||
const target = {
|
||||
socketPath: adopt.socketPath,
|
||||
targetSession: adopt.targetSession,
|
||||
// Derived rather than required: the view name is a function of the Codeman
|
||||
// session id, so a record that predates it (or one whose creator filled it in
|
||||
// after construction) still produces the right name instead of an empty `-s`.
|
||||
viewSession: adopt.viewSession || foreignViewSessionName(sessionId),
|
||||
};
|
||||
if (adopt.location === 'docker' && adopt.docker) {
|
||||
return buildForeignDockerAttachCommand({
|
||||
...target,
|
||||
dockerBase: buildDockerBaseArgs(adopt.docker).join(' '),
|
||||
containerName: adopt.docker.containerName,
|
||||
});
|
||||
}
|
||||
if (adopt.location === 'remote' && adopt.remote) {
|
||||
return buildForeignRemoteAttachCommand({
|
||||
...target,
|
||||
sshArgs: buildSshConnectionArgs(adopt.remote),
|
||||
sshTarget: remoteSshTarget(adopt.remote),
|
||||
});
|
||||
}
|
||||
return buildForeignAttachCommand(target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push one environment variable into a tmux session with `setenv`.
|
||||
*
|
||||
@@ -2512,6 +2561,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
historyLimit = DEFAULT_TMUX_HISTORY_LIMIT,
|
||||
remote,
|
||||
docker,
|
||||
adopt,
|
||||
owner,
|
||||
} = options;
|
||||
const muxName = `codeman-${sessionId.slice(0, 8)}`;
|
||||
@@ -2533,6 +2583,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
workingDir,
|
||||
remote,
|
||||
docker,
|
||||
adopt,
|
||||
owner,
|
||||
mode,
|
||||
attached: false,
|
||||
@@ -2559,7 +2610,13 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
// surfacing as a bare `execvp(3) failed: No such file or directory` with nothing
|
||||
// pointing at the real cause. The container's own CLIs are verified by the adoption
|
||||
// preflight / image gate before launch instead.
|
||||
const cliRunsInContainer = !!docker;
|
||||
//
|
||||
// ⚠️ Skipped for an ADOPTED session for the mirror-image reason: its CLI was started by
|
||||
// a human in a process we did not spawn, and our pane only runs `tmux attach`. Requiring
|
||||
// the binary here would reject adopting a claude that lives in a container or on an ssh
|
||||
// host, and (worse) reject a LOCAL adoption whenever the agent is outside the server
|
||||
// process's PATH, which is the usual systemd/launchd situation.
|
||||
const cliRunsInContainer = !!docker || !!adopt;
|
||||
if (!cliRunsInContainer && !cliDir) {
|
||||
const message = missingCliMessage(mode);
|
||||
if (message) throw new Error(message);
|
||||
@@ -2570,7 +2627,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
const { command: statusLineCommand, state: statusLine } = await this._resolveStatusLine(
|
||||
mode,
|
||||
workingDir,
|
||||
!!(remote || docker)
|
||||
// An adopted wrapper launches no agent, so nothing can carry the exporter.
|
||||
!!(remote || docker || adopt)
|
||||
);
|
||||
const idleCompactionOff = await this._resolveIdleCompactionOptOut(mode, statusLine, keepWarm, spawnedByAgent);
|
||||
// The user's own REAL statusLine, if any (walked via Claude Code's own
|
||||
@@ -2607,11 +2665,21 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
try {
|
||||
// Build the full command to run inside tmux
|
||||
const localFullCmd = `${buildNofileLimitCommand()} && ${pathExport}${envExportsStr} && ${cmd}`;
|
||||
const fullCmd = docker
|
||||
? buildDockerLaunchCommand(resolveDockerLaunchOptions(mode, docker, sessionId, resumeSessionId))
|
||||
: remote
|
||||
? buildRemoteSessionCommand({ mode, remote, sessionId, claudeMode, allowedTools, ompConfig, resumeSessionId })
|
||||
: localFullCmd;
|
||||
const fullCmd = adopt
|
||||
? buildAdoptSessionCommand(adopt, sessionId)
|
||||
: docker
|
||||
? buildDockerLaunchCommand(resolveDockerLaunchOptions(mode, docker, sessionId, resumeSessionId))
|
||||
: remote
|
||||
? buildRemoteSessionCommand({
|
||||
mode,
|
||||
remote,
|
||||
sessionId,
|
||||
claudeMode,
|
||||
allowedTools,
|
||||
ompConfig,
|
||||
resumeSessionId,
|
||||
})
|
||||
: localFullCmd;
|
||||
|
||||
// Create tmux session in three steps to handle cold-start (no server running)
|
||||
// and avoid the race where the command exits before remain-on-exit is set:
|
||||
@@ -2672,9 +2740,11 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
|
||||
// Replace the shell with the actual command (no echo in terminal). Keep
|
||||
// pane launch in /tmp, then cd inside bash against the current mount table.
|
||||
const launchCmd = remote || docker ? fullCmd : `cd ${JSON.stringify(workingDir)} && ${fullCmd}`;
|
||||
// ⚠️ An adopted pane is never `cd`'d: it only attaches, and its `workingDir`
|
||||
// is the neutral wrapper folder, not where the foreign pane is.
|
||||
const launchCmd = remote || docker || adopt ? fullCmd : `cd ${JSON.stringify(workingDir)} && ${fullCmd}`;
|
||||
execSync(
|
||||
`${this.tmux()} respawn-pane -k -c ${TMUX_LAUNCH_CWD} -t "${muxName}" bash -c ${bashCArg(launchCmd, !!(remote || docker))}`,
|
||||
`${this.tmux()} respawn-pane -k -c ${TMUX_LAUNCH_CWD} -t "${muxName}" bash -c ${bashCArg(launchCmd, !!(remote || docker || adopt))}`,
|
||||
{
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
stdio: 'ignore',
|
||||
@@ -2738,6 +2808,7 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
workingDir,
|
||||
remote,
|
||||
docker,
|
||||
adopt,
|
||||
owner,
|
||||
mode,
|
||||
attached: false,
|
||||
@@ -2862,6 +2933,11 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
} = options;
|
||||
const session = this.sessions.get(sessionId);
|
||||
if (!session) return null;
|
||||
// Adoption metadata comes from the tracked session, not the caller: a respawn
|
||||
// of an adopted wrapper RE-ATTACHES to the same foreign target. It must never
|
||||
// be able to become "launch a fresh agent here" because a caller forgot to
|
||||
// pass the field through.
|
||||
const adopt = options.adopt ?? session.adopt;
|
||||
const muxName = session.muxName;
|
||||
|
||||
if (!isValidMuxName(muxName) || !isValidPath(workingDir)) return null;
|
||||
@@ -2874,7 +2950,8 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
const { command: statusLineCommand, state: statusLine } = await this._resolveStatusLine(
|
||||
mode,
|
||||
workingDir,
|
||||
!!(remote || docker)
|
||||
// An adopted wrapper launches no agent, so nothing can carry the exporter.
|
||||
!!(remote || docker || adopt)
|
||||
);
|
||||
const idleCompactionOff = await this._resolveIdleCompactionOptOut(mode, statusLine, keepWarm, spawnedByAgent);
|
||||
const userStatusLineCommand = statusLineCommand ? await findEffectiveUserStatusLineCommand(workingDir) : undefined;
|
||||
@@ -2904,11 +2981,13 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
const config = niceConfig || DEFAULT_NICE_CONFIG;
|
||||
const cmd = wrapWithNice(baseCmd, config);
|
||||
const localFullCmd = `${buildNofileLimitCommand()} && ${pathExport}${envExportsStr} && ${cmd}`;
|
||||
const fullCmd = docker
|
||||
? buildDockerLaunchCommand(resolveDockerLaunchOptions(mode, docker, sessionId, resumeSessionId))
|
||||
: remote
|
||||
? buildRemoteSessionCommand({ mode, remote, sessionId, claudeMode, allowedTools, ompConfig, resumeSessionId })
|
||||
: localFullCmd;
|
||||
const fullCmd = adopt
|
||||
? buildAdoptSessionCommand(adopt, sessionId)
|
||||
: docker
|
||||
? buildDockerLaunchCommand(resolveDockerLaunchOptions(mode, docker, sessionId, resumeSessionId))
|
||||
: remote
|
||||
? buildRemoteSessionCommand({ mode, remote, sessionId, claudeMode, allowedTools, ompConfig, resumeSessionId })
|
||||
: localFullCmd;
|
||||
|
||||
try {
|
||||
// Same per-CLI env setup as createSession, re-applied so the respawned pane inherits it.
|
||||
@@ -2925,9 +3004,11 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
this.applyEnvOverrides(muxName, envOverrides, unsetEnvKeys);
|
||||
|
||||
// -c /tmp + cd bounce — see createSession() for rationale (stale FUSE state).
|
||||
const launchCmd = remote || docker ? fullCmd : `cd ${JSON.stringify(workingDir)} && ${fullCmd}`;
|
||||
// ⚠️ An adopted pane is never `cd`'d: it only attaches, and its `workingDir`
|
||||
// is the neutral wrapper folder, not where the foreign pane is.
|
||||
const launchCmd = remote || docker || adopt ? fullCmd : `cd ${JSON.stringify(workingDir)} && ${fullCmd}`;
|
||||
await execAsync(
|
||||
`${this.tmux()} respawn-pane -k -c ${TMUX_LAUNCH_CWD} -t "${muxName}" bash -c ${bashCArg(launchCmd, !!(remote || docker))}`,
|
||||
`${this.tmux()} respawn-pane -k -c ${TMUX_LAUNCH_CWD} -t "${muxName}" bash -c ${bashCArg(launchCmd, !!(remote || docker || adopt))}`,
|
||||
{
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
}
|
||||
@@ -3133,6 +3214,59 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
// for a non-owned session. The only `kill-session` we run is on OUR LOCAL
|
||||
// socket (`this.tmux()` = `tmux -L codeman` on THIS host), which kills the
|
||||
// local pane — it does NOT reach the REMOTE socket.
|
||||
// ADOPTION — DETACH-NOT-KILL, by construction rather than by discipline.
|
||||
//
|
||||
// An adopted session's wrapper is an ordinary session on OUR socket whose
|
||||
// pane runs `tmux attach` (or `docker exec …`/`ssh …` then attach) against a
|
||||
// FOREIGN server. Killing the wrapper kills our attach client, which is a
|
||||
// DETACH on the foreign side; the human's session keeps running, and our
|
||||
// grouped view session self-destroys via `destroy-unattached on`.
|
||||
//
|
||||
// The guard below is a formality more than a fence — `this.tmux()` only ever
|
||||
// addresses our own socket, so no code path here CAN reach the foreign
|
||||
// server. It is written out anyway so the intent survives future edits, the
|
||||
// same way the non-owned-remote early return does.
|
||||
if (session.adopt) {
|
||||
console.log(`[TmuxManager] DETACH (adopted): tearing down wrapper only for ${session.muxName}`);
|
||||
// A `docker exec` survives its client, so the in-container view would stay
|
||||
// attached forever and leak. Best-effort, and it can only reach OUR view.
|
||||
// See buildForeignDockerViewKillCommand for why local/remote need nothing.
|
||||
// Fire and forget like the owned docker branch below: a daemon that stopped
|
||||
// answering must not hold the event loop for the whole timeout.
|
||||
if (session.adopt.location === 'docker' && session.adopt.docker) {
|
||||
try {
|
||||
exec(
|
||||
buildForeignDockerViewKillCommand({
|
||||
dockerBase: buildDockerBaseArgs(session.adopt.docker).join(' '),
|
||||
containerName: session.adopt.docker.containerName,
|
||||
socketPath: session.adopt.socketPath,
|
||||
viewSession: session.adopt.viewSession || foreignViewSessionName(sessionId),
|
||||
}),
|
||||
{ timeout: EXEC_TIMEOUT_MS },
|
||||
() => {}
|
||||
);
|
||||
} catch {
|
||||
// Best-effort: the container may be gone, or the view already collected.
|
||||
}
|
||||
}
|
||||
if (isValidMuxName(session.muxName)) {
|
||||
try {
|
||||
await execAsync(`${this.tmux()} kill-session -t "${session.muxName}" 2>/dev/null`, {
|
||||
timeout: EXEC_TIMEOUT_MS,
|
||||
});
|
||||
} catch {
|
||||
// Wrapper may already be gone.
|
||||
}
|
||||
}
|
||||
this.lastPaneCount.delete(session.muxName);
|
||||
this.clearPaneExit(session.muxName);
|
||||
this.sessions.delete(sessionId);
|
||||
this.clearRemoteReconnectState(sessionId);
|
||||
this.saveSessions();
|
||||
this.emit('sessionKilled', { sessionId });
|
||||
return true;
|
||||
}
|
||||
|
||||
if (session.remote && session.remote.owned === false) {
|
||||
console.log(`[TmuxManager] DETACH (non-owned remote): tearing down local pane only for ${session.muxName}`);
|
||||
if (isValidMuxName(session.muxName)) {
|
||||
@@ -4678,19 +4812,24 @@ export class TmuxManager extends EventEmitter implements TerminalMultiplexer {
|
||||
|
||||
/**
|
||||
* The `bash -c` argument of a pane launch (`respawn-pane … bash -c <arg>`, run through the
|
||||
* local sh). A remote or docker command is already quoted for the shell at the far end and
|
||||
* must reach bash verbatim, so it goes in single quotes. Double quotes (JSON.stringify) let
|
||||
* the local sh expand every `$` first: the PATH bootstrap of `withRemoteTmuxPath`
|
||||
* (`$HOME/.local/bin:…:$PATH`) arrived on the remote host as this host's home and PATH, so
|
||||
* a remote user with another home found no tmux and every new remote pane exited 127.
|
||||
* `${SHELL:-/bin/sh}` in the remote launch was the local shell for the same reason.
|
||||
* Local commands keep their double-quoted form.
|
||||
* local sh). A remote, docker or adopted command is already quoted for the shell at the far
|
||||
* end and must reach bash verbatim, so it goes in single quotes. Double quotes
|
||||
* (JSON.stringify) let the local sh expand every `$` first: the PATH bootstrap of
|
||||
* `withRemoteTmuxPath` (`$HOME/.local/bin:…:$PATH`) arrived on the remote host as this
|
||||
* host's home and PATH, so a remote user with another home found no tmux and every new
|
||||
* remote pane exited 127. `${SHELL:-/bin/sh}` in the remote launch was the local shell for
|
||||
* the same reason, and an adopted ssh attach carries the same bootstrap, so a tmux in the
|
||||
* remote `~/.local/bin` was found by discovery and then missed by the attach. Single quotes
|
||||
* also keep a real newline, which JSON escaping left as the two characters `\n`.
|
||||
* An adopted attach goes verbatim at all three locations, the local one included: every
|
||||
* value in it is already quoted by `foreign-tmux.ts`, and nothing in it is for this shell.
|
||||
* An agent launched on this host keeps its double-quoted form.
|
||||
*
|
||||
* ⚠️ So nothing in a verbatim launch is expanded on this host any more, the docker client's
|
||||
* own arguments included: a bare `$VAR` in `extraCreateArgs`/`extraExecArgs` reaches docker
|
||||
* as those literal characters.
|
||||
*/
|
||||
function bashCArg(launchCmd: string, verbatim: boolean): string {
|
||||
export function bashCArg(launchCmd: string, verbatim: boolean): string {
|
||||
return verbatim ? shellescape(launchCmd) : JSON.stringify(launchCmd);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user