mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-10-05 06:59:42 +02:00
feat(session): close sessions whose agent exited cleanly (#486)
* fix(cleanup): keep .claude-images while a sibling session uses the same dir
cleanupSession() recursively removes {workingDir}/.claude-images. That
directory belongs to the working directory rather than to the session, and
several sessions routinely share one case directory, so closing one session
deleted the pasted images a live sibling still referred to.
The removal now runs only when no other live session has the same working
directory. A session that is itself being cleaned up does not count as live,
so two sessions of one case closed together still remove the dir.
Split out ahead of the exited-agent sweep for Ark0N/Codeman#446, which closes
sessions unattended and would otherwise make the loss routine.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* feat(session): close sessions whose agent exited cleanly (#446)
Part 2 of Ark0N/Codeman#446. Part 1 records an exited agent as
SessionState.paneExit. A session whose agent the user ended with /exit is
now closed through cleanupSession(), the same path the X button takes, so
finished sessions stop piling up on the board. The lifecycle log records
the reason as "agent exited cleanly (status 0)", and the conversation stays
resumable from the Resume list.
shouldCloseCleanlyExitedSession() in the new pure module pane-exit-sweep.ts
holds the rule. It closes a session only when all of these hold:
- The exit status is an explicit numeric 0 with no signal. An absent status
is how a SIGKILL presents on tmux 3.2a, so it counts as unknown and the
row stays. A non-zero status or any signal also keeps the row, with the
exit code on the tab.
- Two authoritative pane reads agreed on that exit.
TmuxManager.getPaneExitReadCount() counts them, and a failed, empty or
skipped read neither confirms nor resets the count.
- No start, attach or relaunch is running for the pane.
Session.paneLifecycleInFlight covers _setupOrAttachMuxSession(), whose
dead-pane branch revives an exited pane on purpose, and restartCli().
setPaneExit() already scopes paneExit to local mux-backed sessions, so
remote, docker and direct-PTY sessions are never closed.
planRebootRestore() now refuses a record whose persisted paneExit is a
clean exit. That covers an agent that exited just before a reboot, before
the sweep reached it. A crashed agent's record stays eligible, like its row.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(web): show "exited" on the phone overview and desktop home rail (#446)
Part 1 of Ark0N/Codeman#446 taught the tab strip and the rich rail rows
to say that a session's agent has exited. The phone overview and the
desktop home rail still said "idle", beside a green or pulsing dot.
_mobileOverviewExit() in mobile-overview.js is now the one rule for all
three surfaces, and _sidebarRichRow() uses it as well. It changes what a
row shows and leaves the row's state alone, because the state still picks
the section and the sort order. An exited row gets an "exited" pill, a
neutral dot and row accent, and a duration measured from when the server
first saw the pane dead. A pending permission prompt or question still
wins, as it does on the tab.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(cleanup): close the gaps review found in the #446 sweep and image guard
Four fixes from a dual review of Ark0N/Codeman#446 part 2.
- The .claude-images guard compares canonical paths, so a sibling that
reaches the same directory through a symlink keeps it. Its comment used to
say that case only missed a deletion; it caused one.
- A detached session counts as a live sibling. DELETE ?killMux=false removes
it from the server's map while its pane keeps running, so the guard now
reads persisted records too, and exempts only sessions being killed rather
than every session in cleaningUp.
- A session being closed refuses startInteractive() and startShell(). The
/interactive route awaits listener setup before the start, and a start
that raced the close could launch a CLI in a tmux session whose record was
then deleted. A failed close clears the mark again.
- The clean-exit sweep tries each exit once, keyed by session id and the
exit's at stamp, so a close that fails is not retried and logged every
two seconds.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
* fix(session): keep a clean exit that lands within 10 s of a pane start (#446)
A CLI that prints a startup error ("not logged in", a bad profile, a config
error) and exits 0 used to lose its tab, and the error with it, about 4 s
after launch. The sweep now keeps any clean exit that lands within
CLEAN_EXIT_MIN_PANE_LIFETIME_MS (10 s) of the last start, attach or relaunch
finishing (Session.paneStartedAt, stamped when _withPaneLifecycle ends). The
row stays as "exited (0)" for the user to read and close.
Verified on an isolated instance: a shell that ran `exit 0` 2 s after start
kept its row, one that exited after 13 s was closed.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
d67da5c9d0
commit
b80d47aff8
+97
-3
@@ -33,7 +33,8 @@ import fastifyCookie from '@fastify/cookie';
|
||||
import fastifyStatic from '@fastify/static';
|
||||
import fastifyWebsocket from '@fastify/websocket';
|
||||
import fastifyMultipart from '@fastify/multipart';
|
||||
import { startPasteImageGc } from './paste-image-gc.js';
|
||||
import { pasteImageDirInUseByOtherSession, startPasteImageGc } from './paste-image-gc.js';
|
||||
import { CLEAN_EXIT_CLOSE_REASON, shouldCloseCleanlyExitedSession } from '../pane-exit-sweep.js';
|
||||
import { join, dirname } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { existsSync, mkdirSync, readFileSync, chmodSync, rmSync, statSync } from 'node:fs';
|
||||
@@ -1321,16 +1322,32 @@ export class WebServer extends EventEmitter {
|
||||
// Clean up all resources associated with a session
|
||||
// Track sessions currently being cleaned up to prevent concurrent cleanup races
|
||||
private cleaningUp: Set<string> = new Set();
|
||||
/**
|
||||
* The subset of {@link cleaningUp} whose tmux session is being KILLED rather
|
||||
* than detached. The paste-image guard needs the difference: a detaching
|
||||
* session keeps running in tmux and still uses its working directory.
|
||||
*/
|
||||
private killingSessions: Set<string> = new Set();
|
||||
|
||||
private async cleanupSession(sessionId: string, killMux: boolean = true, reason?: string): Promise<void> {
|
||||
// Guard against concurrent cleanup of the same session
|
||||
if (this.cleaningUp.has(sessionId)) return;
|
||||
this.cleaningUp.add(sessionId);
|
||||
if (killMux) this.killingSessions.add(sessionId);
|
||||
// Refuse a start or attach from here on (Ark0N/Codeman#446): a start that
|
||||
// raced this cleanup would launch a CLI in a tmux session whose record is
|
||||
// about to be deleted, leaving an orphan the next boot rediscovers.
|
||||
const session = this.sessions.get(sessionId);
|
||||
session?.markClosing(true);
|
||||
|
||||
try {
|
||||
await this._doCleanupSession(sessionId, killMux, reason);
|
||||
} finally {
|
||||
this.cleaningUp.delete(sessionId);
|
||||
this.killingSessions.delete(sessionId);
|
||||
// A cleanup that failed leaves the session on the board, so it must be
|
||||
// startable again.
|
||||
if (this.sessions.get(sessionId) === session) session?.markClosing(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1482,8 +1499,24 @@ export class WebServer extends EventEmitter {
|
||||
attachmentRegistry.clearSession(sessionId);
|
||||
// Stop watching for images in this session's directory
|
||||
imageWatcher.unwatchSession(sessionId);
|
||||
// Clean up pasted images directory for this session
|
||||
if (killMux && session.workingDir) {
|
||||
// Clean up pasted images directory for this session. The dir belongs to the
|
||||
// working directory rather than the session, so it stays while another live
|
||||
// session in the same case still uses it (Ark0N/Codeman#446).
|
||||
if (
|
||||
killMux &&
|
||||
session.workingDir &&
|
||||
!pasteImageDirInUseByOtherSession({
|
||||
live: this.sessions.values(),
|
||||
persisted: Object.entries(this.store.getSessions()).map(([id, record]) => ({
|
||||
id,
|
||||
workingDir: record.workingDir,
|
||||
status: record.status,
|
||||
})),
|
||||
closingId: sessionId,
|
||||
workingDir: session.workingDir,
|
||||
killing: this.killingSessions,
|
||||
})
|
||||
) {
|
||||
const pasteImageDir = join(session.workingDir, '.claude-images');
|
||||
try {
|
||||
rmSync(pasteImageDir, { recursive: true, force: true });
|
||||
@@ -2502,6 +2535,9 @@ export class WebServer extends EventEmitter {
|
||||
* Nothing here touches `status` or `pid`. `status: 'error'` belongs to the
|
||||
* PTY-exit breaker and makes the browser offer a restart, and a null `pid` is
|
||||
* what makes the browser re-attach and launch a fresh CLI.
|
||||
*
|
||||
* Once the records are current, {@link closeCleanlyExitedSessions} closes the
|
||||
* sessions whose agent the user ended.
|
||||
*/
|
||||
private applyPaneExits(): void {
|
||||
const getPaneExit = this.mux.getPaneExit?.bind(this.mux);
|
||||
@@ -2515,6 +2551,63 @@ export class WebServer extends EventEmitter {
|
||||
this.persistSessionState(session);
|
||||
this.broadcastSessionStateDebounced(session.id);
|
||||
}
|
||||
this.closeCleanlyExitedSessions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Close every session whose agent exited cleanly, through the same
|
||||
* `cleanupSession()` the X button uses (Ark0N/Codeman#446). A pinned session
|
||||
* is demoted to `status: 'stopped'` there rather than removed, and either way
|
||||
* the reboot restore stops offering it back. The conversation stays
|
||||
* resumable, since the Resume list reads the lifecycle log and the transcript
|
||||
* files, and the pane owns neither.
|
||||
*
|
||||
* `shouldCloseCleanlyExitedSession()` (`pane-exit-sweep.ts`) holds the rule:
|
||||
* an explicit status of 0, confirmed by more than one pane read, with no
|
||||
* start or attach in flight and not within seconds of one (a startup error). A crashed agent keeps its row with the exit
|
||||
* code on it. `session.paneExit` is already scoped to local mux-backed
|
||||
* sessions by `setPaneExit()`, so a remote, docker or direct-PTY session is
|
||||
* never closed here.
|
||||
*
|
||||
* The close runs in the background. `cleanupSession()` ignores a second call
|
||||
* for a session it is already closing, and the `closing` check below keeps
|
||||
* the next tick from queueing one.
|
||||
*
|
||||
* Each exit is attempted ONCE, keyed by session id and the exit's `at`
|
||||
* stamp. A close that fails leaves the session on the board with its exit
|
||||
* badge, which is where a crashed agent's row would be too, rather than
|
||||
* retrying and logging every two seconds. A new exit in the same pane has a
|
||||
* new `at` and gets its own attempt.
|
||||
*/
|
||||
/** Exits the clean-exit sweep has already tried to close, as `<sessionId>:<exit.at>`. */
|
||||
private cleanExitCloseAttempts: Set<string> = new Set();
|
||||
|
||||
private closeCleanlyExitedSessions(): void {
|
||||
const readCount = this.mux.getPaneExitReadCount?.bind(this.mux);
|
||||
if (!readCount) return;
|
||||
// Forget attempts for sessions that are gone, so the set stays bounded.
|
||||
for (const key of this.cleanExitCloseAttempts) {
|
||||
if (!this.sessions.has(key.slice(0, key.lastIndexOf(':')))) this.cleanExitCloseAttempts.delete(key);
|
||||
}
|
||||
for (const session of [...this.sessions.values()]) {
|
||||
const muxName = session.muxName;
|
||||
if (!muxName) continue;
|
||||
const close = shouldCloseCleanlyExitedSession({
|
||||
paneExit: session.paneExit,
|
||||
confirmingReads: readCount(muxName),
|
||||
paneLifecycleInFlight: session.paneLifecycleInFlight,
|
||||
closing: this.cleaningUp.has(session.id),
|
||||
paneStartedAt: session.paneStartedAt,
|
||||
});
|
||||
if (!close) continue;
|
||||
const attempt = `${session.id}:${session.paneExit?.at ?? 0}`;
|
||||
if (this.cleanExitCloseAttempts.has(attempt)) continue;
|
||||
this.cleanExitCloseAttempts.add(attempt);
|
||||
console.log(`[Server] Closing session ${session.id} (${session.name}): ${CLEAN_EXIT_CLOSE_REASON}`);
|
||||
void this.cleanupSession(session.id, true, CLEAN_EXIT_CLOSE_REASON).catch((err) => {
|
||||
console.error(`[Server] Failed to close cleanly exited session ${session.id}:`, err);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ========== Web Push ==========
|
||||
@@ -3963,6 +4056,7 @@ export class WebServer extends EventEmitter {
|
||||
}
|
||||
this.activePlanOrchestrators.clear();
|
||||
this.cleaningUp.clear();
|
||||
this.killingSessions.clear();
|
||||
|
||||
// Dispose push store (flush pending saves)
|
||||
this.pushStore.dispose();
|
||||
|
||||
Reference in New Issue
Block a user