mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-17 19:59: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
@@ -197,7 +197,7 @@ export function registerDiscordRoutes(app: FastifyInstance, deps: DiscordRouteDe
|
||||
}
|
||||
let upload: { name: string; data: Uint8Array } | undefined;
|
||||
if (file !== undefined) {
|
||||
const problem = await fileProblem(session.workingDir, !!session.remote, file);
|
||||
const problem = await fileProblem(session.workingDir, !!session.remote || session.isAdopted, file);
|
||||
if (typeof problem === 'string') {
|
||||
refundNotifyToken(session.id);
|
||||
reply.code(400);
|
||||
|
||||
@@ -99,6 +99,7 @@ export function registerEditHistoryRoutes(app: FastifyInstance, ctx: SessionPort
|
||||
mode: session.mode,
|
||||
remote: session.remote,
|
||||
docker: session.docker,
|
||||
adopt: session.adopt,
|
||||
claudeSessionId: session.claudeSessionId,
|
||||
claudeConfigDir: session.claudeConfigDir(),
|
||||
};
|
||||
|
||||
@@ -81,6 +81,8 @@ export function registerGitStatusRoutes(
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
if (session.remote) return { success: true, data: emptyOverview('unsupported', { reason: 'remote' }) };
|
||||
if (session.docker) return { success: true, data: emptyOverview('unsupported', { reason: 'docker' }) };
|
||||
// An adopted wrapper's folder is the neutral `/tmp`, so a scan would run git on whatever sits there.
|
||||
if (session.isAdopted) return { success: true, data: emptyOverview('unsupported', { reason: 'adopted' }) };
|
||||
return {
|
||||
success: true,
|
||||
data: await getGitWorkspaceOverview(session.workingDir, {
|
||||
@@ -103,9 +105,12 @@ export function registerGitStatusRoutes(
|
||||
const { repo, path, kind } = query;
|
||||
const limits = limitsFrom(query);
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
if (session.remote || session.docker) {
|
||||
if (session.remote || session.docker || session.isAdopted) {
|
||||
reply.code(400);
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Git is not available for remote or Docker sessions');
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Git is not available for remote, Docker or adopted sessions'
|
||||
);
|
||||
}
|
||||
const repoRoot = repo
|
||||
? await findWorkspaceRepo(session.workingDir, repo, {
|
||||
@@ -159,6 +164,7 @@ export function registerGitStatusRoutes(
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
if (session.remote) return { success: true, data: emptyReport('unsupported', { reason: 'remote' }) };
|
||||
if (session.docker) return { success: true, data: emptyReport('unsupported', { reason: 'docker' }) };
|
||||
if (session.isAdopted) return { success: true, data: emptyReport('unsupported', { reason: 'adopted' }) };
|
||||
// Fail CLOSED on a Docker case list that cannot be read: a fetch runs the repository's hooks, so it never
|
||||
// runs without knowing which folders a container can write to. Answered as a failed run (`state: 'error'`),
|
||||
// published like one, so the Session Options Git row shows it.
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
/**
|
||||
* @fileoverview Mux (tmux) session management routes.
|
||||
* Provides mux session listing, killing, reconciliation, and stats control.
|
||||
* Provides mux session listing, killing, reconciliation, stats control, and
|
||||
* discovery of FOREIGN tmux sessions (ones a human started outside Codeman).
|
||||
*
|
||||
* Discovery lives here rather than beside the adopt endpoint on purpose: like
|
||||
* every other route in this file it exposes cross-user process state — other
|
||||
* people's session names, commands and working directories — so it inherits the
|
||||
* admin gate this file already applies. Adoption is a session CREATE and stays in
|
||||
* `session-routes.ts`, where the owner, capacity and case-space gates live.
|
||||
*/
|
||||
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import type { InfraPort } from '../ports/index.js';
|
||||
import type { InfraPort, SessionPort } from '../ports/index.js';
|
||||
import { STATS_COLLECTION_INTERVAL_MS } from '../../config/server-timing.js';
|
||||
import { requireAdmin } from '../route-helpers.js';
|
||||
import { isMultiUserMode } from '../../config/multiuser.js';
|
||||
import { discoverForeignSessions, readAllDockerCases, readAllRemoteHosts } from '../../foreign-tmux-discovery.js';
|
||||
import { adoptTargetIdentity, foreignTargetKey } from '../../foreign-tmux.js';
|
||||
import { FOREIGN_POLL_INTERVAL_MS } from '../../config/foreign-tmux.js';
|
||||
|
||||
export function registerMuxRoutes(app: FastifyInstance, ctx: InfraPort): void {
|
||||
export function registerMuxRoutes(app: FastifyInstance, ctx: InfraPort & SessionPort): void {
|
||||
app.get('/api/mux-sessions', async (req, reply) => {
|
||||
// Multi-user: this recovery/debug surface exposes every user's tmux + workdirs → admin-only
|
||||
// (requireAdmin is a no-op allow-all in single-user mode, so flag-off is unchanged).
|
||||
@@ -36,6 +46,57 @@ export function registerMuxRoutes(app: FastifyInstance, ctx: InfraPort): void {
|
||||
return result;
|
||||
});
|
||||
|
||||
/**
|
||||
* Foreign tmux sessions available for adoption.
|
||||
*
|
||||
* LOCAL results are always included and are TTL-cached, because the home screen
|
||||
* polls this endpoint while it is open. DOCKER and REMOTE are opt-in per
|
||||
* request (`?docker=1`, `?remote=1`): each costs one `docker exec` or one ssh
|
||||
* per target, and having the home page fan those out on every load is the one
|
||||
* cost this design refuses to pay.
|
||||
*
|
||||
* `adoptedBy` is filled from the live sessions, so a target Codeman already wraps
|
||||
* renders as "open" rather than offering a second wrapper. Sessions and not mux
|
||||
* records: the tmux record only exists once the tab's first attach starts the pane.
|
||||
*/
|
||||
app.get('/api/mux/foreign', async (req, reply) => {
|
||||
if (isMultiUserMode() && !requireAdmin(req, reply)) return;
|
||||
const q = (req.query ?? {}) as Record<string, string | undefined>;
|
||||
const wantDocker = q.docker === '1' || q.docker === 'true';
|
||||
const wantRemote = q.remote === '1' || q.remote === 'true';
|
||||
|
||||
// Read the registries either way: `canScanWide` tells the browser whether the
|
||||
// expensive scan has anywhere to go. Without it the UI hides an empty block —
|
||||
// and with it the toggle that is the ONLY way to populate that block, which on
|
||||
// a host with containers but no local tmux sessions made the feature invisible.
|
||||
const dockerCases = await readAllDockerCases();
|
||||
const remoteHosts = await readAllRemoteHosts();
|
||||
|
||||
const result = await discoverForeignSessions({
|
||||
local: true,
|
||||
force: q.force === '1',
|
||||
dockerCases: wantDocker ? dockerCases : undefined,
|
||||
remoteHosts: wantRemote ? remoteHosts : undefined,
|
||||
});
|
||||
|
||||
// The same key the adopt route's one-wrapper check reads (see foreignTargetKey).
|
||||
const wrapped = new Map<string, string>();
|
||||
for (const session of ctx.sessions.values()) {
|
||||
if (session.adopt) wrapped.set(foreignTargetKey(adoptTargetIdentity(session.adopt)), session.id);
|
||||
}
|
||||
|
||||
return {
|
||||
sessions: result.sessions.map((f) => ({
|
||||
...f,
|
||||
adoptedBy: wrapped.get(foreignTargetKey(f)),
|
||||
})),
|
||||
scannedAt: result.scannedAt,
|
||||
notes: result.notes,
|
||||
pollIntervalMs: FOREIGN_POLL_INTERVAL_MS,
|
||||
canScanWide: dockerCases.length > 0 || remoteHosts.length > 0,
|
||||
};
|
||||
});
|
||||
|
||||
app.post('/api/mux-sessions/stats/start', async (req, reply) => {
|
||||
// Multi-user: process-wide stats collection toggle → admin-only.
|
||||
if (isMultiUserMode() && !requireAdmin(req, reply)) return;
|
||||
|
||||
@@ -37,6 +37,15 @@ import type { SessionPort, EventPort, RespawnPort, ConfigPort, InfraPort } from
|
||||
/** Cap on a remote `@fix_plan.md` read over ssh (a task list, not a document). */
|
||||
const MAX_REMOTE_FIX_PLAN_BYTES = 1024 * 1024;
|
||||
|
||||
/**
|
||||
* An adopted session's `workingDir` is the neutral wrapper folder `/tmp`, not a workspace.
|
||||
* Using it would write a predictable name into a folder anyone can write to, and read one
|
||||
* back, while the agent in the pane never sees either file.
|
||||
*/
|
||||
function refuseAdoptedRalphFile(file: string) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `${file} is not available for an adopted session`);
|
||||
}
|
||||
|
||||
export function registerRalphRoutes(
|
||||
app: FastifyInstance,
|
||||
ctx: SessionPort & EventPort & RespawnPort & ConfigPort & InfraPort
|
||||
@@ -60,6 +69,17 @@ export function registerRalphRoutes(
|
||||
};
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
|
||||
// ⚠️ Adoption gate, kept SEPARATE from the external-CLI gate above: an adopted
|
||||
// session can be `mode: 'claude'` and still be a process we never launched.
|
||||
// Everything below drives the pane on the assumption Codeman owns what runs
|
||||
// in it — sending `/clear`, killing and relaunching the agent — which against
|
||||
// someone else's live session is destructive, not merely unsupported.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'The Ralph tracker is not available for adopted sessions: Codeman did not start this agent and must not drive its lifecycle'
|
||||
);
|
||||
}
|
||||
// Ralph tracker is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(
|
||||
@@ -197,6 +217,7 @@ export function registerRalphRoutes(
|
||||
app.post('/api/sessions/:id/fix-plan/write', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
if (session.isAdopted) return refuseAdoptedRalphFile('@fix_plan.md');
|
||||
// A remote session's workingDir is a path on the remote host. Writing it with local fs would land
|
||||
// the file in a same-named local folder (or fail), and remote writes are out of scope by design
|
||||
// (src/remote-files.ts is read-only), so it is refused, like the File Viewer's remote edit.
|
||||
@@ -233,6 +254,7 @@ export function registerRalphRoutes(
|
||||
app.post('/api/sessions/:id/fix-plan/read', async (req) => {
|
||||
const { id } = req.params as { id: string };
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
if (session.isAdopted) return refuseAdoptedRalphFile('@fix_plan.md');
|
||||
|
||||
const workingDir = session.workingDir;
|
||||
if (!workingDir) {
|
||||
@@ -280,6 +302,7 @@ export function registerRalphRoutes(
|
||||
const { id } = req.params as { id: string };
|
||||
const { content } = parseBody(RalphPromptWriteSchema, req.body, 'Invalid request body');
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
if (session.isAdopted) return refuseAdoptedRalphFile('@ralph_prompt.md');
|
||||
// Same rule as fix-plan/write: never write a remote session's file on the local disk.
|
||||
if (session.remote) {
|
||||
return createErrorResponse(
|
||||
|
||||
@@ -91,8 +91,9 @@ export function registerReadMyMindRoutes(app: FastifyInstance, ctx: SessionPort
|
||||
const transcriptPath = ctx.getTranscriptPath(id);
|
||||
const transcript = transcriptPath ? await readTranscriptSignals(transcriptPath) : null;
|
||||
// Remote-SSH cases skip git: workingDir is not local. Docker cases are
|
||||
// fine (the workspace is bind-mounted at the same host path).
|
||||
const workspace = session.remote ? null : await collectWorkspaceSignals(session.workingDir);
|
||||
// fine (the workspace is bind-mounted at the same host path). An adopted
|
||||
// session's workingDir is a neutral wrapper folder, so it skips git too.
|
||||
const workspace = session.remote || session.isAdopted ? null : await collectWorkspaceSignals(session.workingDir);
|
||||
|
||||
const lastPromptTs = profile.recentPrompts[profile.recentPrompts.length - 1]?.ts;
|
||||
const tracker = ctx.runSummaryTrackers.get(id);
|
||||
|
||||
@@ -98,6 +98,17 @@ export function registerRespawnRoutes(
|
||||
}
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
|
||||
// ⚠️ Adoption gate, kept SEPARATE from the external-CLI gate above: an adopted
|
||||
// session can be `mode: 'claude'` and still be a process we never launched.
|
||||
// Everything below drives the pane on the assumption Codeman owns what runs
|
||||
// in it — sending `/clear`, killing and relaunching the agent — which against
|
||||
// someone else's live session is destructive, not merely unsupported.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Respawn is not available for adopted sessions: Codeman did not start this agent and must not drive its lifecycle'
|
||||
);
|
||||
}
|
||||
// Respawn is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Respawn is not supported for ${session.mode} sessions`);
|
||||
@@ -241,6 +252,17 @@ export function registerRespawnRoutes(
|
||||
return createErrorResponse(ApiErrorCode.SESSION_BUSY, 'Session is busy');
|
||||
}
|
||||
|
||||
// ⚠️ Adoption gate, kept SEPARATE from the external-CLI gate above: an adopted
|
||||
// session can be `mode: 'claude'` and still be a process we never launched.
|
||||
// Everything below drives the pane on the assumption Codeman owns what runs
|
||||
// in it — sending `/clear`, killing and relaunching the agent — which against
|
||||
// someone else's live session is destructive, not merely unsupported.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Respawn is not available for adopted sessions: Codeman did not start this agent and must not drive its lifecycle'
|
||||
);
|
||||
}
|
||||
// Respawn is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Respawn is not supported for ${session.mode} sessions`);
|
||||
@@ -310,6 +332,17 @@ export function registerRespawnRoutes(
|
||||
const body = reResult.data as { config?: Partial<RespawnConfig>; durationMinutes?: number };
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
|
||||
// ⚠️ Adoption gate, kept SEPARATE from the external-CLI gate above: an adopted
|
||||
// session can be `mode: 'claude'` and still be a process we never launched.
|
||||
// Everything below drives the pane on the assumption Codeman owns what runs
|
||||
// in it — sending `/clear`, killing and relaunching the agent — which against
|
||||
// someone else's live session is destructive, not merely unsupported.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Respawn is not available for adopted sessions: Codeman did not start this agent and must not drive its lifecycle'
|
||||
);
|
||||
}
|
||||
// Respawn is not supported for external-CLI sessions (opencode/codex)
|
||||
if (isExternalCliMode(session.mode)) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, `Respawn is not supported for ${session.mode} sessions`);
|
||||
|
||||
@@ -34,6 +34,17 @@ import {
|
||||
type OmpConfig,
|
||||
type RemoteHost,
|
||||
} from '../../types.js';
|
||||
import { AdoptForeignSessionSchema } from '../schemas.js';
|
||||
import {
|
||||
discoverForeignSessions,
|
||||
invalidateForeignCache,
|
||||
readAllDockerCases,
|
||||
readAllRemoteHosts,
|
||||
} from '../../foreign-tmux-discovery.js';
|
||||
import { adoptTargetIdentity, foreignTargetKey, foreignViewSessionName } from '../../foreign-tmux.js';
|
||||
import { requireAdmin } from '../route-helpers.js';
|
||||
import type { SessionAdopt } from '../../types/session.js';
|
||||
import type { ForeignTmuxSession } from '../../types/foreign-tmux.js';
|
||||
import {
|
||||
GuardedInputBusyError,
|
||||
Session,
|
||||
@@ -1490,6 +1501,187 @@ export function registerSessionRoutes(
|
||||
};
|
||||
});
|
||||
|
||||
// ========== Adopt a foreign tmux session ==========
|
||||
|
||||
/**
|
||||
* The wrapper pane for an adopted session runs `tmux attach`, never the agent,
|
||||
* so it needs no workspace, and must not borrow the foreign one. Same value
|
||||
* `resolveMuxAttachCwd()` gives remote and docker panes.
|
||||
*/
|
||||
const ADOPTED_WRAPPER_WORKING_DIR = '/tmp';
|
||||
|
||||
/**
|
||||
* Targets with a wrapper being created right now. The live-session check alone
|
||||
* leaves a gap: between it and `addSession` the route awaits the host registries,
|
||||
* the history config and the owner's layout lock, so two devices opening one row
|
||||
* could each pass it.
|
||||
*/
|
||||
const adoptsInFlight = new Set<string>();
|
||||
|
||||
/**
|
||||
* Wrap a tmux session a HUMAN started (local, in a container, or over ssh) in a
|
||||
* Codeman session, so it appears as a tab and can be driven from the browser.
|
||||
*
|
||||
* Four things make this safe, and each is load-bearing:
|
||||
*
|
||||
* 1. **The body carries only an opaque id.** The socket path, session name and
|
||||
* host are re-resolved by re-running discovery here. A browser therefore
|
||||
* never supplies a fragment of the command we are about to run, which is the
|
||||
* same rule that keeps docker-adopt and remote-attach injection-free.
|
||||
* 2. **The candidate must still exist.** Discovery is re-run rather than cached,
|
||||
* so a session that died between the listing and the click fails with a 404
|
||||
* instead of producing a wrapper attached to nothing.
|
||||
* 3. **One wrapper per target.** Two wrappers on one foreign session would each
|
||||
* create their own grouped view and each think they own the tab; the guard
|
||||
* is here rather than in the button's in-flight lock, which only stops a
|
||||
* double-click on one device.
|
||||
* 4. **Admin-only under multi-user.** Discovery already is (it exposes other
|
||||
* users' processes), and adopting someone's `shell` is arbitrary execution
|
||||
* as the server account, which is exactly what the `can-bypass-permissions`
|
||||
* grant gates elsewhere. The admin gate subsumes it, so there is deliberately
|
||||
* no second grant check here.
|
||||
*/
|
||||
app.post('/api/sessions/adopt', async (req, reply) => {
|
||||
if (isMultiUserMode() && !requireAdmin(req, reply)) return;
|
||||
|
||||
const owner = ownerFor(req);
|
||||
const body = parseBody(AdoptForeignSessionSchema, req.body, 'Invalid request body');
|
||||
|
||||
// Re-resolve rather than trust: point 1 and 2 above.
|
||||
const found = await discoverForeignSessions({
|
||||
local: true,
|
||||
force: true,
|
||||
dockerCases: body.docker ? await readAllDockerCases() : undefined,
|
||||
remoteHosts: body.remote ? await readAllRemoteHosts() : undefined,
|
||||
});
|
||||
const target = found.sessions.find((f) => f.id === body.id);
|
||||
if (!target) {
|
||||
// ⚠️ "Not in the re-resolve" has two very different causes and they must not
|
||||
// be reported as one. The session really being gone is the ordinary case;
|
||||
// the OTHER case is a location we could not reach this time, which on a
|
||||
// flaky link makes a perfectly live remote session read as deleted. Measured
|
||||
// against a real VM whose ssh path dropped ~10% of connections: clicking
|
||||
// Open failed with "no longer there" while the session was sitting right
|
||||
// there. Discovery already knows which it was: it wrote a note, so say so.
|
||||
const reach = found.notes.filter((n) => !/skipped/.test(n));
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.NOT_FOUND,
|
||||
reach.length
|
||||
? `Could not reach it just now (${reach.join('; ')}). It may still be running, try again.`
|
||||
: 'That tmux session is no longer there. Refresh the list and try again.'
|
||||
);
|
||||
}
|
||||
|
||||
// Point 3: one wrapper per target. Live sessions and not mux records, which
|
||||
// only exist once the first attach starts the pane, so reading those let a
|
||||
// second adopt through before the first tab had started.
|
||||
const targetKey = foreignTargetKey(target);
|
||||
for (const session of ctx.sessions.values()) {
|
||||
if (session.adopt && foreignTargetKey(adoptTargetIdentity(session.adopt)) === targetKey) {
|
||||
return { session: ctx.getSessionStateWithRespawn(session), alreadyAdopted: true };
|
||||
}
|
||||
}
|
||||
if (adoptsInFlight.has(targetKey)) {
|
||||
return createErrorResponse(ApiErrorCode.SESSION_BUSY, 'That tmux session is already being opened');
|
||||
}
|
||||
|
||||
// After the reuse above, which creates nothing and so must not be refused at capacity.
|
||||
const capMsg = sessionCapacityMessage(ctx.sessions, owner);
|
||||
if (capMsg) return createErrorResponse(ApiErrorCode.SESSION_BUSY, capMsg);
|
||||
|
||||
adoptsInFlight.add(targetKey);
|
||||
try {
|
||||
return await createAdoptedSession(req, target, owner, body);
|
||||
} finally {
|
||||
adoptsInFlight.delete(targetKey);
|
||||
}
|
||||
});
|
||||
|
||||
/** Everything past the guards in `POST /api/sessions/adopt`, held under its in-flight mark. */
|
||||
async function createAdoptedSession(
|
||||
req: FastifyRequest,
|
||||
target: ForeignTmuxSession,
|
||||
owner: string | undefined,
|
||||
body: { name?: string; parentSessionId?: string }
|
||||
) {
|
||||
// Connection facts are copied onto the session rather than referenced by id:
|
||||
// a wrapper restored after a server restart must be able to rebuild its
|
||||
// command even if the host registry was edited in the meantime.
|
||||
const adopt: SessionAdopt = {
|
||||
location: target.location,
|
||||
socketPath: target.socketPath,
|
||||
targetSession: target.sessionName,
|
||||
viewSession: '',
|
||||
paneCurrentPath: target.workingDir,
|
||||
};
|
||||
|
||||
if (target.location === 'docker') {
|
||||
const hosts = await readDockerHosts(CODEMAN_CONFIG_DIR);
|
||||
const host = hosts.find((h) => h.id === target.hostId);
|
||||
if (!target.containerName) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Container name missing for a docker candidate');
|
||||
}
|
||||
adopt.docker = {
|
||||
hostId: target.hostId ?? '',
|
||||
label: target.hostLabel ?? target.containerName,
|
||||
engine: host?.engine ?? 'docker',
|
||||
containerName: target.containerName,
|
||||
daemonHost: host?.daemonHost,
|
||||
context: host?.context,
|
||||
};
|
||||
} else if (target.location === 'remote') {
|
||||
const host = (await readRemoteHosts(CODEMAN_CONFIG_DIR)).find((h) => h.id === target.hostId);
|
||||
if (!host) return createErrorResponse(ApiErrorCode.NOT_FOUND, 'Remote host not found');
|
||||
adopt.remote = {
|
||||
hostId: host.id,
|
||||
label: host.label,
|
||||
host: host.host,
|
||||
username: host.username,
|
||||
port: host.port,
|
||||
identityFile: host.identityFile,
|
||||
socksProxy: host.socksProxy,
|
||||
jumpHost: host.jumpHost,
|
||||
extraSshOptions: host.extraSshOptions,
|
||||
};
|
||||
}
|
||||
|
||||
const adoptHistoryConfig = await ctx.getTerminalHistoryConfig();
|
||||
|
||||
// ⚠️ The wrapper's `workingDir` is a NEUTRAL LOCAL path, never the foreign
|
||||
// pane's cwd. That cwd is an observation about another machine: it can carry
|
||||
// characters outside SAFE_PATH_PATTERN (`~/c++`, `Program Files (x86)`), which
|
||||
// makes `createSession` throw so the tab never starts at all, and when it is a
|
||||
// container or ssh path every local consumer of `workingDir` — the Files panel,
|
||||
// the boot hook sweep, the fs watchers — reads it as a path on THIS host. The
|
||||
// foreign cwd stays on `adopt.paneCurrentPath`, which is for display only.
|
||||
// `/tmp` is the same neutral cwd `resolveMuxAttachCwd` already gives the pane.
|
||||
const session = new Session({
|
||||
workingDir: ADOPTED_WRAPPER_WORKING_DIR,
|
||||
mode: target.mode,
|
||||
name: body.name || target.sessionName,
|
||||
mux: ctx.mux,
|
||||
useMux: true,
|
||||
tmuxHistoryLimit: adoptHistoryConfig.tmuxHistoryLimit,
|
||||
adopt,
|
||||
owner,
|
||||
parentSessionId: resolveParentSessionId(ctx, req, body.parentSessionId, owner),
|
||||
});
|
||||
// The view session name is derived from the Codeman session id, so it can only
|
||||
// be filled once the Session exists.
|
||||
adopt.viewSession = foreignViewSessionName(session.id);
|
||||
|
||||
await ctx.addSession(session);
|
||||
ctx.store.incrementSessionsCreated();
|
||||
ctx.persistSessionState(session);
|
||||
await ctx.setupSessionListeners(session);
|
||||
getLifecycleLog().log({ event: 'created', sessionId: session.id, name: session.name });
|
||||
invalidateForeignCache();
|
||||
|
||||
const lightState = ctx.getSessionStateWithRespawn(session);
|
||||
ctx.broadcast(SseEvent.SessionCreated, lightState);
|
||||
return { session: lightState, adopted: true };
|
||||
}
|
||||
|
||||
// ========== Rename Session ==========
|
||||
|
||||
app.put('/api/sessions/:id/name', async (req) => {
|
||||
@@ -1553,6 +1745,13 @@ export function registerSessionRoutes(
|
||||
'Custom model endpoints are not supported for remote (SSH) or Docker sessions yet'
|
||||
);
|
||||
}
|
||||
// Its own check: this restarts the CLI in the pane, and an adopted pane's CLI is not ours to restart.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Custom model endpoints are not available for adopted sessions: Codeman did not start this agent'
|
||||
);
|
||||
}
|
||||
if (session.isBusy()) {
|
||||
return createErrorResponse(ApiErrorCode.SESSION_BUSY, 'Session is busy');
|
||||
}
|
||||
@@ -1912,6 +2111,10 @@ export function registerSessionRoutes(
|
||||
// and belongs in its own PR, not in a refactor that is meant to change nothing.
|
||||
if (
|
||||
!isExternalCliMode(session.mode) &&
|
||||
// ⚠️ And never for an adopted session, whose mode can be claude while the
|
||||
// agent in that pane belongs to someone else. Kept as its own clause for
|
||||
// the same reason the respawn and Ralph routes keep theirs separate.
|
||||
!session.isAdopted &&
|
||||
ctx.store.getConfig().ralphEnabled &&
|
||||
!session.ralphTracker.autoEnableDisabled
|
||||
) {
|
||||
@@ -2850,7 +3053,13 @@ export function registerSessionRoutes(
|
||||
* effort: the tab rename has already happened and must not fail on this.
|
||||
*/
|
||||
async function syncClaudeTitle(session: Session): Promise<void> {
|
||||
if (getCli(session.mode)?.capabilities.transcript !== 'claude-jsonl' || session.remote || session.docker) return;
|
||||
if (
|
||||
getCli(session.mode)?.capabilities.transcript !== 'claude-jsonl' ||
|
||||
session.remote ||
|
||||
session.docker ||
|
||||
session.isAdopted
|
||||
)
|
||||
return;
|
||||
try {
|
||||
const projectsDir = join(process.env.HOME || '/tmp', '.claude', 'projects');
|
||||
const hookPath = ctx.getTranscriptPath(session.id);
|
||||
@@ -2928,6 +3137,17 @@ export function registerSessionRoutes(
|
||||
// The body of GET /api/sessions/:id/last-response, so the Discord bridge reads the same transcript
|
||||
// the response viewer does (per-CLI reader, pane fallback) without a second copy of this logic.
|
||||
const lastResponseFor = async (session: Session, context?: string) => {
|
||||
// ⚠️ An adopted session has no transcript Codeman can name. Every reader below pairs one by
|
||||
// the id Codeman launched the CLI with or by the session's folder, and neither means anything
|
||||
// here: the CLI chose its own id, and the folder is the neutral `/tmp`, so the newest file for
|
||||
// that folder would be another conversation's answer shown as this one's. Nothing said yet is
|
||||
// the honest answer.
|
||||
if (session.isAdopted) {
|
||||
return context === 'full' || context === 'turn'
|
||||
? { text: '', timestamp: '', messages: [] }
|
||||
: { text: '', timestamp: '' };
|
||||
}
|
||||
|
||||
// Codex sessions don't write to ~/.claude/projects — their transcripts
|
||||
// live in ~/.codex/sessions/**. Branch to a Codex-specific reader so the
|
||||
// response-viewer works for Codex panes too.
|
||||
@@ -3658,6 +3878,16 @@ export function registerSessionRoutes(
|
||||
const { id } = req.params as { id: string };
|
||||
const body = parseBody(AutoClearSchema, req.body, 'Invalid request body');
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
// ⚠️ Separate from the external-CLI gate on purpose: an adopted session's mode
|
||||
// can perfectly well BE claude, and this drives the pane of a session someone
|
||||
// else is using. Merging the two checks means a future change to the
|
||||
// external-CLI rule silently reopens this one.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Auto-clear is not available for adopted sessions: Codeman did not start this agent and must not drive it'
|
||||
);
|
||||
}
|
||||
|
||||
session.setAutoClear(body.enabled, body.threshold);
|
||||
persistAndBroadcastSession(ctx, session);
|
||||
@@ -3679,6 +3909,16 @@ export function registerSessionRoutes(
|
||||
const { id } = req.params as { id: string };
|
||||
const body = parseBody(AutoCompactSchema, req.body, 'Invalid request body');
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
// ⚠️ Separate from the external-CLI gate on purpose: an adopted session's mode
|
||||
// can perfectly well BE claude, and this drives the pane of a session someone
|
||||
// else is using. Merging the two checks means a future change to the
|
||||
// external-CLI rule silently reopens this one.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Auto-compact is not available for adopted sessions: Codeman did not start this agent and must not drive it'
|
||||
);
|
||||
}
|
||||
|
||||
session.setAutoCompact(body.enabled, body.threshold, body.prompt);
|
||||
persistAndBroadcastSession(ctx, session);
|
||||
@@ -3741,8 +3981,11 @@ export function registerSessionRoutes(
|
||||
const { id } = req.params as { id: string };
|
||||
const body = parseBody(GitFetchSettingsSchema, req.body, 'Invalid request body');
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
if (session.remote || session.docker) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Git fetch does not run for remote or Docker sessions');
|
||||
if (session.remote || session.docker || session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Git fetch does not run for remote, Docker or adopted sessions'
|
||||
);
|
||||
}
|
||||
|
||||
const enabled = 'enabled' in body ? (body.enabled ?? undefined) : session.gitFetchEnabled;
|
||||
@@ -3768,6 +4011,16 @@ export function registerSessionRoutes(
|
||||
const { id } = req.params as { id: string };
|
||||
const body = parseBody(AutoResumeSchema, req.body, 'Invalid request body');
|
||||
const session = findSessionOrFail(ctx, id, req);
|
||||
// ⚠️ Separate from the external-CLI gate on purpose: an adopted session's mode
|
||||
// can perfectly well BE claude, and this drives the pane of a session someone
|
||||
// else is using. Merging the two checks means a future change to the
|
||||
// external-CLI rule silently reopens this one.
|
||||
if (session.isAdopted) {
|
||||
return createErrorResponse(
|
||||
ApiErrorCode.INVALID_INPUT,
|
||||
'Auto-resume is not available for adopted sessions: Codeman did not start this agent and must not drive it'
|
||||
);
|
||||
}
|
||||
|
||||
session.setAutoResume(body.enabled);
|
||||
persistAndBroadcastSession(ctx, session);
|
||||
@@ -3838,6 +4091,10 @@ export function registerSessionRoutes(
|
||||
if (body.enabled && session.remote) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Image watching does not run for remote sessions');
|
||||
}
|
||||
// An adopted session's folder is the neutral wrapper folder, not the foreign pane's work.
|
||||
if (body.enabled && session.isAdopted) {
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Image watching does not run for adopted sessions');
|
||||
}
|
||||
|
||||
if (body.enabled) {
|
||||
imageWatcher.watchSession(session.id, session.workingDir);
|
||||
@@ -5804,6 +6061,13 @@ export function registerSessionRoutes(
|
||||
'Prompt uploads are not supported for remote (SSH) sessions'
|
||||
);
|
||||
}
|
||||
// An adopted session has no workspace of ours: its folder is the neutral `/tmp`, shared with
|
||||
// whatever else runs there, and an agent in a container or on an ssh host could not read it.
|
||||
// The foreign pane's own folder is not ours to write into either.
|
||||
if (session.isAdopted) {
|
||||
reply.code(400);
|
||||
return createErrorResponse(ApiErrorCode.INVALID_INPUT, 'Prompt uploads are not supported for adopted sessions');
|
||||
}
|
||||
|
||||
// The upload is written under session.workingDir (ensureUploadDir below), and
|
||||
// a live session's workspace can sit on a network mount that stopped answering.
|
||||
|
||||
@@ -1185,9 +1185,10 @@ export function registerSystemRoutes(
|
||||
// Handle image watcher toggle dynamically
|
||||
toggleService((merged.imageWatcherEnabled as boolean) ?? false, imageWatcher, 'Image watcher', () => {
|
||||
// Re-watch all active sessions that have image watcher enabled (never a remote session: its
|
||||
// workingDir is a path on the remote host, not on this disk)
|
||||
// workingDir is a path on the remote host, not on this disk; nor an adopted one, whose folder
|
||||
// is the neutral wrapper folder and not the foreign pane's work)
|
||||
for (const session of ctx.sessions.values()) {
|
||||
if (session.imageWatcherEnabled && !session.remote) {
|
||||
if (session.imageWatcherEnabled && !session.remote && !session.isAdopted) {
|
||||
imageWatcher.watchSession(session.id, session.workingDir);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user