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

+281
View File
@@ -0,0 +1,281 @@
/**
* @fileoverview Agent inbox routes (src/web/routes/inbox-routes.ts) via app.inject().
*
* The caller is whoever `X-Codeman-Parent-Session` resolves to (live session, same
* owner as the receiver). These tests pin what that decides: who a post is from,
* whether a read marks seen or is a peek, and who may ack. Plus the wait rule (parks
* while nothing is UNSEEN), the full-inbox 409 and the owner-scoped summary.
*
* The routes use the process-wide `agentInbox` and `sessionWaits`; every test resets
* the inbox and cancels its waiters.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import fastifyCookie from '@fastify/cookie';
import { registerInboxRoutes } from '../../src/web/routes/inbox-routes.js';
import { agentInbox, MAX_MESSAGES_PER_INBOX } from '../../src/web/agent-inbox.js';
import { sessionWaits } from '../../src/web/session-wait-registry.js';
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { httpStatusForErrorCode, type ApiErrorCode, type AuthUser } from '../../src/types.js';
import { createMockRouteContext, createMockSession, type MockRouteContext } from '../mocks/index.js';
const RX = 'aaaaaaaa-1111-4111-8111-111111111111';
const TX = 'bbbbbbbb-2222-4222-8222-222222222222';
const OTHER = 'cccccccc-3333-4333-8333-333333333333';
interface Harness {
app: FastifyInstance;
ctx: MockRouteContext;
}
let currentUser: AuthUser | undefined;
async function createHarness(): Promise<Harness> {
const app = Fastify({ logger: false });
await app.register(fastifyCookie);
const ctx = createMockRouteContext({ sessionId: RX });
for (const id of [TX, OTHER]) ctx.sessions.set(id, createMockSession(id) as never);
app.decorateRequest('authUser', undefined);
app.addHook('onRequest', async (req) => {
req.authUser = currentUser;
});
registerInboxRoutes(app, ctx as never);
// server.ts's envelope hook: an error envelope carries its 4xx.
app.addHook('preSerialization', (req, reply, payload: unknown, done) => {
const p = payload as { success?: unknown; errorCode?: unknown } | null;
if (p && p.success === false && reply.statusCode === 200 && typeof p.errorCode === 'string') {
reply.code(httpStatusForErrorCode(p.errorCode as ApiErrorCode));
}
done(null, payload);
});
installRouteErrorHandler(app);
await app.ready();
return { app, ctx };
}
const as = (caller?: string) => (caller ? { 'x-codeman-parent-session': caller } : {});
describe('agent inbox routes', () => {
let h: Harness;
const post = (to: string, text: string, caller?: string) =>
h.app.inject({ method: 'POST', url: `/api/sessions/${to}/inbox`, payload: { text }, headers: as(caller) });
const read = (of: string, caller?: string, query = '') =>
h.app.inject({ method: 'GET', url: `/api/sessions/${of}/inbox${query}`, headers: as(caller) });
const ack = (of: string, ids: string[], caller?: string) =>
h.app.inject({ method: 'POST', url: `/api/sessions/${of}/inbox/ack`, payload: { ids }, headers: as(caller) });
const data = (res: { body: string }) => JSON.parse(res.body).data;
beforeEach(async () => {
agentInbox.resetForTests();
currentUser = undefined;
delete process.env.CODEMAN_MULTIUSER;
h = await createHarness();
});
afterEach(async () => {
for (const id of [RX, TX, OTHER]) sessionWaits.cancelAll(id);
await h.app.close();
agentInbox.resetForTests();
delete process.env.CODEMAN_MULTIUSER;
});
describe('from', () => {
it('is the resolved caller session (exact id or 8-char prefix)', async () => {
expect(data(await post(RX, 'hi', TX)).message.from).toBe(TX);
expect(data(await post(RX, 'hi', TX.slice(0, 8))).message.from).toBe(TX);
});
it('is null (the user) without a header, for an unknown id, or for a short prefix', async () => {
expect(data(await post(RX, 'a')).message.from).toBeNull();
expect(data(await post(RX, 'b', 'dddddddd-0000-4000-8000-000000000000')).message.from).toBeNull();
expect(data(await post(RX, 'c', TX.slice(0, 7))).message.from).toBeNull();
});
it('a body field cannot set it: the schema rejects unknown keys', async () => {
const res = await h.app.inject({
method: 'POST',
url: `/api/sessions/${RX}/inbox`,
payload: { text: 'x', from: TX },
});
expect(res.statusCode).toBe(400);
});
it('multi-user, non-admin: a session the caller cannot see never resolves as the sender', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'alice', role: 'user' };
(h.ctx.sessions.get(RX) as unknown as { owner: string }).owner = 'alice';
(h.ctx.sessions.get(TX) as unknown as { owner: string }).owner = 'bob';
(h.ctx.sessions.get(OTHER) as unknown as { owner: string }).owner = 'alice';
expect(data(await post(RX, 'x', TX)).message.from).toBeNull();
expect(data(await post(RX, 'y', OTHER)).message.from).toBe(OTHER);
// Nor can alice read as bob's session or ack for it: bob's inbox is a 404 to her.
expect((await read(TX, TX)).statusCode).toBe(404);
expect((await ack(TX, ['m'], TX)).statusCode).toBe(404);
});
it('multi-user, admin: may act as any session of the receiver’s owner (admins see everything)', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'root', role: 'admin' };
(h.ctx.sessions.get(RX) as unknown as { owner: string }).owner = 'bob';
(h.ctx.sessions.get(TX) as unknown as { owner: string }).owner = 'bob';
expect(data(await post(RX, 'x', TX)).message.from).toBe(TX);
expect(data(await read(RX, RX)).receiver).toBe(true);
});
it('multi-user: a session of another owner never resolves as the sender', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'alice', role: 'admin' };
(h.ctx.sessions.get(RX) as unknown as { owner: string }).owner = 'alice';
(h.ctx.sessions.get(TX) as unknown as { owner: string }).owner = 'bob';
(h.ctx.sessions.get(OTHER) as unknown as { owner: string }).owner = 'alice';
expect(data(await post(RX, 'x', TX)).message.from).toBeNull();
expect(data(await post(RX, 'y', OTHER)).message.from).toBe(OTHER);
});
});
describe('post', () => {
it('keeps multi-line text as data', async () => {
await post(RX, 'one\ntwo\n', TX);
expect(data(await read(RX, RX)).messages[0].text).toBe('one\ntwo\n');
});
it('a full inbox is 409 CONFLICT with a clear message, and the oldest stays', async () => {
const first = data(await post(RX, 'first')).message.id;
for (let i = 1; i < MAX_MESSAGES_PER_INBOX; i++) agentInbox.post(RX, null, String(i));
const res = await post(RX, 'one too many');
expect(res.statusCode).toBe(409);
expect(JSON.parse(res.body)).toMatchObject({ errorCode: 'CONFLICT' });
expect(JSON.parse(res.body).error).toMatch(/full .*Nothing was stored/);
expect(data(await read(RX)).messages[0].id).toBe(first);
});
it('a message over the byte cap is 400 with the store’s hint, multi-byte or not', async () => {
for (const text of ['é'.repeat(8193), 'x'.repeat(16_385)]) {
const res = await post(RX, text);
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).error).toMatch(/Write it to a file in the workspace and post the path/);
}
});
it('404 for an unknown session', async () => {
expect((await post('nope', 'x')).statusCode).toBe(404);
});
});
describe('read', () => {
it('only the receiver marks seen; a coordinator read is a peek', async () => {
await post(RX, 'task', TX);
const peek = data(await read(RX, TX));
expect(peek).toMatchObject({ receiver: false, pending: 1, unseen: 1 });
expect(data(await read(RX)).unseen).toBe(1);
const own = data(await read(RX, RX));
expect(own).toMatchObject({ receiver: true, pending: 1, unseen: 0 });
expect(own.messages[0].seen).toBe(false);
expect(data(await read(RX, RX)).messages[0].seen).toBe(true);
});
it('?wait= parks while nothing is unseen, even with a seen-but-unacked message', async () => {
await post(RX, 'already seen', TX);
await read(RX, RX);
const parked = read(RX, RX, '?wait=5000');
await new Promise((r) => setTimeout(r, 30));
expect(sessionWaits.inboxWaiterCount(RX, true)).toBe(1);
await post(RX, 'new', TX);
const res = data(await parked);
expect(res.wait).toMatchObject({ posted: true, timedOut: false });
expect(res.messages.map((m: { text: string; seen: boolean }) => [m.text, m.seen])).toEqual([
['already seen', true],
['new', false],
]);
});
it('?wait= answers at once when something is unseen', async () => {
await post(RX, 'm', TX);
const res = data(await read(RX, RX, '?wait=60000'));
expect(res.wait).toMatchObject({ immediate: true, waitedMs: 0, timeoutMs: 60000 });
});
it('?wait= runs out as a 200 with timedOut, clamped to the wait floor', async () => {
const res = await read(RX, RX, '?wait=1');
expect(res.statusCode).toBe(200);
expect(data(res).wait).toMatchObject({ timedOut: true, timeoutMs: 1000 });
expect(res.headers['cache-control']).toBe('no-store');
});
it('?wait= rejects junk', async () => {
expect((await read(RX, RX, '?wait=-5')).statusCode).toBe(400);
expect((await read(RX, RX, '?wait=abc')).statusCode).toBe(400);
});
it('a parked read on a session that goes away answers ended, with an empty inbox', async () => {
await post(RX, 'x');
await read(RX, RX);
const parked = read(RX, RX, '?wait=5000');
await new Promise((r) => setTimeout(r, 30));
// What server.ts does on delete: drop the inbox, then cancel the waiters.
agentInbox.drop(RX);
sessionWaits.cancelAll(RX);
const res = data(await parked);
expect(res.wait).toMatchObject({ ended: true });
expect(res.messages).toEqual([]);
});
});
describe('ack', () => {
it('removes by id for the receiver, idempotently', async () => {
const id = data(await post(RX, 'm', TX)).message.id;
expect(data(await ack(RX, [id], RX))).toMatchObject({ removed: 1, pending: 0 });
const again = await ack(RX, [id, 'never-existed'], RX);
expect(again.statusCode).toBe(200);
expect(data(again)).toMatchObject({ removed: 0, pending: 0 });
});
it('is 403 for anyone but the receiver, and removes nothing', async () => {
const id = data(await post(RX, 'm', TX)).message.id;
for (const caller of [TX, undefined]) {
const res = await ack(RX, [id], caller);
expect(res.statusCode).toBe(403);
expect(JSON.parse(res.body).errorCode).toBe('FORBIDDEN');
}
expect(agentInbox.pendingCount(RX)).toBe(1);
});
it('rejects an empty id list', async () => {
expect((await ack(RX, [], RX)).statusCode).toBe(400);
});
});
describe('summary', () => {
it('reports counts and parked per session, never text', async () => {
await post(RX, 'secret', TX);
await post(TX, 'other secret', RX);
await read(TX, TX);
const parked = read(OTHER, OTHER, '?wait=5000');
// A coordinator peeking with ?wait= is not the receiver: not "parked".
const peeking = read(RX, TX, '?wait=5000');
await new Promise((r) => setTimeout(r, 30));
const res = await h.app.inject({ method: 'GET', url: '/api/agent-inbox/summary' });
expect(res.body).not.toContain('secret');
expect(data(res).sessions).toEqual({
[RX]: { pending: 1, unseen: 1, oldestUnseenAt: expect.any(Number), parked: false },
[TX]: { pending: 1, unseen: 0, oldestUnseenAt: null, parked: false },
[OTHER]: { pending: 0, unseen: 0, oldestUnseenAt: null, parked: true },
});
sessionWaits.cancelAll(OTHER);
sessionWaits.cancelAll(RX);
await Promise.all([parked, peeking]);
});
it('multi-user: lists only sessions the caller can see', async () => {
process.env.CODEMAN_MULTIUSER = '1';
currentUser = { username: 'alice', role: 'user' };
(h.ctx.sessions.get(RX) as unknown as { owner: string }).owner = 'alice';
(h.ctx.sessions.get(TX) as unknown as { owner: string }).owner = 'bob';
agentInbox.post(RX, null, 'mine');
agentInbox.post(TX, null, 'bob’s');
const res = await h.app.inject({ method: 'GET', url: '/api/agent-inbox/summary' });
expect(Object.keys(data(res).sessions)).toEqual([RX]);
});
});
});
+12
View File
@@ -26,6 +26,7 @@ import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
import { ApiErrorCode, httpStatusForErrorCode } from '../../src/types.js';
import { Session } from '../../src/session.js';
import { agentInbox } from '../../src/web/agent-inbox.js';
// Mock execFile so the send-key route's `tmux` invocation is observable (not run for real).
const { execFile } = vi.hoisted(() => ({ execFile: vi.fn() }));
@@ -985,6 +986,17 @@ describe('session-routes', () => {
expect(harness.ctx.broadcast).toHaveBeenCalledWith('session:deleted', { id: 'ghost-session' });
});
it('a persisted-only delete drops the agent inbox the detach kept', async () => {
// Detach (killMux=false) keeps the inbox; retiring the row afterwards is the delete.
agentInbox.resetForTests();
agentInbox.post('ghost-session', null, 'mail from before the detach');
vi.mocked(harness.ctx.store.getSession).mockReturnValueOnce({ id: 'ghost-session', owner: undefined } as never);
const res = await harness.app.inject({ method: 'DELETE', url: '/api/sessions/ghost-session' });
expect(res.statusCode).toBe(200);
expect(agentInbox.pendingCount('ghost-session')).toBe(0);
agentInbox.resetForTests();
});
it('404s a persisted-only session id the state store does not recognize either', async () => {
vi.mocked(harness.ctx.store.getSession).mockReturnValueOnce(null);
const res = await harness.app.inject({
@@ -47,13 +47,15 @@ const { EXISTING_SETTINGS, subagentWatcher, imageWatcher, workflowRunWatcher } =
};
};
return {
// Persisted settings.json for these tests: two watchers ON, subagent tracking OFF.
// Persisted settings.json for these tests: two watchers ON, subagent tracking OFF,
// agent inbox snapshot ON.
EXISTING_SETTINGS: {
subagentTrackingEnabled: false,
imageWatcherEnabled: true,
showUltracodeAgents: true,
promptCacheKeepWarm: false,
promptCacheKeepWarmMaxHours: 2,
agentInboxPersistEnabled: true,
},
subagentWatcher: makeWatcher(false),
imageWatcher: makeWatcher(true),
@@ -61,6 +63,9 @@ const { EXISTING_SETTINGS, subagentWatcher, imageWatcher, workflowRunWatcher } =
};
});
// setEnabled(false) deletes the snapshot file, so a wrong default here loses mail.
const { agentInboxPersistence } = vi.hoisted(() => ({ agentInboxPersistence: { setEnabled: vi.fn() } }));
vi.mock('node:fs/promises', () => ({
default: {
readFile: vi.fn(async () => JSON.stringify(EXISTING_SETTINGS)),
@@ -76,6 +81,7 @@ vi.mock('node:fs', async (importOriginal) => {
vi.mock('../../src/subagent-watcher.js', () => ({ subagentWatcher }));
vi.mock('../../src/image-watcher.js', () => ({ imageWatcher }));
vi.mock('../../src/workflow-run-watcher.js', () => ({ workflowRunWatcher }));
vi.mock('../../src/web/agent-inbox-persistence.js', () => ({ agentInboxPersistence }));
describe('PUT /api/settings — partial body must not reset service toggles', () => {
let harness: RouteTestHarness;
@@ -87,6 +93,7 @@ describe('PUT /api/settings — partial body must not reset service toggles', ()
w.stop.mockClear();
w.__resetRunning(); // running state, not just call records — see makeWatcher
}
agentInboxPersistence.setEnabled.mockClear();
});
afterEach(async () => {
@@ -167,4 +174,25 @@ describe('PUT /api/settings — partial body must not reset service toggles', ()
expect((await put({ promptCacheKeepWarm: true })).statusCode).toBe(200);
expect(harness.ctx.keepWarm.rescheduleAll).toHaveBeenCalledTimes(2);
});
it('keeps the agent inbox snapshot on when the body omits its key', async () => {
const res = await harness.app.inject({
method: 'PUT',
url: '/api/settings',
payload: { showPlanUsageLimits: true },
});
expect(res.statusCode).toBe(200);
expect(agentInboxPersistence.setEnabled).toHaveBeenCalledWith(true);
expect(agentInboxPersistence.setEnabled).not.toHaveBeenCalledWith(false);
});
it('switches the agent inbox snapshot off when the body says so', async () => {
const res = await harness.app.inject({
method: 'PUT',
url: '/api/settings',
payload: { agentInboxPersistEnabled: false },
});
expect(res.statusCode).toBe(200);
expect(agentInboxPersistence.setEnabled).toHaveBeenCalledWith(false);
});
});
+55
View File
@@ -11,6 +11,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
import { registerSystemRoutes } from '../../src/web/routes/system-routes.js';
import { agentInbox } from '../../src/web/agent-inbox.js';
const hostSensors = vi.hoisted(() => ({ readHostSensors: vi.fn(async (_request: unknown) => ({})) }));
vi.mock('../../src/host-sensors.js', () => hostSensors);
@@ -360,6 +361,60 @@ describe('system-routes', () => {
expect(harness.ctx.store.cleanupSessionsByIds).toHaveBeenCalledWith(new Set());
expect(runStaleSessionCleanup).toHaveBeenCalledOnce();
});
it('drops the agent inbox of every record it removes, and only those', async () => {
agentInbox.resetForTests();
agentInbox.post('stale-detached', null, 'mail for a detached session');
agentInbox.post('still-kept', null, 'mail for a session that stays');
harness.ctx.tabLayouts.runStaleSessionCleanup = vi.fn(
async (_activeIds: Set<string>, action: (ids: ReadonlySet<string>) => unknown) =>
action(new Set(['stale-detached']))
);
vi.mocked(harness.ctx.store.cleanupSessionsByIds).mockReturnValueOnce({
count: 1,
cleaned: [{ id: 'stale-detached', name: 'w9-gone' }],
});
try {
const res = await harness.app.inject({ method: 'POST', url: '/api/cleanup-state' });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.body).cleanedSessions).toBe(1);
expect(agentInbox.pendingCount('stale-detached')).toBe(0);
expect(agentInbox.pendingCount('still-kept')).toBe(1);
} finally {
agentInbox.resetForTests();
}
});
it('keeps the agent inbox of a removed record whose tmux session the multiplexer still lists', async () => {
// Detach keeps the tmux session and its mux entry; the next boot re-adopts it
// under the same id even without a state.json record, so its mail must survive.
agentInbox.resetForTests();
agentInbox.post('stale-detached', null, 'mail for a session nothing can bring back');
agentInbox.post('pane-still-alive', null, 'mail for a detached pane that boot re-adopts');
harness.ctx.tabLayouts.runStaleSessionCleanup = vi.fn(
async (_activeIds: Set<string>, action: (ids: ReadonlySet<string>) => unknown) =>
action(new Set(['stale-detached', 'pane-still-alive']))
);
vi.mocked(harness.ctx.store.cleanupSessionsByIds).mockReturnValueOnce({
count: 2,
cleaned: [
{ id: 'stale-detached', name: 'w9-gone' },
{ id: 'pane-still-alive', name: 'w8-detached' },
],
});
// The harness is rebuilt per test, so this mock does not leak into the next one.
vi.mocked(harness.ctx.mux.getSession).mockImplementation(((id: string) =>
id === 'pane-still-alive' ? { sessionId: id } : null) as unknown as typeof harness.ctx.mux.getSession);
try {
const res = await harness.app.inject({ method: 'POST', url: '/api/cleanup-state' });
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.body).cleanedSessions).toBe(2);
expect(agentInbox.pendingCount('stale-detached')).toBe(0);
expect(agentInbox.pendingCount('pane-still-alive')).toBe(1);
} finally {
agentInbox.resetForTests();
}
});
});
// ========== GET /api/subagents ==========