Merge pull request #690: feat(agent): per-session agent inbox (discussion #558)

Conflict in src/web/routes/session-routes.ts (the import block) resolved
by keeping both sides: #680's claudeProjectDirName import stays, and the
fastify import takes #690's form without FastifyReply, since #690 moved
abortOnClientHangUp (its only user here) into route-helpers.ts.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer committed 2026-10-24 15:29:15 +02:00
commit e739b2e9d4
39 files changed
+2664 -86

No files matched your search

+45 -2
View File
@@ -117,6 +117,8 @@ import {
} from './session-listener-wiring.js';
import { sessionWaits } from './session-wait-registry.js';
import { intentStore } from '../intent-store.js';
import { agentInbox } from './agent-inbox.js';
import { agentInboxPersistence } from './agent-inbox-persistence.js';
import { AI_CHECK_MODEL } from '../config/ai-defaults.js';
import { approvalInbox } from './approval-inbox.js';
import { SCREEN_BLOCKED_SOURCE } from './screen-blocked.js';
@@ -202,6 +204,7 @@ import {
registerScheduledRoutes,
registerHookEventRoutes,
registerApprovalRoutes,
registerInboxRoutes,
registerRebootRestoreRoutes,
registerReadMyMindRoutes,
registerGitStatusRoutes,
@@ -1232,6 +1235,7 @@ export class WebServer extends EventEmitter {
registerScheduledRoutes(this.app, ctx);
registerHookEventRoutes(this.app, ctx);
registerApprovalRoutes(this.app, ctx);
registerInboxRoutes(this.app, ctx);
registerRebootRestoreRoutes(this.app, ctx);
registerReadMyMindRoutes(this.app, ctx);
registerGitStatusRoutes(this.app, ctx);
@@ -1689,6 +1693,11 @@ export class WebServer extends EventEmitter {
// The 'exit' here is NOT redundant with the PTY-exit listener: listeners are
// detached a few lines above, before `session.stop()`, so on a delete the
// session's own exit event never reaches the registry.
// The agent inbox goes with a DELETED session only. killMux=false is shutdown or
// detach: mail posted before that is still there when the session is re-attached
// (while detached, the routes answer 404, so nothing new arrives). Before
// cancelAll, so a reader released by it reads an empty inbox.
if (killMux) agentInbox.drop(sessionId);
sessionWaits.notifySignal(sessionId, 'exit');
sessionWaits.cancelAll(sessionId);
approvalInbox.resolveForSession(sessionId, 'session_ended');
@@ -2214,6 +2223,13 @@ export class WebServer extends EventEmitter {
return settings.agentSkillEnabled === true;
}
// Whether pending agent-inbox mail is snapshotted to disk (synced
// `agentInboxPersistEnabled` setting). Default OFF: an absent key writes nothing.
private async getAgentInboxPersistEnabled(): Promise<boolean> {
const settings = await this.readSettings();
return settings.agentInboxPersistEnabled === true;
}
// Whether a Claude session installs Codeman's hooks block into its workspace
// (synced `workspaceHooksEnabled` setting). Default ON — an absent key means a
// user who has never seen this setting, and OFF for them would mean no tab
@@ -3044,6 +3060,10 @@ export class WebServer extends EventEmitter {
// This prevents race conditions where clients connect before state is ready
// CRITICAL: Skip in test mode to prevent tests from picking up user sessions
if (!this.testMode) {
// Pending agent mail first (opt-in snapshot), so it is in place before any
// route can answer. Pruned against the restored sessions in finalizeRestoredState.
const restoredMail = agentInboxPersistence.load(await this.getAgentInboxPersistEnabled());
if (restoredMail > 0) console.log(`[AgentInbox] restored ${restoredMail} pending message(s)`);
const restored = await this.restoreMuxSessions();
await this.finalizeRestoredState(restored);
@@ -4016,6 +4036,20 @@ export class WebServer extends EventEmitter {
this.tabLayouts.markRestorationComplete();
await this.cleanupStaleSessions();
await this.tabLayouts.reconcileAfterRestoration();
// Same gate as the tab layouts: only a restore that succeeded may decide which
// inboxes are orphans. A failed one returns above and leaves every message alone.
// Kept: live sessions plus every record state.json still holds (a session that
// was not re-adopted this boot but is kept for recovery keeps its mail), plus the
// sessions on the reboot-restore offer. `cleanupStaleSessions()` above has already
// pruned their records, and a rebuild reuses the old id, so without them a restored
// session would come back to an empty inbox. The 12 h TTL bounds what is never rebuilt.
const keep = new Set([
...this.sessions.keys(),
...Object.keys(this.store.getSessions()),
...rebootRestoreRegistry.list(() => true).map((entry) => entry.sessionId),
]);
const pruned = agentInbox.pruneExcept(keep);
if (pruned > 0) console.log(`[AgentInbox] dropped ${pruned} inbox(es) of sessions that did not come back`);
}
/**
@@ -4195,8 +4229,11 @@ export class WebServer extends EventEmitter {
sessionWaits.cancelEverything();
approvalInbox.stop();
this.keepWarmService.stop();
// A post within the debounce window before shutdown would otherwise not reach disk.
// Flushed again after `app.close()` below, for a post that lands in between.
agentInboxPersistence.flush();
// Same reason as `cancelEverything` above: an in-flight wake is awaited by a request,
// and `app.close()` (the last line of this method) does not abort in-flight requests —
// and `app.close()` (at the end of this method) does not abort in-flight requests,
// so without this a restart during a wake waits out the readiness poll.
this.remoteWake?.stop();
@@ -4341,7 +4378,13 @@ export class WebServer extends EventEmitter {
// Dispose push store (flush pending saves)
this.pushStore.dispose();
await this.app.close();
try {
await this.app.close();
} finally {
// The routes answer until `app.close()` returns, so a post after the flush above
// would otherwise sit in an unref'd debounce timer and never reach disk.
agentInboxPersistence.flush();
}
}
}