fix(session): resume the conversation when respawning a dead pane

A CLI that launches with `--session-id <id>` refuses an id that is already in
use (claude: `Error: Session ID ... is already in use.`), and every session
whose agent has been prompted owns a transcript under that id. The dead-pane
respawn in `_setupOrAttachMuxSession()` passed the bare launch line, so
recovering such a session relaunched a CLI that died on startup, the pane went
dead again at once, and the conversation was stranded behind a tab that looked
merely idle.

`restartCli()` has pinned a resume id against this since the custom-model work,
and its comment states the assumption that made the other path look safe:
"Unlike the dead-pane respawn, this one kills a WORKING pane whose conversation
already has a transcript". A pane whose agent exited has a transcript too.

Both relaunch paths now build options through
`_buildRespawnPaneOptionsWithResumePin()`, and so does the create-path fallback
after a failed respawn, which otherwise met the same refusal that made it the
fallback. Four gates guard the pin, each standing for a way of resuming the
WRONG conversation or of making a working relaunch fail.

A remote or docker session is never pinned. Unlike `restartCli()`, whose route
refuses both, the dead-pane respawn is reached by every session shape. Their
pane commands already render a self-healing `--session-id || --resume`, and
both flip to resume-first once the resume id differs; the conversation lives on
the far side, so a local id resolves to nothing there and the `--session-id`
fallback then collides with the transcript the far side does hold.

The id comes from the conversation CHAIN rather than `_claudeSessionId`, which
also holds history-correlated guesses keyed on the working directory.
`_recordClaudeSessionInChain()` refuses those so they cannot "write a foreign
conversation into this pane's permanent record", and launching from one is
worse than the display bug that rule prevents. The chain tail also outranks the
launch seed, which is written once at construction and never moves off a
`/clear`.

A pin no transcript backs is dropped, because the fallback branch keeps
`--session-id <this.id>` and would collide. A synthetic `restored-<fragment>`
id from socket discovery is dropped too, and logged: it fails claude's `uuid`
token pattern, so the renderer would emit the unpinned command while the caller
believed otherwise.

Tests cover each gate and the rendered command. Four of them fail against the
unfixed source; the remote and docker ones were separately checked against a
build with only that guard removed, since they pass on master for the wrong
reason.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Michael Grundberg
2026-09-21 15:36:17 +02:00
co-authored by Claude Opus 5
parent 9466acfc1a
commit 47e7935274
3 changed files with 441 additions and 17 deletions
+102 -17
View File
@@ -62,6 +62,8 @@ import {
type SessionWriteOptions,
} from './types.js';
import { resolveAndClaimOmpSessionId } from './utils/omp-session-resolver.js';
import { claudeTranscriptExists } from './utils/claude-transcript.js';
import { matchesPattern } from './config/cli-registry/patterns.js';
import { probeDockerCliVersion } from './docker-hosts.js';
import { probeRemoteCliVersion } from './remote-hosts.js';
import type { TerminalMultiplexer, MuxSession } from './mux-interface.js';
@@ -1749,7 +1751,7 @@ export class Session extends EventEmitter {
// `options.respawnPaneOptions` was built eagerly before this dead-pane
// check ran, so it still carries the pre-pin ompConfig; rebuild it.
this._pinOmpRespawnId();
const newPid = await mux.respawnPane(this._buildRespawnPaneOptions());
const newPid = await mux.respawnPane(await this._buildRespawnPaneOptionsWithResumePin());
if (!newPid) {
console.error('[Session] Failed to respawn pane, will create new session');
needsNewSession = true;
@@ -1765,7 +1767,17 @@ export class Session extends EventEmitter {
if (isRestored) {
console.log('[Session] Attaching to existing mux session:', this._muxSession!.muxName);
} else {
// Create a new mux session
// Create a new mux session. When this is the FALLBACK after a failed
// respawn, the eagerly-built create options still carry the unpinned
// launch seed, so a session whose transcript exists would meet the same
// `--session-id ... already in use` refusal the respawn just lost to —
// the recovery of last resort failing for the very reason it was needed.
// A genuinely new session has no chain and no transcript, so the pin
// resolves to its own id and the command shape is unchanged.
if (needsNewSession) {
const pinned = (await this._buildRespawnPaneOptionsWithResumePin()).resumeSessionId;
if (pinned) options.createSessionOptions.resumeSessionId = pinned;
}
this._muxSession = await mux.createSession(options.createSessionOptions);
console.log('[Session] Created mux session:', this._muxSession.muxName);
// No extra sleep — createSession() already waits for tmux readiness
@@ -1878,21 +1890,7 @@ export class Session extends EventEmitter {
}
this._pinOmpRespawnId();
const options = this._buildRespawnPaneOptions();
// Unlike the dead-pane respawn, this one kills a WORKING pane whose conversation
// already has a transcript, and a CLI that launches with `--session-id <id>` refuses
// an id that is already in use (claude: `Error: Session ID ... is already in use.`),
// which turned an endpoint switch into a dead pane and a lost session. A launch that
// declares a `fallback` chain renders `resume || new` once a resume id is set, the
// same `--resume <id> || --session-id <id>` shape the docker and remote pane commands
// already use, so pin the live conversation id for THIS respawn only. The registry
// shape is the gate, not the CLI's name: an entry whose resume id is minted by the
// CLI itself (codex/pi/omp/grok) never declares that chain, and its resume field is
// read from its own `<Mode>Config` rather than this top-level one anyway.
if (!options.resumeSessionId && getCli(this.mode)?.launch.chain === 'fallback') {
options.resumeSessionId = this._claudeSessionId ?? this.id;
}
const newPid = await mux.respawnPane(options);
const newPid = await mux.respawnPane(await this._buildRespawnPaneOptionsWithResumePin());
if (!newPid) {
console.error('[Session] restartCli: respawnPane failed for', this._muxSession.muxName);
return false;
@@ -1947,6 +1945,93 @@ export class Session extends EventEmitter {
return this._withCustomModelLaunchModel(options);
}
/**
* Respawn options for a pane whose command is being REPLACED, with the
* conversation pinned so the relaunch resumes rather than collides.
*
* A CLI that launches with `--session-id <id>` refuses an id that is already
* in use (claude: `Error: Session ID ... is already in use.`), and every
* session whose agent has been prompted owns a transcript under that id. So
* relaunching such a pane with the bare launch line fails, the pane dies
* again immediately, and the user's conversation is stranded. A launch that
* declares a `fallback` chain renders `resume || new` once a resume id is
* set, which is the shape that survives both cases.
*
* Four conditions gate the pin, each protecting against a way of resuming the
* WRONG conversation or of making a working relaunch fail.
*
* ⚠️ **A remote or docker session is never pinned.** Unlike `restartCli()`,
* whose route refuses both, the dead-pane respawn is reached by every session
* shape. Their pane commands (`buildRemoteLaunchCommand`,
* `claudeDockerPaneCommand`) already render a SELF-HEALING
* `--session-id <sid> || --resume <sid>`, and both flip to resume-first the
* moment the resume id differs from the session id. The conversation lives on
* the far side, so a local id pinned onto it resolves to nothing there, the
* resume fails, and the `--session-id` fallback then collides with the
* transcript the far side really does hold — both branches fail and the pane
* dies. `_pinOmpRespawnId()` refuses remote for the same reason.
*
* ⚠️ **The id comes from the conversation CHAIN, not from
* `_claudeSessionId`.** That field holds either a first-hand id from the
* CLI's own hook payload or a history correlation, which is a guess keyed on
* the working directory. `_recordClaudeSessionInChain()` refuses a guess
* precisely so it cannot "write a foreign conversation into this pane's
* permanent record", and launching from one would do worse than the display
* bug that rule exists to prevent: the relaunched CLI would open and WRITE to
* a conversation that was never this pane's. The chain's tail is the live
* conversation and is hook-vouched, so it also outranks the launch seed,
* which is written once at construction and never moves off a `/clear`.
*
* ⚠️ **A pin that no transcript backs is dropped.** When the pinned id
* differs from the session id, the fallback branch still carries
* `--session-id <this.id>`; if the resume finds nothing, that fallback
* collides and the pane dies exactly as it did before this pinning existed.
* The create route pre-validates a resume id for the same reason, though it
* additionally requires the transcript be substantial — here mere existence
* is the question, because a one-line transcript still makes `--session-id`
* collide.
*
* The registry shape is the last gate, not the CLI's name: an entry whose
* resume id is minted by the CLI itself (codex/pi/omp/grok) declares no
* `fallback` chain and reads its resume field from its own `<Mode>Config`.
*
* `reattachRemote()` deliberately does NOT call this. It re-runs the remote
* session command, which attaches to the durable remote tmux with the agent
* still inside it and renders no local `--session-id` to collide.
*/
private async _buildRespawnPaneOptionsWithResumePin(): Promise<import('./mux-interface.js').RespawnPaneOptions> {
const options = this._buildRespawnPaneOptions();
if (this._remote || this._docker) return options;
if (getCli(this.mode)?.launch.chain !== 'fallback') return options;
const chainTail = this._claudeSessionChain[this._claudeSessionChain.length - 1];
const pin = chainTail ?? options.resumeSessionId ?? this.id;
// A session Codeman DISCOVERED on the socket rather than created carries a
// synthetic `restored-<fragment>` id, which fails claude's `uuid` token
// pattern. The renderer would silently drop the resume flag and emit the
// unpinned command, so say so here rather than letting the caller believe
// the pane was pinned. Such a pane keeps the pre-existing behaviour.
const resumeIdPattern = getCli(this.mode)?.launch.params?.resumeId;
if (resumeIdPattern?.type === 'token' && !matchesPattern(resumeIdPattern.pattern, pin)) {
console.log(`[Session] Not pinning resume id ${pin} for relaunch: the CLI cannot accept that id shape`);
return options;
}
// Pinning the session's own id renders the self-healing
// `--session-id <id> || --resume <id>`, which needs no transcript to be
// correct: it starts fresh when there is none and resumes when there is.
if (pin !== this.id && !(await claudeTranscriptExists(pin, this._claudeConfigDir()))) {
console.log(`[Session] Not pinning resume id ${pin} for relaunch: no transcript on disk`);
return options;
}
options.resumeSessionId = pin;
return options;
}
/** The session's Claude config dir when it has been relocated (#255), else undefined. */
private _claudeConfigDir(): string | undefined {
return this._envOverrides?.CLAUDE_CONFIG_DIR;
}
/**
* Force the custom-model selection's `launchModel` (pi/omp `custom/<id>`, grok's
* `[model.<name>]` block name) onto the CLI's `model` launch param. Where that param
+57
View File
@@ -0,0 +1,57 @@
/**
* @fileoverview Does a Claude conversation transcript exist on this host?
*
* Claude writes one `<conversation-id>.jsonl` per conversation under
* `<config dir>/projects/<mangled cwd>/`. Two launch decisions turn on whether
* such a file exists: `--resume <id>` needs one, and `--session-id <id>` is
* REFUSED when one exists (`Error: Session ID ... is already in use.`).
*
* The project directory name is derived from the working directory, and a case
* that has been moved or renamed leaves its transcript under the OLD name, so
* the search is across every project directory rather than the one that matches
* the pane's cwd today.
*
* ⚠️ Existence is the whole question here, with no size floor. The create route
* additionally requires ~4 KB before it will resume, which is a "is this
* conversation worth resuming" judgement; for a relaunch the question is the
* opposite one — a one-line transcript still makes `--session-id` collide.
*
* @dependencies none
* @consumedby session (relaunch resume pinning)
*
* @module utils/claude-transcript
*/
import { readdir, stat } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
/** `<config dir>/projects`, honouring a session's relocated `CLAUDE_CONFIG_DIR`. */
export function claudeProjectsDir(configDir?: string): string {
return join(configDir || join(homedir(), '.claude'), 'projects');
}
/**
* True when a transcript for `conversationId` exists under any project
* directory. Returns false for a missing projects dir or an unreadable one:
* the caller's fallback is to skip the resume, which is the safe direction.
*/
export async function claudeTranscriptExists(conversationId: string, configDir?: string): Promise<boolean> {
if (!conversationId) return false;
const projectsDir = claudeProjectsDir(configDir);
let projectDirs: string[];
try {
projectDirs = await readdir(projectsDir);
} catch {
return false;
}
for (const projectDir of projectDirs) {
try {
await stat(join(projectsDir, projectDir, `${conversationId}.jsonl`));
return true;
} catch {
// Not in this project directory; keep looking.
}
}
return false;
}