mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-19 04:39:33 +01:00
Merge master into feat/story-mode
Conflicts were additive registrations (types barrel, routes barrel, server, index.html, settings keys, docs) plus three in session.ts: - master's public claudeConfigDir() method replaces the branch's getter; Story Mode's route now calls it. - writeViaMux keeps master's guarded-turn structure; the composer pairing (_notePastedPrompt) runs after _verifySubmitted in _writeViaMuxNow. - the imports keep both sides. Master now pastes a multi-line API prompt with its line breaks, so _verifySubmitted keeps them too (the same text TmuxManager.sendInput pastes): a prompt Claude Code shows as "[Pasted text #1 +3 lines]" is recognised by its line count, and the CLAUDE.md gotcha no longer says it is missed. The changeset and Settings Reference describe the three reading levels and the prompt bar. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
commit
a516a3d106
775 files changed
+168958
-7674
No files matched your search
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
|
||||
import { assertSandboxedHome, createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { MAX_ROUTE_PARAM_LENGTH } from '../../src/web/route-helpers.js';
|
||||
|
||||
@@ -31,6 +31,10 @@ export async function createRouteTestHarness(
|
||||
registerFn: (app: FastifyInstance, ctx: any) => void,
|
||||
ctxOptions?: { sessionId?: string; authUser?: { username: string; role: 'admin' | 'user' } }
|
||||
): Promise<RouteTestHarness> {
|
||||
// Route tests write the linked-cases, docker and settings files. Refuse to build a harness against
|
||||
// a real home (a bare vitest has no setupFiles), instead of finding out from a wiped registry.
|
||||
assertSandboxedHome('A route test');
|
||||
|
||||
const app = Fastify({ logger: false, routerOptions: { maxParamLength: MAX_ROUTE_PARAM_LENGTH } });
|
||||
|
||||
// Register cookie plugin — some routes access req.cookies
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
/** @fileoverview Agent inspection and guarded input HTTP contracts (no live ports). */
|
||||
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { dirname } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
AGENT_COORDINATION_DISABLED_MESSAGE,
|
||||
registerAgentSessionRoutes,
|
||||
} from '../../src/web/routes/agent-session-routes.js';
|
||||
import { InspectionReader } from '../../src/agent-inspection.js';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
|
||||
let harness: RouteTestHarness;
|
||||
/** The routes are opt-in (`agentCoordinationEnabled`, default OFF); undefined = key absent. */
|
||||
function setEnabled(on: boolean | undefined): void {
|
||||
mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify(on === undefined ? {} : { agentCoordinationEnabled: on }));
|
||||
}
|
||||
beforeEach(() => setEnabled(true));
|
||||
afterEach(async () => {
|
||||
await harness?.app.close();
|
||||
rmSync(SETTINGS_PATH, { force: true });
|
||||
});
|
||||
|
||||
describe('the agentCoordinationEnabled gate', () => {
|
||||
const requests = (id: string) => [
|
||||
{ method: 'GET' as const, url: `/api/sessions/${id}/inspect` },
|
||||
{ method: 'GET' as const, url: `/api/sessions/${id}/inspect?maxBytes=0` },
|
||||
{ method: 'POST' as const, url: `/api/sessions/${id}/stage`, payload: { message: 'hello' } },
|
||||
{
|
||||
method: 'POST' as const,
|
||||
url: `/api/sessions/${id}/submit`,
|
||||
payload: { stageId: '11111111-1111-4111-8111-111111111111', confirmSha: 'a'.repeat(64) },
|
||||
},
|
||||
];
|
||||
it.each([
|
||||
['absent', undefined],
|
||||
['false', false],
|
||||
] as const)('answers 403 naming the setting on every route while it is %s', async (_label, value) => {
|
||||
setEnabled(value);
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes);
|
||||
const session = [...harness.ctx.sessions.values()][0];
|
||||
// A session id that does not exist is refused the same way: the gate runs before lookup.
|
||||
for (const request of [...requests(session.id), ...requests('no-such-session')]) {
|
||||
const result = await harness.app.inject(request);
|
||||
expect(result.statusCode).toBe(403);
|
||||
expect(result.json()).toEqual({
|
||||
success: false,
|
||||
error: AGENT_COORDINATION_DISABLED_MESSAGE,
|
||||
errorCode: 'FORBIDDEN',
|
||||
});
|
||||
}
|
||||
expect(AGENT_COORDINATION_DISABLED_MESSAGE).toContain('agentCoordinationEnabled');
|
||||
expect(session.writeBuffer).toEqual([]);
|
||||
});
|
||||
it('answers on every route once it is on, with no restart', async () => {
|
||||
setEnabled(false);
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes);
|
||||
const session = [...harness.ctx.sessions.values()][0];
|
||||
expect((await harness.app.inject(requests(session.id)[0])).statusCode).toBe(403);
|
||||
setEnabled(true);
|
||||
const [inspect, invalid, stage, submit] = await Promise.all(
|
||||
requests(session.id).map((request) => harness.app.inject(request))
|
||||
);
|
||||
expect(inspect.statusCode).toBe(200);
|
||||
expect(inspect.json().data.source).toBe('pane-snapshot');
|
||||
expect(invalid.statusCode).toBe(400);
|
||||
// The mock session has no characterized composer, so the guards refuse: the route answered.
|
||||
expect(stage.statusCode).toBe(409);
|
||||
expect(submit.statusCode).toBe(409);
|
||||
});
|
||||
});
|
||||
|
||||
it('reports a non-cursor inspection failure as OPERATION_FAILED and logs only the session and error code', async () => {
|
||||
const { mkdtemp, mkdir, writeFile, rm } = await import('node:fs/promises');
|
||||
const { tmpdir } = await import('node:os');
|
||||
const { join } = await import('node:path');
|
||||
const { Session } = await import('../../src/session.js');
|
||||
const root = await mkdtemp(join(tmpdir(), 'agent-inspect-fail-'));
|
||||
const home = join(root, 'codex');
|
||||
await mkdir(join(home, 'sessions'), { recursive: true });
|
||||
const session = new Session({
|
||||
id: 'inspect-fail',
|
||||
workingDir: root,
|
||||
mode: 'codex',
|
||||
envOverrides: { CODEX_HOME: home },
|
||||
});
|
||||
const id = '11111111-1111-4111-8111-111111111111';
|
||||
const path = join(home, 'sessions', `rollout-${id}.jsonl`);
|
||||
await writeFile(
|
||||
path,
|
||||
JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, originator: `codeman_${session.id}` } }) + '\n'
|
||||
);
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes);
|
||||
(harness.ctx.sessions as unknown as Map<string, Session>).set(session.id, session);
|
||||
const read = vi
|
||||
.spyOn(InspectionReader.prototype, 'read')
|
||||
.mockRejectedValue(Object.assign(new Error(`EACCES: permission denied, open '${path}'`), { code: 'EACCES' }));
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
try {
|
||||
const result = await harness.app.inject({ url: `/api/sessions/${session.id}/inspect` });
|
||||
expect(read).toHaveBeenCalled();
|
||||
expect(result.statusCode).toBe(422);
|
||||
expect(result.json().errorCode).toBe('OPERATION_FAILED');
|
||||
expect(result.body).not.toContain(path);
|
||||
const logged = warn.mock.calls.map((call) => call.join(' ')).join('\n');
|
||||
expect(logged).toContain(session.id);
|
||||
expect(logged).toContain('EACCES');
|
||||
expect(logged).not.toContain(home);
|
||||
} finally {
|
||||
read.mockRestore();
|
||||
warn.mockRestore();
|
||||
await session.stop(false);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
describe('agent session routes', () => {
|
||||
it('returns an explicitly bounded pane snapshot when no attributed transcript exists', async () => {
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes);
|
||||
const session = [...harness.ctx.sessions.values()][0];
|
||||
const result = await harness.app.inject({ url: `/api/sessions/${session.id}/inspect?maxBytes=20` });
|
||||
expect(result.statusCode).toBe(200);
|
||||
const body = result.json();
|
||||
expect(body.data.source).toBe('pane-snapshot');
|
||||
expect(body.data.cursor).toBeNull();
|
||||
expect(Buffer.byteLength(body.data.evidence)).toBeLessThanOrEqual(20);
|
||||
});
|
||||
it('refuses guarded staging for an uncharacterized composer', async () => {
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes);
|
||||
const session = [...harness.ctx.sessions.values()][0];
|
||||
const result = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${session.id}/stage`,
|
||||
payload: { message: 'hello' },
|
||||
});
|
||||
expect(result.statusCode).toBe(409);
|
||||
});
|
||||
});
|
||||
|
||||
it('checks ownership before inspection, stage and submit', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
try {
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes, {
|
||||
authUser: { username: 'alice', role: 'user' },
|
||||
});
|
||||
const session = [...harness.ctx.sessions.values()][0];
|
||||
session.owner = 'bob';
|
||||
for (const request of [
|
||||
{ method: 'GET' as const, url: `/api/sessions/${session.id}/inspect` },
|
||||
{ method: 'POST' as const, url: `/api/sessions/${session.id}/stage`, payload: { message: 'hello' } },
|
||||
{
|
||||
method: 'POST' as const,
|
||||
url: `/api/sessions/${session.id}/submit`,
|
||||
payload: { stageId: '11111111-1111-4111-8111-111111111111', confirmSha: 'a'.repeat(64) },
|
||||
},
|
||||
])
|
||||
expect((await harness.app.inject(request)).statusCode).toBe(404);
|
||||
expect(session.writeBuffer).toEqual([]);
|
||||
} finally {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
}
|
||||
});
|
||||
it('validates output budgets and refuses to resume a pane fallback', async () => {
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes);
|
||||
const session = [...harness.ctx.sessions.values()][0];
|
||||
session.terminalBuffer = '😀é'.repeat(20);
|
||||
for (const value of ['0', '-1', '65537', '1.5', 'NaN'])
|
||||
expect(
|
||||
(await harness.app.inject({ url: `/api/sessions/${session.id}/inspect?maxBytes=${value}` })).statusCode
|
||||
).toBe(400);
|
||||
const result = (await harness.app.inject({ url: `/api/sessions/${session.id}/inspect?maxBytes=7` })).json();
|
||||
expect(result.data.evidence).not.toContain('�');
|
||||
expect(Buffer.byteLength(result.data.evidence)).toBeLessThanOrEqual(7);
|
||||
expect(result.data.truncated).toBe(true);
|
||||
expect(
|
||||
(
|
||||
await harness.app.inject({
|
||||
url: `/api/sessions/${session.id}/inspect?since=11111111-1111-4111-8111-111111111111`,
|
||||
})
|
||||
).statusCode
|
||||
).toBe(409);
|
||||
});
|
||||
it('uses real session writes to stage without Enter and refuses intervening API input', async () => {
|
||||
const { Session } = await import('../../src/session.js');
|
||||
const { formatPaneSnapshot } = await import('../../src/tmux-manager.js');
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes);
|
||||
let composer = '';
|
||||
const writes: string[] = [];
|
||||
const session = new Session({
|
||||
id: 'guarded-session',
|
||||
workingDir: '/tmp',
|
||||
mode: 'codex',
|
||||
mux: {
|
||||
isAvailable: () => true,
|
||||
capturePaneBuffer: (
|
||||
_name: string,
|
||||
_pane?: string,
|
||||
opts?: { capturedGeometry?: { cols: number; rows: number } }
|
||||
) => {
|
||||
if (opts) opts.capturedGeometry = { cols: 100, rows: 20 };
|
||||
return formatPaneSnapshot([`› ${composer}`, ' GPT-6-Luna default · ~/case'], {
|
||||
cols: 100,
|
||||
rows: 20,
|
||||
cursorX: 2 + composer.length,
|
||||
cursorY: 0,
|
||||
});
|
||||
},
|
||||
sendInput: async (_id: string, text: string, options?: { beforeDispatch?: () => boolean }) => {
|
||||
if (options?.beforeDispatch && !options.beforeDispatch()) return false;
|
||||
writes.push(text);
|
||||
composer += text;
|
||||
return true;
|
||||
},
|
||||
},
|
||||
muxSession: { muxName: 'codeman-test', sessionId: 'guarded-session', createdAt: 1, pid: 1 },
|
||||
} as unknown as ConstructorParameters<typeof Session>[0]);
|
||||
(harness.ctx.sessions as unknown as Map<string, Session>).set(session.id, session);
|
||||
try {
|
||||
const stage = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${session.id}/stage`,
|
||||
payload: { message: 'hello' },
|
||||
});
|
||||
expect(stage.statusCode).toBe(200);
|
||||
expect(writes).toEqual(['hello']);
|
||||
const { stageId, sha256 } = stage.json().data;
|
||||
const submit = () =>
|
||||
harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${session.id}/submit`,
|
||||
payload: { stageId, confirmSha: sha256 },
|
||||
});
|
||||
expect((await submit()).statusCode).toBe(200);
|
||||
expect(writes).toEqual(['hello', '\r']);
|
||||
expect((await submit()).statusCode).toBe(409);
|
||||
composer = '';
|
||||
const next = (
|
||||
await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${session.id}/stage`,
|
||||
payload: { message: 'again' },
|
||||
})
|
||||
).json().data;
|
||||
await session.writeViaMux('x');
|
||||
composer = 'again'; // Even restoring the visible text cannot erase the input revision.
|
||||
const stale = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${session.id}/submit`,
|
||||
payload: { stageId: next.stageId, confirmSha: next.sha256 },
|
||||
});
|
||||
expect(stale.statusCode).toBe(409);
|
||||
expect(writes.filter((s) => s === '\r')).toHaveLength(1);
|
||||
// Codex's command popup opens on `/`; Enter would run the highlighted command.
|
||||
composer = '';
|
||||
writes.length = 0;
|
||||
const slash = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${session.id}/stage`,
|
||||
payload: { message: '/stat' },
|
||||
});
|
||||
expect(slash.statusCode).toBe(409);
|
||||
expect(slash.json().error).toMatch(/starting with "\/".*codeman agent send/);
|
||||
expect(writes).toEqual([]);
|
||||
} finally {
|
||||
await session.stop(false);
|
||||
}
|
||||
});
|
||||
it('reads only a strictly attributed Codex rollout and binds HTTP cursors to its owner', async () => {
|
||||
const { mkdtemp, mkdir, writeFile, rm } = await import('node:fs/promises');
|
||||
const { tmpdir } = await import('node:os');
|
||||
const { join } = await import('node:path');
|
||||
const { Session } = await import('../../src/session.js');
|
||||
const root = await mkdtemp(join(tmpdir(), 'agent-inspect-route-'));
|
||||
const home = join(root, 'codex');
|
||||
await mkdir(join(home, 'sessions'), { recursive: true });
|
||||
const session = new Session({
|
||||
id: 'inspect-session',
|
||||
workingDir: root,
|
||||
mode: 'codex',
|
||||
envOverrides: { CODEX_HOME: home },
|
||||
});
|
||||
const id = '11111111-1111-4111-8111-111111111111';
|
||||
const row =
|
||||
JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, originator: `codeman_${session.id}` } }) + '\n';
|
||||
await writeFile(join(home, 'sessions', `rollout-${id}.jsonl`), row + '{"text":"hello"}\n');
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes, {
|
||||
authUser: { username: 'alice', role: 'admin' },
|
||||
});
|
||||
(harness.ctx.sessions as unknown as Map<string, Session>).set(session.id, session);
|
||||
try {
|
||||
const first = await harness.app.inject({
|
||||
url: `/api/sessions/${session.id}/inspect?maxBytes=${Buffer.byteLength(row)}`,
|
||||
});
|
||||
expect(first.statusCode).toBe(200);
|
||||
const data = first.json().data;
|
||||
expect(data.source).toBe('codex-jsonl');
|
||||
expect(data.evidence).toBe('{\"text\":\"hello\"}\n');
|
||||
expect(data.omittedBeforeBytes).toBe(Buffer.byteLength(row));
|
||||
expect(data.identity).toEqual({ sessionId: session.id, mode: 'codex', conversationId: id });
|
||||
expect(data.cursor).not.toContain(home);
|
||||
const next = await harness.app.inject({ url: `/api/sessions/${session.id}/inspect?since=${data.cursor}` });
|
||||
expect(next.json().data.evidence).toBe('');
|
||||
const access = session as unknown as { ptyProcess: { resize(cols: number, rows: number): void } | null };
|
||||
access.ptyProcess = { resize: () => {} };
|
||||
session.resize(80, 24);
|
||||
access.ptyProcess = null;
|
||||
expect(
|
||||
(await harness.app.inject({ url: `/api/sessions/${session.id}/inspect?since=${data.cursor}` })).statusCode
|
||||
).toBe(200);
|
||||
session.owner = 'changed-owner';
|
||||
expect(
|
||||
(await harness.app.inject({ url: `/api/sessions/${session.id}/inspect?since=${data.cursor}` })).statusCode
|
||||
).toBe(409);
|
||||
} finally {
|
||||
await session.stop(false);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a stale launch-resume cursor once a new managed rollout conflicts with it', async () => {
|
||||
const { mkdtemp, mkdir, writeFile, rm } = await import('node:fs/promises');
|
||||
const { tmpdir } = await import('node:os');
|
||||
const { join } = await import('node:path');
|
||||
const { Session } = await import('../../src/session.js');
|
||||
const root = await mkdtemp(join(tmpdir(), 'agent-resume-conflict-'));
|
||||
const home = join(root, 'codex');
|
||||
const old = '11111111-1111-4111-8111-111111111111',
|
||||
fresh = '22222222-2222-4222-8222-222222222222';
|
||||
await mkdir(join(home, 'sessions'), { recursive: true });
|
||||
const session = new Session({
|
||||
id: 'resumed-session',
|
||||
workingDir: root,
|
||||
mode: 'codex',
|
||||
envOverrides: { CODEX_HOME: home },
|
||||
codexConfig: { resumeSessionId: old },
|
||||
});
|
||||
const row = (id: string, originator: string) =>
|
||||
JSON.stringify({ type: 'session_meta', payload: { id, cwd: root, originator } }) + '\n';
|
||||
await writeFile(join(home, 'sessions', `rollout-${old}.jsonl`), row(old, 'original-launch'));
|
||||
harness = await createRouteTestHarness(registerAgentSessionRoutes);
|
||||
(harness.ctx.sessions as unknown as Map<string, Session>).set(session.id, session);
|
||||
try {
|
||||
const initial = (await harness.app.inject({ url: `/api/sessions/${session.id}/inspect` })).json().data;
|
||||
expect(initial.source).toBe('codex-jsonl');
|
||||
await writeFile(join(home, 'sessions', `rollout-${fresh}.jsonl`), row(fresh, `codeman_${session.id}`));
|
||||
const stale = await harness.app.inject({ url: `/api/sessions/${session.id}/inspect?since=${initial.cursor}` });
|
||||
expect(stale.statusCode).toBe(409);
|
||||
const fallback = (await harness.app.inject({ url: `/api/sessions/${session.id}/inspect` })).json().data;
|
||||
expect(fallback.source).toBe('pane-snapshot');
|
||||
expect(fallback.cursor).toBeNull();
|
||||
} finally {
|
||||
await session.stop(false);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -7,12 +7,13 @@
|
||||
* The routes read the process-wide `approvalInbox` singleton, so every test
|
||||
* drains it in afterEach; a leaked pending item would bleed into the next test.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { registerApprovalRoutes } from '../../src/web/routes/approval-routes.js';
|
||||
import { registerHookEventRoutes } from '../../src/web/routes/hook-event-routes.js';
|
||||
import { approvalInbox } from '../../src/web/approval-inbox.js';
|
||||
import { sessionWaits } from '../../src/web/session-wait-registry.js';
|
||||
import { raiseScreenBlocked } from '../../src/web/screen-blocked.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { httpStatusForErrorCode, type ApiErrorCode } from '../../src/types.js';
|
||||
@@ -285,6 +286,10 @@ describe('approval routes', () => {
|
||||
});
|
||||
|
||||
describe('staleness sweep on GET /api/approvals', () => {
|
||||
/** Past the delay `notePrompt` waits before it judges a new dialog. */
|
||||
const pastTheDelay = () => vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 3_100);
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('resolves an item whose dialog left the pane, and tells the other clients', async () => {
|
||||
const resolved: Array<Record<string, unknown>> = [];
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'Bash' });
|
||||
@@ -294,11 +299,24 @@ describe('approval routes', () => {
|
||||
// the pane knows. The dialog is gone from the frame the next capture sees.
|
||||
approvalInbox.onResolved = (info) => resolved.push({ ...info });
|
||||
session.terminalBuffer = 'claude> back at the composer';
|
||||
pastTheDelay();
|
||||
|
||||
expect(await listApprovals(harness)).toHaveLength(0);
|
||||
expect(resolved).toEqual([expect.objectContaining({ resolution: 'resolved_in_terminal' })]);
|
||||
});
|
||||
|
||||
it('leaves a dialog too new to judge, however often it is listed', async () => {
|
||||
// The hook beat Ink's paint: the frame still shows the turn, which alone
|
||||
// would count as proof that no dialog is up.
|
||||
session.terminalBuffer = '✻ Actualizing… (13s · esc to interrupt)';
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'Bash' });
|
||||
expect(await listApprovals(harness)).toHaveLength(1);
|
||||
expect(await listApprovals(harness)).toHaveLength(1);
|
||||
|
||||
pastTheDelay();
|
||||
expect(await listApprovals(harness)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('keeps an item whose dialog is still on screen', async () => {
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'Bash' });
|
||||
// Pane unchanged (PERMISSION_DIALOG): the human has not answered yet.
|
||||
@@ -505,6 +523,113 @@ describe('approval routes: supervised-hook (DeepSeek) alert-only items', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('approval routes: approval-only hook module (omp) alert-only items', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let session: MockSession;
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createEnvelopeHarness();
|
||||
session = harness.ctx.sessions.get(SESSION_ID)!;
|
||||
session.mode = 'omp';
|
||||
// A Claude-shaped frame on purpose: even when the capture parses into options, an
|
||||
// omp item must stay alert-only, because omp's composer takes the keystroke.
|
||||
session.terminalBuffer = PERMISSION_DIALOG;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
for (const item of approvalInbox.listPending()) {
|
||||
approvalInbox.resolveForSession(item.sessionId, 'dismissed');
|
||||
}
|
||||
approvalInbox.onPending = approvalInbox.onUpdated = approvalInbox.onResolved = undefined;
|
||||
await harness.app.close();
|
||||
});
|
||||
|
||||
it('creates an answerInTerminal item and omits approvalId from push', async () => {
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'bash', message: 'restricted folder' });
|
||||
const approvals = await listApprovals(harness);
|
||||
expect(approvals).toHaveLength(1);
|
||||
expect(approvals[0]).toMatchObject({
|
||||
sessionId: SESSION_ID,
|
||||
kind: 'permission',
|
||||
toolName: 'bash',
|
||||
message: 'restricted folder',
|
||||
answerInTerminal: true,
|
||||
});
|
||||
const push = harness.ctx.sendPushNotifications.mock.calls.find((c) => c[0] === 'hook:permission_prompt');
|
||||
expect(push?.[1]).toBeDefined();
|
||||
expect(push?.[1]).not.toHaveProperty('approvalId');
|
||||
});
|
||||
|
||||
it('refuses Approve with a terminal-only error and writes nothing into the pane', async () => {
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'bash' });
|
||||
const [item] = await listApprovals(harness);
|
||||
for (const payload of [{ action: 'approve' }, { action: 'deny' }, { action: 'option', option: 1 }]) {
|
||||
const res = await harness.app.inject({ method: 'POST', url: `/api/approvals/${item.id}/answer`, payload });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/answered in the terminal/i);
|
||||
}
|
||||
expect(session.writeBuffer).toEqual([]);
|
||||
expect(await listApprovals(harness)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('resolves the item on elicitation_complete', async () => {
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'bash' });
|
||||
await postHook(harness, 'elicitation_complete', { tool_name: 'bash', approved: true });
|
||||
expect(await listApprovals(harness)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('wakes a blocked waiter, and never a stop waiter', async () => {
|
||||
const notify = vi.spyOn(sessionWaits, 'notifySignal');
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'bash' });
|
||||
await postHook(harness, 'stop', {});
|
||||
expect(notify.mock.calls).toEqual([[SESSION_ID, 'blocked']]);
|
||||
});
|
||||
|
||||
it('drops events the module never sends (stop, idle_prompt) instead of opening items', async () => {
|
||||
await postHook(harness, 'idle_prompt', {});
|
||||
expect(await listApprovals(harness)).toHaveLength(0);
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'bash' });
|
||||
// A forged stop must not clear a real pending dialog either.
|
||||
await postHook(harness, 'stop', {});
|
||||
expect(await listApprovals(harness)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('keeps the alert while a numbered list above the dialog scrolls out of the frame', async () => {
|
||||
// A stand-in for omp's dialog: it has no numbered rows. An agent's plan above it
|
||||
// does, and Claude's dialog parser took that list for the item's options. Once the
|
||||
// list scrolled out of the frame, the next read took the dialog for answered and
|
||||
// cleared the alert while omp was still waiting.
|
||||
const dialog = [' Allow bash?', ' rm -rf build', ' > Approve', ' Deny', ' Deny and send message'].join('\n');
|
||||
const plan = ['Plan:', ' 1. Remove the build folder', ' 2. Run the build', ' 3. Run the tests', ''].join('\n');
|
||||
session.terminalBuffer = `${plan}\n${dialog}`;
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'bash' });
|
||||
const [item] = await listApprovals(harness);
|
||||
// The frame is kept once, as the card's context, and never read for options.
|
||||
expect(item.options).toBeUndefined();
|
||||
expect(item.context).toContain('Allow bash?');
|
||||
|
||||
const resolved: Array<Record<string, unknown>> = [];
|
||||
approvalInbox.onResolved = (info) => resolved.push({ ...info });
|
||||
session.terminalBuffer = dialog;
|
||||
// Past the delay `notePrompt` waits before it judges a new dialog.
|
||||
vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 3_100);
|
||||
expect(await listApprovals(harness)).toHaveLength(1);
|
||||
expect(await listApprovals(harness)).toHaveLength(1);
|
||||
expect(resolved).toEqual([]);
|
||||
|
||||
// The module's own report is what clears it.
|
||||
await postHook(harness, 'elicitation_complete', { tool_name: 'bash', approved: true });
|
||||
expect(await listApprovals(harness)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('opens nothing for a remote omp session, where no module was installed', async () => {
|
||||
(session as unknown as { remote: unknown }).remote = { host: 'box' };
|
||||
await postHook(harness, 'permission_prompt', { tool_name: 'bash' });
|
||||
expect(await listApprovals(harness)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('approval routes: dialogs read off a hook-less screen (codex) are alert-only', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let session: MockSession;
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
/**
|
||||
* @fileoverview POST /api/cases/clone with a `path`: clone INTO that folder (an empty or not yet existing one,
|
||||
* with no subfolder added) and register it as a linked case. Real filesystem under test/setup.ts's temp
|
||||
* HOME and a REAL `git` cloning a local bare repo (the path policy itself is in test/case-path.test.ts).
|
||||
* Port: N/A (app.inject()).
|
||||
*
|
||||
* Like case-custom-path-routes.test.ts this suite rewrites the linked-cases registry, so it refuses to
|
||||
* start outside the sandboxed HOME (a raw `npx vitest` would reach the real ~/.codeman).
|
||||
*/
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
realpathSync,
|
||||
rmSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { homedir, tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerCaseRoutes } from '../../src/web/routes/case-routes.js';
|
||||
import { dataPath } from '../../src/config/instance.js';
|
||||
import {
|
||||
classifyGitFailure,
|
||||
cloneRepository,
|
||||
getActiveGitOperationCount,
|
||||
getQueuedGitOperationCount,
|
||||
isGitAvailable,
|
||||
} from '../../src/git-clone.js';
|
||||
import { isSandboxedHome, safeRmHomeTree } from '../mocks/index.js';
|
||||
|
||||
const LINKED = () => dataPath('linked-cases.json');
|
||||
const linked = (): Record<string, string> => (existsSync(LINKED()) ? JSON.parse(readFileSync(LINKED(), 'utf8')) : {});
|
||||
const clone = (app: Awaited<ReturnType<typeof createRouteTestHarness>>['app'], payload: Record<string, unknown>) =>
|
||||
app.inject({ method: 'POST', url: '/api/cases/clone', payload });
|
||||
|
||||
describe.skipIf(!isGitAvailable())('POST /api/cases/clone with a custom folder', () => {
|
||||
let root: string;
|
||||
let origin: string;
|
||||
let workDir = '';
|
||||
|
||||
const git = (args: string[], cwd: string) =>
|
||||
execFileSync('git', args, { cwd, encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
|
||||
beforeAll(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'codeman-clone-custom-'));
|
||||
origin = join(root, 'origin.git');
|
||||
mkdirSync(origin);
|
||||
git(['init', '--bare', '--quiet'], origin);
|
||||
const work = join(root, 'work');
|
||||
mkdirSync(work);
|
||||
git(['init', '--quiet'], work);
|
||||
git(['config', 'user.email', 'test@example.com'], work);
|
||||
git(['config', 'user.name', 'Codeman Test'], work);
|
||||
writeFileSync(join(work, 'README.md'), '# fixture\n');
|
||||
git(['add', '.'], work);
|
||||
git(['commit', '--quiet', '-m', 'initial'], work);
|
||||
git(['branch', '-M', 'main'], work);
|
||||
git(['remote', 'add', 'origin', origin], work);
|
||||
git(['push', '--quiet', 'origin', 'main'], work);
|
||||
git(['symbolic-ref', 'HEAD', 'refs/heads/main'], origin);
|
||||
});
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }));
|
||||
|
||||
beforeEach(() => {
|
||||
if (!isSandboxedHome()) {
|
||||
throw new Error('case-clone-custom-folder.test.ts rewrites the linked-cases registry: run it via npm test');
|
||||
}
|
||||
safeRmHomeTree(LINKED());
|
||||
// Resolved, because the server answers with the symlink-resolved folder.
|
||||
workDir = realpathSync(mkdtempSync(join(homedir(), 'clone-custom-')));
|
||||
});
|
||||
afterEach(() => {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
if (workDir) safeRmHomeTree(workDir);
|
||||
workDir = '';
|
||||
if (isSandboxedHome()) safeRmHomeTree(LINKED());
|
||||
});
|
||||
|
||||
it('clones into the chosen folder, scaffolds it and registers it as a linked case', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const target = join(workDir, 'my-clone');
|
||||
const res = await clone(app, { name: 'my-clone', repository: origin, path: target });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data.case).toEqual({ name: 'my-clone', path: target });
|
||||
expect(existsSync(join(target, 'README.md'))).toBe(true);
|
||||
expect(existsSync(join(target, '.git'))).toBe(true);
|
||||
expect(existsSync(join(target, '.claude', 'settings.local.json'))).toBe(true);
|
||||
expect(linked()).toEqual({ 'my-clone': target });
|
||||
expect(ctx.broadcast).toHaveBeenCalledWith('case:created', { name: 'my-clone', path: target });
|
||||
// Nothing lands under the cases directory.
|
||||
expect(existsSync(join(homedir(), 'codeman-cases', 'my-clone'))).toBe(false);
|
||||
});
|
||||
|
||||
it('expands ~ in the folder', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const folder = workDir.slice(homedir().length + 1);
|
||||
const res = await clone(app, { name: 'tilde', repository: origin, path: `~/${folder}/tilde` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(existsSync(join(workDir, 'tilde', 'README.md'))).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses a parent folder that does not exist, and creates nothing', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const res = await clone(app, { name: 'orphan', repository: origin, path: join(workDir, 'nope', 'orphan') });
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(existsSync(join(workDir, 'nope'))).toBe(false);
|
||||
expect(linked()).toEqual({});
|
||||
});
|
||||
|
||||
it('refuses a target folder that already has files, and leaves them alone', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const target = join(workDir, 'busy');
|
||||
mkdirSync(target);
|
||||
writeFileSync(join(target, 'mine.txt'), 'keep me');
|
||||
const res = await clone(app, { name: 'busy', repository: origin, path: target });
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json().error).toMatch(/already has files/);
|
||||
expect(readFileSync(join(target, 'mine.txt'), 'utf8')).toBe('keep me');
|
||||
expect(linked()).toEqual({});
|
||||
});
|
||||
|
||||
it('clones straight INTO the chosen empty folder, with no subfolder named after the case', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const target = join(workDir, 'picked');
|
||||
mkdirSync(target);
|
||||
const res = await clone(app, { name: 'a-different-name', repository: origin, path: target });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data.case).toEqual({ name: 'a-different-name', path: target });
|
||||
expect(existsSync(join(target, 'README.md'))).toBe(true);
|
||||
expect(existsSync(join(target, '.git'))).toBe(true);
|
||||
expect(existsSync(join(target, 'a-different-name'))).toBe(false);
|
||||
expect(linked()).toEqual({ 'a-different-name': target });
|
||||
});
|
||||
|
||||
it('leaves the empty folder in place, and empty, when the clone fails', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const target = join(workDir, 'stays');
|
||||
mkdirSync(target);
|
||||
const res = await clone(app, { name: 'stays', repository: join(root, 'no-such-repo.git'), path: target });
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(existsSync(target)).toBe(true);
|
||||
expect(readdirSync(target)).toEqual([]);
|
||||
expect(linked()).toEqual({});
|
||||
});
|
||||
|
||||
it('two clones into one empty folder at once: exactly one wins and its files survive', async () => {
|
||||
const target = join(workDir, 'raced');
|
||||
mkdirSync(target);
|
||||
const results = await Promise.all([
|
||||
cloneRepository({ repository: origin, destination: target, intoEmptyDir: true }),
|
||||
cloneRepository({ repository: origin, destination: target, intoEmptyDir: true }),
|
||||
]);
|
||||
expect(results.filter((r) => r.ok)).toHaveLength(1);
|
||||
const loser = results.find((r) => !r.ok);
|
||||
expect(loser && !loser.ok && loser.failure.code).toBe('DESTINATION_EXISTS');
|
||||
expect(existsSync(join(target, 'README.md'))).toBe(true);
|
||||
expect(existsSync(join(target, '.git'))).toBe(true);
|
||||
});
|
||||
|
||||
it('a name linked while the clone ran is a 409 that keeps the folder and names it', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const [a, b] = await Promise.all([
|
||||
clone(app, { name: 'twin', repository: origin, path: join(workDir, 'twin-a') }),
|
||||
clone(app, { name: 'twin', repository: origin, path: join(workDir, 'twin-b') }),
|
||||
]);
|
||||
const loserDir = a.json().success ? join(workDir, 'twin-b') : join(workDir, 'twin-a');
|
||||
const loser = a.json().success ? b : a;
|
||||
expect([a.json().success, b.json().success].filter(Boolean)).toHaveLength(1);
|
||||
expect(loser.statusCode).toBe(409);
|
||||
expect(loser.json().errorCode).toBe('ALREADY_EXISTS');
|
||||
expect(loser.json().error).toContain(loserDir);
|
||||
expect(existsSync(join(loserDir, 'README.md'))).toBe(true);
|
||||
expect(Object.keys(linked())).toEqual(['twin']);
|
||||
});
|
||||
|
||||
it('a registry that is not a JSON object is a 409 that keeps the folder, names it and leaves the file alone', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const target = join(workDir, 'refused');
|
||||
mkdirSync(dirname(LINKED()), { recursive: true });
|
||||
writeFileSync(LINKED(), '[]');
|
||||
const res = await clone(app, { name: 'refused', repository: origin, path: target });
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json().errorCode).toBe('CONFLICT');
|
||||
expect(res.json().error).toContain(target);
|
||||
expect(res.json().error).toContain('Use Link Existing');
|
||||
expect(existsSync(join(target, 'README.md'))).toBe(true);
|
||||
expect(readFileSync(LINKED(), 'utf8')).toBe('[]');
|
||||
});
|
||||
|
||||
it('a direct clone whose git-slot wait times out leaves what was written into the folder meanwhile', async () => {
|
||||
const target = join(workDir, 'queued');
|
||||
mkdirSync(target);
|
||||
// Two slow ssh clones hold both git slots (no network needed: the ssh command just sleeps).
|
||||
const prior = process.env.GIT_SSH_COMMAND;
|
||||
process.env.GIT_SSH_COMMAND = 'sleep 4; true';
|
||||
try {
|
||||
const holders = [0, 1].map((i) =>
|
||||
cloneRepository({
|
||||
repository: 'ssh://localhost/x.git',
|
||||
destination: join(workDir, `hold-${i}`),
|
||||
timeoutMs: 10_000,
|
||||
})
|
||||
);
|
||||
await vi.waitFor(() => expect(getActiveGitOperationCount()).toBe(2));
|
||||
const queued = cloneRepository({
|
||||
repository: origin,
|
||||
destination: target,
|
||||
intoEmptyDir: true,
|
||||
timeoutMs: 1_000,
|
||||
});
|
||||
await vi.waitFor(() => expect(getQueuedGitOperationCount()).toBe(1));
|
||||
// Written during the wait, so not this attempt's: a user copying files in, or another case created there.
|
||||
writeFileSync(join(target, 'mine.txt'), 'keep me');
|
||||
mkdirSync(join(target, 'src'));
|
||||
const result = await queued;
|
||||
expect(!result.ok && result.failure.code).toBe('TIMEOUT');
|
||||
expect(readFileSync(join(target, 'mine.txt'), 'utf8')).toBe('keep me');
|
||||
expect(existsSync(join(target, 'src'))).toBe(true);
|
||||
await Promise.all(holders);
|
||||
} finally {
|
||||
if (prior === undefined) delete process.env.GIT_SSH_COMMAND;
|
||||
else process.env.GIT_SSH_COMMAND = prior;
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
it('refuses a folder at or inside a Docker case workspace, and creates nothing', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const workspace = join(workDir, 'dockerws');
|
||||
mkdirSync(workspace);
|
||||
writeFileSync(
|
||||
join(dataPath('docker-cases.json')),
|
||||
JSON.stringify([{ name: 'box', type: 'docker', hostId: 'h', hostWorkspacePath: workspace, container: 'c' }])
|
||||
);
|
||||
try {
|
||||
for (const path of [workspace, join(workspace, 'repo')]) {
|
||||
const res = await clone(app, { name: 'inside', repository: origin, path });
|
||||
expect(res.json().errorCode, path).toBe('INVALID_INPUT');
|
||||
expect(res.json().error, path).toMatch(/Docker case workspace/);
|
||||
}
|
||||
expect(readdirSync(workspace)).toEqual([]);
|
||||
expect(linked()).toEqual({});
|
||||
// A sibling of the workspace is fine.
|
||||
const ok = await clone(app, { name: 'beside', repository: origin, path: join(workDir, 'beside') });
|
||||
expect(ok.statusCode).toBe(200);
|
||||
} finally {
|
||||
safeRmHomeTree(dataPath('docker-cases.json'));
|
||||
}
|
||||
});
|
||||
|
||||
it('fails closed when the Docker case list cannot be read', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
writeFileSync(dataPath('docker-cases.json'), '{not json');
|
||||
try {
|
||||
const res = await clone(app, { name: 'blind', repository: origin, path: join(workDir, 'blind') });
|
||||
expect(res.statusCode).toBe(503);
|
||||
expect(existsSync(join(workDir, 'blind'))).toBe(false);
|
||||
} finally {
|
||||
safeRmHomeTree(dataPath('docker-cases.json'));
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['plain', 'openssl', 'rustls', 'does not exist'])(
|
||||
'a refused folder named %s keeps what was written meanwhile and reports DESTINATION_EXISTS',
|
||||
async (folder) => {
|
||||
const target = join(workDir, folder);
|
||||
mkdirSync(target);
|
||||
const prior = process.env.GIT_SSH_COMMAND;
|
||||
process.env.GIT_SSH_COMMAND = 'sleep 2; true';
|
||||
try {
|
||||
const holders = [0, 1].map((i) =>
|
||||
cloneRepository({
|
||||
repository: 'ssh://localhost/x.git',
|
||||
destination: join(workDir, `hold-${i}`),
|
||||
timeoutMs: 10_000,
|
||||
})
|
||||
);
|
||||
await vi.waitFor(() => expect(getActiveGitOperationCount()).toBe(2));
|
||||
// Queues behind the holders but has time to get a slot, so git runs and refuses the folder.
|
||||
const queued = cloneRepository({
|
||||
repository: origin,
|
||||
destination: target,
|
||||
intoEmptyDir: true,
|
||||
timeoutMs: 15_000,
|
||||
});
|
||||
await vi.waitFor(() => expect(getQueuedGitOperationCount()).toBe(1));
|
||||
writeFileSync(join(target, 'mine.txt'), 'keep me');
|
||||
const result = await queued;
|
||||
expect(!result.ok && result.failure.code).toBe('DESTINATION_EXISTS');
|
||||
expect(readFileSync(join(target, 'mine.txt'), 'utf8')).toBe('keep me');
|
||||
await Promise.all(holders);
|
||||
} finally {
|
||||
if (prior === undefined) delete process.env.GIT_SSH_COMMAND;
|
||||
else process.env.GIT_SSH_COMMAND = prior;
|
||||
}
|
||||
},
|
||||
30_000
|
||||
);
|
||||
|
||||
it('classifies git stderr by what it says, not by words in a path it quotes', () => {
|
||||
const refusal = (dir: string) => `fatal: destination path '${dir}' already exists and is not an empty directory.`;
|
||||
for (const dir of ['/home/u/src/openssl', '/home/u/rustls', '/x/tls-test', '/x/repository not found']) {
|
||||
expect(classifyGitFailure(refusal(dir), false).code, dir).toBe('DESTINATION_EXISTS');
|
||||
}
|
||||
expect(classifyGitFailure('fatal: unable to access: SSL certificate problem: self signed', false).code).toBe(
|
||||
'HOST_UNREACHABLE'
|
||||
);
|
||||
expect(classifyGitFailure('fatal: TLS handshake failure', false).code).toBe('HOST_UNREACHABLE');
|
||||
// `_` is a word character, so a bare \bssl\b misses OpenSSL's and LibreSSL's usual flaky-network error.
|
||||
expect(
|
||||
classifyGitFailure(
|
||||
"fatal: unable to access 'https://github.com/o/r/': OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443",
|
||||
false
|
||||
).code
|
||||
).toBe('HOST_UNREACHABLE');
|
||||
expect(classifyGitFailure('fatal: could not resolve host: example.invalid', false).code).toBe('HOST_UNREACHABLE');
|
||||
expect(classifyGitFailure("fatal: repository 'https://x/y.git/' not found", false).code).toBe('NOT_FOUND');
|
||||
});
|
||||
|
||||
it('refuses a clone without a path into the cases folder when it is a Docker case workspace', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const casesDir = join(homedir(), 'codeman-cases');
|
||||
mkdirSync(casesDir, { recursive: true });
|
||||
writeFileSync(
|
||||
dataPath('docker-cases.json'),
|
||||
JSON.stringify([{ name: 'box', type: 'docker', hostId: 'h', hostWorkspacePath: casesDir, container: 'c' }])
|
||||
);
|
||||
try {
|
||||
const res = await clone(app, { name: 'default-inside', repository: origin });
|
||||
expect(res.json().errorCode).toBe('INVALID_INPUT');
|
||||
expect(res.json().error).toMatch(/Docker case workspace/);
|
||||
expect(existsSync(join(casesDir, 'default-inside'))).toBe(false);
|
||||
} finally {
|
||||
safeRmHomeTree(dataPath('docker-cases.json'));
|
||||
}
|
||||
});
|
||||
|
||||
it('points Clone Repo at itself, not Create New, for the cases folder and a folder directly in it', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const casesDir = join(homedir(), 'codeman-cases');
|
||||
mkdirSync(casesDir, { recursive: true });
|
||||
for (const path of [casesDir, join(casesDir, 'direct-child')]) {
|
||||
const res = await clone(app, { name: 'direct-child', repository: origin, path });
|
||||
expect(res.statusCode, path).toBe(400);
|
||||
expect(res.json().error, path).toMatch(/clone there without a custom folder/);
|
||||
expect(res.json().error, path).not.toMatch(/Create New/);
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a blocked tree such as ~/.ssh', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
mkdirSync(join(homedir(), '.ssh'), { recursive: true });
|
||||
const res = await clone(app, { name: 'sneaky', repository: origin, path: join(homedir(), '.ssh', 'sneaky') });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(existsSync(join(homedir(), '.ssh', 'sneaky'))).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses a name already linked, before running git', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
writeFileSync(LINKED(), JSON.stringify({ taken: join(workDir, 'elsewhere') }));
|
||||
const res = await clone(app, { name: 'taken', repository: origin, path: join(workDir, 'taken') });
|
||||
// The harness has no preSerialization status mapping, so read the envelope's code.
|
||||
expect(res.json().errorCode).toBe('ALREADY_EXISTS');
|
||||
expect(existsSync(join(workDir, 'taken'))).toBe(false);
|
||||
});
|
||||
|
||||
it('leaves no folder behind when the clone fails', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const target = join(workDir, 'ghost');
|
||||
const res = await clone(app, { name: 'ghost', repository: join(root, 'no-such-repo.git'), path: target });
|
||||
expect(res.json().errorCode).toBe('NOT_FOUND');
|
||||
expect(existsSync(target)).toBe(false);
|
||||
expect(linked()).toEqual({});
|
||||
});
|
||||
|
||||
it('without a path the clone still goes under the cases directory and is not linked', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const res = await clone(app, { name: 'custom-folder-default', repository: origin });
|
||||
try {
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data.case.path).toBe(join(homedir(), 'codeman-cases', 'custom-folder-default'));
|
||||
expect(linked()).toEqual({});
|
||||
} finally {
|
||||
safeRmHomeTree(join(homedir(), 'codeman-cases', 'custom-folder-default'));
|
||||
}
|
||||
});
|
||||
|
||||
it('multi-user: a non-admin is refused (403) and nothing is cloned; an admin is allowed', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const user = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
const denied = await clone(user.app, { name: 'bobs', repository: origin, path: join(workDir, 'bobs') });
|
||||
expect(denied.statusCode).toBe(403);
|
||||
expect(existsSync(join(workDir, 'bobs'))).toBe(false);
|
||||
expect(linked()).toEqual({});
|
||||
const admin = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'root', role: 'admin' } });
|
||||
const ok = await clone(admin.app, { name: 'roots', repository: origin, path: join(workDir, 'roots') });
|
||||
expect(ok.statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@
|
||||
* to start there. Each test's folders sit in a fresh mkdtemp dir, and everything is removed through
|
||||
* safeRmHomeTree, so a run can only ever delete what it created.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
@@ -19,17 +19,18 @@ import {
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { basename, join } from 'node:path';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerCaseRoutes } from '../../src/web/routes/case-routes.js';
|
||||
import { dataPath } from '../../src/config/instance.js';
|
||||
import { safeRmHomeTree } from '../mocks/index.js';
|
||||
import { isSandboxedHome, safeRmHomeTree } from '../mocks/index.js';
|
||||
|
||||
const LINKED = () => dataPath('linked-cases.json');
|
||||
const CASES_DIR = () => join(homedir(), 'codeman-cases');
|
||||
/** test/setup.ts's temp HOME (its prefix is pinned by test/test-env-isolation.test.ts). */
|
||||
const sandboxed = () => basename(homedir()).startsWith('codeman-vitest-');
|
||||
const sandboxed = () => isSandboxedHome();
|
||||
let workDir = '';
|
||||
const work = () => workDir;
|
||||
const linked = (): Record<string, string> => (existsSync(LINKED()) ? JSON.parse(readFileSync(LINKED(), 'utf8')) : {});
|
||||
@@ -40,7 +41,7 @@ beforeEach(() => {
|
||||
if (!sandboxed()) {
|
||||
throw new Error('case-custom-path-routes.test.ts deletes the linked-cases registry: run it via npm test');
|
||||
}
|
||||
// Recursive: the rollback tests turn the registry into a directory.
|
||||
// Recursive, so a test that left anything at the registry's path cannot leak into the next one.
|
||||
safeRmHomeTree(LINKED());
|
||||
// Resolved, because the server answers with the symlink-resolved folder (macOS temp is under /private).
|
||||
workDir = realpathSync(mkdtempSync(join(homedir(), 'case-custom-path-')));
|
||||
@@ -134,20 +135,36 @@ describe('POST /api/cases with a custom path', () => {
|
||||
|
||||
it('undoes what it created when registering fails (a new folder is removed entirely)', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
mkdirSync(LINKED(), { recursive: true }); // writeFile onto a directory fails
|
||||
const res = await create(app, { name: 'doomed', path: join(work(), 'doomed') });
|
||||
// The registry is replaced by renaming a temp file over it: fail that rename.
|
||||
const realRename = fs.rename;
|
||||
const spy = vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {
|
||||
if (to === LINKED()) throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
|
||||
return realRename(from, to);
|
||||
});
|
||||
let res;
|
||||
try {
|
||||
res = await create(app, { name: 'doomed', path: join(work(), 'doomed') });
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(existsSync(join(work(), 'doomed'))).toBe(false);
|
||||
expect(linked()).toEqual({});
|
||||
});
|
||||
|
||||
it('undoes only the scaffold inside an empty folder the user picked, leaving the folder', async () => {
|
||||
it('undoes only the scaffold inside an empty folder the user picked when the registry is refused', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
mkdirSync(join(work(), 'picked'));
|
||||
mkdirSync(LINKED(), { recursive: true });
|
||||
// A registry that does not parse is never written over (that would unlink every other case).
|
||||
const torn = '{\n "kept": "/somewhere"\n}tail"\n}';
|
||||
writeFileSync(LINKED(), torn);
|
||||
const res = await create(app, { name: 'picked', path: join(work(), 'picked') });
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json().errorCode).toBe('CONFLICT');
|
||||
expect(res.json().error).toContain('is not a valid JSON object');
|
||||
expect(existsSync(join(work(), 'picked'))).toBe(true);
|
||||
expect(readdirSync(join(work(), 'picked'))).toEqual([]);
|
||||
expect(readFileSync(LINKED(), 'utf8')).toBe(torn);
|
||||
});
|
||||
|
||||
it('a request without a path still creates under the cases directory, as before', async () => {
|
||||
@@ -183,6 +200,21 @@ describe('POST /api/cases with a custom path', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('creates and links a folder two levels under the cases directory (not listed as a local case)', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
mkdirSync(join(CASES_DIR(), 'parent-dir'), { recursive: true });
|
||||
try {
|
||||
const target = join(realpathSync(join(CASES_DIR(), 'parent-dir')), 'nested');
|
||||
const res = await create(app, { name: 'nested', path: target });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data.case).toEqual({ name: 'nested', path: target });
|
||||
expect(linked()).toEqual({ nested: target });
|
||||
expect(existsSync(join(target, 'CLAUDE.md'))).toBe(true);
|
||||
} finally {
|
||||
safeRmHomeTree(join(CASES_DIR(), 'parent-dir'));
|
||||
}
|
||||
});
|
||||
|
||||
it('multi-user: a non-admin is refused (403) and nothing is created; an admin is allowed', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const user = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
|
||||
@@ -0,0 +1,551 @@
|
||||
/**
|
||||
* @fileoverview Per-case default session group over HTTP: the case routes that
|
||||
* read and write it, and the create routes that carry the case into the real
|
||||
* TabLayoutService so a new session lands in its case's group in the creating
|
||||
* write (POST /api/sessions, and POST /api/quick-start for local, remote and
|
||||
* Docker cases). The tab "+" picker (app.js) is driven end to end against the
|
||||
* same routes, since an ungrouped tab relies on this fallback by design.
|
||||
*
|
||||
* Uses app.inject(), so no real HTTP port is needed.
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { mkdir, rm, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { homedir } from 'node:os';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
import { registerCaseRoutes } from '../../src/web/routes/case-routes.js';
|
||||
import { Session } from '../../src/session.js';
|
||||
import { TabLayoutService } from '../../src/tab-layout-service.js';
|
||||
import { ownerLayoutKey } from '../../src/tab-layout-persistence.js';
|
||||
import type { TabLayout } from '../../src/tab-layout.js';
|
||||
import { CASES_DIR } from '../../src/web/route-helpers.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { safeRmHomeTree } from '../mocks/index.js';
|
||||
|
||||
vi.mock('../../src/utils/cli-launcher.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/utils/cli-launcher.js')>();
|
||||
return { ...actual, resolveCliLaunchError: vi.fn().mockResolvedValue(null) };
|
||||
});
|
||||
|
||||
const CASE = 'cdgcase';
|
||||
const DATA_FILES = ['docker-hosts.json', 'docker-cases.json', 'remote-hosts.json', 'remote-cases.json'];
|
||||
|
||||
interface World {
|
||||
layouts: Record<string, TabLayout>;
|
||||
order: string[];
|
||||
defaults: Record<string, Record<string, string | null>>;
|
||||
service: TabLayoutService;
|
||||
}
|
||||
|
||||
/** The real layout service over an in-memory store, wired the way server.ts wires it. */
|
||||
function attachRealLayout(harness: RouteTestHarness): World {
|
||||
const world = { layouts: {}, order: [], defaults: {} } as unknown as World;
|
||||
const caseDefaults = {
|
||||
getCaseDefaultGroup: (owner: string, name: string) =>
|
||||
world.defaults[owner] && name in world.defaults[owner] ? world.defaults[owner][name] : undefined,
|
||||
setCaseDefaultGroup: (owner: string, name: string, id: string | null) => {
|
||||
world.defaults[owner] = { ...(world.defaults[owner] ?? {}), [name]: id };
|
||||
},
|
||||
deleteCaseDefaultGroup: (owner: string, name: string) => {
|
||||
if (world.defaults[owner]) delete world.defaults[owner][name];
|
||||
},
|
||||
};
|
||||
world.service = new TabLayoutService({
|
||||
store: {
|
||||
getTabLayout: (owner: string) => world.layouts[owner] ?? null,
|
||||
getTabLayouts: () => ({ ...world.layouts }),
|
||||
getSessions: () => ({}),
|
||||
getSessionOrder: () => [...world.order],
|
||||
commitTabLayoutProjection: (
|
||||
updates: Readonly<Record<string, TabLayout>>,
|
||||
project: (latest: readonly string[]) => readonly string[]
|
||||
) => {
|
||||
world.order = [...project(world.order)];
|
||||
Object.assign(world.layouts, structuredClone(updates));
|
||||
return { layouts: structuredClone(updates), sessionOrder: [...world.order] };
|
||||
},
|
||||
} as never,
|
||||
sessions: harness.ctx.sessions as never,
|
||||
readWebviews: async () => [],
|
||||
broadcast: () => {},
|
||||
broadcastSessionOrder: () => {},
|
||||
caseDefaults,
|
||||
});
|
||||
world.service.markRestorationSkipped();
|
||||
(harness.ctx as unknown as { tabLayouts: TabLayoutService }).tabLayouts = world.service;
|
||||
harness.ctx.addSession.mockImplementation((session: Session, placement?: object) =>
|
||||
world.service.sessionCreated(ownerLayoutKey(session.owner), session.id, placement, () => {
|
||||
harness.ctx.sessions.set(session.id, session as never);
|
||||
return () => harness.ctx.sessions.delete(session.id);
|
||||
})
|
||||
);
|
||||
return world;
|
||||
}
|
||||
|
||||
const OWNER = ownerLayoutKey(undefined);
|
||||
const withGroups = (world: World) => {
|
||||
world.layouts[OWNER] = {
|
||||
version: 3,
|
||||
updatedAt: '2026-10-21T00:00:00.000Z',
|
||||
groups: [
|
||||
{ id: 'g-core', name: 'Core', refs: [] },
|
||||
{ id: 'g-ops', name: 'Ops', refs: [] },
|
||||
],
|
||||
ungrouped: [],
|
||||
};
|
||||
};
|
||||
const groupOf = (layout: TabLayout, sessionId: string): string | null =>
|
||||
layout.groups.find((g) => g.refs.some((r) => r.id === sessionId))?.id ?? null;
|
||||
const unwrap = (raw: string) => {
|
||||
const parsed = JSON.parse(raw);
|
||||
return parsed.data ?? parsed;
|
||||
};
|
||||
|
||||
/**
|
||||
* The shipping frontend in JSDOM, with fetch answered by the route harnesses, so
|
||||
* a click in the tab "+" picker reaches the real create route and layout service.
|
||||
*/
|
||||
async function bootTabApp(route: (url: string, init?: { method?: string; body?: string }) => Promise<unknown>) {
|
||||
const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', {
|
||||
url: 'https://localhost/',
|
||||
runScripts: 'outside-only',
|
||||
});
|
||||
if (dom.window.document.readyState !== 'complete') {
|
||||
await new Promise((resolve) => dom.window.addEventListener('load', resolve));
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const win = dom.window as any;
|
||||
win.setInterval = () => 0;
|
||||
win.requestAnimationFrame = () => 0;
|
||||
win.__codemanCliCatalog = [{ id: 'shell', kind: 'shell', label: 'Shell', enabled: true }];
|
||||
const publicDir = join(process.cwd(), 'src/web/public');
|
||||
win.eval(
|
||||
'var MobileDetection = { isTouchDevice: () => false, getDeviceType: () => "desktop" }, KeyboardHandler = {}, ' +
|
||||
'SwipeHandler = {}, VoiceInput = {}, DeepgramProvider = {}, NotificationManager = function(){};\n' +
|
||||
['constants.js', 'app.js', 'mobile-overview.js', 'session-ui.js']
|
||||
.map((file) => readFileSync(join(publicDir, file), 'utf8'))
|
||||
.join('\n;\n') +
|
||||
'\n;window.__CdgCodemanApp = CodemanApp;'
|
||||
);
|
||||
win.fetch = async (url: string, init?: { method?: string; body?: string }) => {
|
||||
const body = await route(url, init);
|
||||
return { ok: true, status: 200, json: async () => body };
|
||||
};
|
||||
win.document.body.innerHTML = '<div id="sessionTabs"></div><select id="quickStartCase"></select>';
|
||||
const app = Object.create(win.__CdgCodemanApp.prototype);
|
||||
Object.assign(app, {
|
||||
$: (id: string) => win.document.getElementById(id),
|
||||
sessions: new Map(),
|
||||
activeSessionId: 'tab-1',
|
||||
terminal: { clear: () => {}, writeln: () => {}, focus: () => {}, cols: 80, rows: 24 },
|
||||
_runMinLockMs: 0,
|
||||
_runMode: 'claude',
|
||||
getTerminalDimensions: () => null,
|
||||
selectSession: async () => {},
|
||||
loadQuickStartCases: () => {},
|
||||
showToast: vi.fn(),
|
||||
_applyTabLayout: () => {},
|
||||
_onSessionCreated: () => {},
|
||||
_renderSessionTabsImmediate: () => {},
|
||||
});
|
||||
return { app, win };
|
||||
}
|
||||
|
||||
describe('case default group: create routes', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let world: World;
|
||||
const caseDir = join(CASES_DIR, CASE);
|
||||
const outside = join(homedir(), 'cdg-not-a-case');
|
||||
|
||||
beforeEach(async () => {
|
||||
for (const name of DATA_FILES) await rm(join(getDataDir(), name), { force: true });
|
||||
await mkdir(caseDir, { recursive: true });
|
||||
await mkdir(outside, { recursive: true });
|
||||
vi.spyOn(Session.prototype, 'startInteractive').mockResolvedValue(undefined);
|
||||
vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined);
|
||||
harness = await createRouteTestHarness(registerSessionRoutes);
|
||||
harness.ctx.sessions.clear();
|
||||
world = attachRealLayout(harness);
|
||||
withGroups(world);
|
||||
world.defaults[OWNER] = { [CASE]: 'g-ops' };
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
for (const name of DATA_FILES) await rm(join(getDataDir(), name), { force: true });
|
||||
safeRmHomeTree(CASES_DIR);
|
||||
safeRmHomeTree(outside);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('POST /api/sessions in a case folder lands in the case default group and returns that layout', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions',
|
||||
payload: { name: 'w1-cdg', mode: 'shell', workingDir: caseDir },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(groupOf(world.layouts[OWNER], data.session.id)).toBe('g-ops');
|
||||
// The response carries the committed layout so the browser draws the tab in place.
|
||||
expect(data.tabLayout).toEqual(world.layouts[OWNER]);
|
||||
});
|
||||
|
||||
it('POST /api/sessions in a Claude worktree of the case lands in the case default group too', async () => {
|
||||
// What the Git worktrees modal sends for Claude; every other CLI goes through quick-start with the case name.
|
||||
const worktree = join(caseDir, '.claude', 'worktrees', 'feat');
|
||||
await mkdir(worktree, { recursive: true });
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions',
|
||||
payload: { name: 'w1-cdg-wt', mode: 'shell', workingDir: worktree },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(groupOf(world.layouts[OWNER], data.session.id)).toBe('g-ops');
|
||||
expect(data.tabLayout).toEqual(world.layouts[OWNER]);
|
||||
});
|
||||
|
||||
it('POST /api/sessions without a workingDir infers no case from the server cwd', async () => {
|
||||
vi.spyOn(process, 'cwd').mockReturnValue(caseDir); // the server's own cwd happens to be a case folder
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions',
|
||||
payload: { name: 'w1-nowd', mode: 'shell' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(data.session.workingDir).toBe(caseDir);
|
||||
expect(Object.keys(data)).toEqual(['session']);
|
||||
expect(groupOf(world.layouts[OWNER], data.session.id)).toBeNull();
|
||||
});
|
||||
|
||||
it('POST /api/sessions outside any case gets no case default and keeps its response shape', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions',
|
||||
payload: { name: 'w1-out', mode: 'shell', workingDir: outside },
|
||||
});
|
||||
const data = unwrap(res.body);
|
||||
expect(Object.keys(data)).toEqual(['session']);
|
||||
expect(groupOf(world.layouts[OWNER], data.session.id)).toBeNull();
|
||||
});
|
||||
|
||||
it('POST /api/sessions: an explicit tabGroupId still wins', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions',
|
||||
payload: { name: 'w1-cdg', mode: 'shell', workingDir: caseDir, tabGroupId: 'g-core' },
|
||||
});
|
||||
expect(groupOf(world.layouts[OWNER], unwrap(res.body).session.id)).toBe('g-core');
|
||||
});
|
||||
|
||||
it('POST /api/quick-start for a local case lands in the case default group', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: CASE, mode: 'shell' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(groupOf(world.layouts[OWNER], data.sessionId)).toBe('g-ops');
|
||||
expect(data.tabLayout).toEqual(world.layouts[OWNER]);
|
||||
});
|
||||
|
||||
it('POST /api/quick-start: explicit tabGroupId wins over the case default', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: CASE, mode: 'shell', tabGroupId: 'g-core' },
|
||||
});
|
||||
expect(groupOf(world.layouts[OWNER], unwrap(res.body).sessionId)).toBe('g-core');
|
||||
});
|
||||
|
||||
it('POST /api/quick-start for a remote case lands in the case default group', async () => {
|
||||
await writeFile(
|
||||
join(getDataDir(), 'remote-hosts.json'),
|
||||
JSON.stringify([{ id: 'remote1', label: 'Remote', host: '10.0.0.5', username: 'dev' }])
|
||||
);
|
||||
await writeFile(
|
||||
join(getDataDir(), 'remote-cases.json'),
|
||||
JSON.stringify([{ name: 'cdgremote', type: 'remote', hostId: 'remote1', remotePath: '/home/dev/work' }])
|
||||
);
|
||||
world.defaults[OWNER].cdgremote = 'g-core';
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: 'cdgremote', mode: 'claude' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(data.sessionId, res.body).toBeTruthy();
|
||||
expect(groupOf(world.layouts[OWNER], data.sessionId)).toBe('g-core');
|
||||
});
|
||||
|
||||
it('POST /api/quick-start for a Docker case lands in the case default group', async () => {
|
||||
await writeFile(
|
||||
join(getDataDir(), 'docker-hosts.json'),
|
||||
JSON.stringify([{ id: 'docker1', label: 'Docker', image: 'codeman/agent:base' }])
|
||||
);
|
||||
await writeFile(
|
||||
join(getDataDir(), 'docker-cases.json'),
|
||||
JSON.stringify([
|
||||
{ name: 'cdgdocker', type: 'docker', hostId: 'docker1', hostWorkspacePath: caseDir, container: 'codeman-cdg' },
|
||||
])
|
||||
);
|
||||
world.defaults[OWNER].cdgdocker = 'g-core';
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: 'cdgdocker', mode: 'claude' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(data.sessionId, res.body).toBeTruthy();
|
||||
expect(groupOf(world.layouts[OWNER], data.sessionId)).toBe('g-core');
|
||||
});
|
||||
|
||||
it('a deleted default group never fails creation: the session lands ungrouped and the value is cleared', async () => {
|
||||
world.defaults[OWNER][CASE] = 'g-deleted';
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: CASE, mode: 'shell' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = unwrap(res.body);
|
||||
expect(groupOf(world.layouts[OWNER], data.sessionId)).toBeNull();
|
||||
expect(data.tabLayout).toBeUndefined();
|
||||
expect(CASE in world.defaults[OWNER]).toBe(false);
|
||||
});
|
||||
|
||||
it('a creation that fails after registration leaves no layout reference', async () => {
|
||||
vi.mocked(Session.prototype.startShell).mockRejectedValueOnce(new Error('pane failed'));
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/quick-start',
|
||||
payload: { caseName: CASE, mode: 'shell' },
|
||||
});
|
||||
expect(unwrap(res.body).sessionId).toBeUndefined();
|
||||
// The route's own error path ran cleanupSession for the registered id.
|
||||
expect(harness.ctx.cleanupSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
describe('from a tab "+" in the browser', () => {
|
||||
/** Opens the tab's "+" picker, picks Shell, and returns the create request and the new session's group. */
|
||||
async function launchBeside(tabGroupId: string | null) {
|
||||
const cases = await createRouteTestHarness(registerCaseRoutes);
|
||||
const creates: Array<Record<string, unknown>> = [];
|
||||
try {
|
||||
const { app, win } = await bootTabApp(async (url, init) => {
|
||||
const payload = init?.body ? JSON.parse(init.body) : undefined;
|
||||
if (url === '/api/sessions' && init?.method === 'POST') creates.push(payload);
|
||||
const target = url.startsWith('/api/cases/') ? cases : harness;
|
||||
const res = await target.app.inject({ method: (init?.method ?? 'GET') as 'GET', url, payload });
|
||||
// The envelope server.ts's preSerialization hook adds, which the harness does not install.
|
||||
const body = res.body ? JSON.parse(res.body) : {};
|
||||
return typeof body.success === 'boolean' ? body : { success: true, data: body };
|
||||
});
|
||||
app.cases = [{ name: CASE, path: caseDir }];
|
||||
app.sessions.set('tab-1', { id: 'tab-1', name: 'w1-cdg', workingDir: caseDir });
|
||||
app.tabLayout = {
|
||||
...world.layouts[OWNER],
|
||||
groups: world.layouts[OWNER].groups.map((g) => ({
|
||||
...g,
|
||||
refs: g.id === tabGroupId ? [{ kind: 'session', id: 'tab-1' }] : [],
|
||||
})),
|
||||
};
|
||||
app.collapsedTabGroupIds = new Set();
|
||||
app.toggleTabGroupCollapsed = () => {};
|
||||
const plus = win.document.createElement('span');
|
||||
win.document.body.appendChild(plus);
|
||||
app.openTabNewSessionMenu({ preventDefault() {}, stopPropagation() {}, currentTarget: plus }, 'tab-1');
|
||||
const shell = [...win.document.querySelectorAll('[aria-label="New session here"] button')].find(
|
||||
(button: Element) => button.textContent === 'Terminal / Shell'
|
||||
) as HTMLElement;
|
||||
shell.click();
|
||||
await vi.waitFor(() => expect(creates).toHaveLength(1));
|
||||
await vi.waitFor(() => expect(harness.ctx.sessions.size).toBe(1));
|
||||
const [id] = [...harness.ctx.sessions.keys()];
|
||||
return { create: creates[0], group: groupOf(world.layouts[OWNER], id), toasts: app.showToast.mock.calls };
|
||||
} finally {
|
||||
await cases.app.close();
|
||||
}
|
||||
}
|
||||
|
||||
it('an ungrouped tab sends no group, so the case default group places the session (chosen on purpose)', async () => {
|
||||
const { create, group, toasts } = await launchBeside(null);
|
||||
expect(create).toEqual({ workingDir: caseDir, mode: 'shell', name: `s1-${CASE}` });
|
||||
expect(group).toBe('g-ops');
|
||||
// The launch went through: no error reported along the way.
|
||||
expect(toasts.filter(([, kind]: [string, string]) => kind === 'error')).toEqual([]);
|
||||
});
|
||||
|
||||
it('a grouped tab sends its own group, which wins over the case default', async () => {
|
||||
const { create, group } = await launchBeside('g-core');
|
||||
expect(create).toEqual({ workingDir: caseDir, mode: 'shell', name: `s1-${CASE}`, tabGroupId: 'g-core' });
|
||||
expect(group).toBe('g-core');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('case default group: GET/PUT /api/cases/:name/default-group', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let world: World;
|
||||
const caseDir = join(CASES_DIR, CASE);
|
||||
|
||||
beforeEach(async () => {
|
||||
for (const name of DATA_FILES) await rm(join(getDataDir(), name), { force: true });
|
||||
await mkdir(caseDir, { recursive: true });
|
||||
harness = await createRouteTestHarness(registerCaseRoutes);
|
||||
world = attachRealLayout(harness);
|
||||
withGroups(world);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
for (const name of DATA_FILES) await rm(join(getDataDir(), name), { force: true });
|
||||
safeRmHomeTree(CASES_DIR);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const get = (name = CASE) => harness.app.inject({ method: 'GET', url: `/api/cases/${name}/default-group` });
|
||||
const put = (groupId: unknown, name = CASE) =>
|
||||
harness.app.inject({ method: 'PUT', url: `/api/cases/${name}/default-group`, payload: { groupId } });
|
||||
|
||||
it('lists Ungrouped (null) and every named group of the owner', async () => {
|
||||
const res = await get();
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({
|
||||
success: true,
|
||||
data: {
|
||||
caseName: CASE,
|
||||
groupId: null,
|
||||
groups: [
|
||||
{ id: 'g-core', name: 'Core' },
|
||||
{ id: 'g-ops', name: 'Ops' },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('saves a group and reads it back; null is an intentional Ungrouped', async () => {
|
||||
expect((await put('g-ops')).json().data.groupId).toBe('g-ops');
|
||||
expect(world.defaults[OWNER][CASE]).toBe('g-ops');
|
||||
expect((await get()).json().data.groupId).toBe('g-ops');
|
||||
expect((await put(null)).json().data.groupId).toBeNull();
|
||||
expect(world.defaults[OWNER][CASE]).toBeNull();
|
||||
});
|
||||
|
||||
it('reads the current group names, so a rename shows through (the id is stored)', async () => {
|
||||
await put('g-ops');
|
||||
world.layouts[OWNER].groups[1].name = 'Operations';
|
||||
const data = (await get()).json().data;
|
||||
expect(data.groupId).toBe('g-ops');
|
||||
expect(data.groups[1]).toEqual({ id: 'g-ops', name: 'Operations' });
|
||||
});
|
||||
|
||||
it('a deleted group reads back as Ungrouped, and the read changes nothing', async () => {
|
||||
world.defaults[OWNER] = { [CASE]: 'g-gone' };
|
||||
expect((await get()).json().data.groupId).toBeNull();
|
||||
// GET is read-only; the next session created for the case forgets the stale id.
|
||||
expect(world.defaults[OWNER][CASE]).toBe('g-gone');
|
||||
});
|
||||
|
||||
it.each([
|
||||
['an unknown group', 'g-nope', 400],
|
||||
['an empty string', '', 400],
|
||||
['a number', 7, 400],
|
||||
])('refuses %s without changing the stored value', async (_label, groupId, status) => {
|
||||
await put('g-core');
|
||||
const res = await put(groupId);
|
||||
expect(res.statusCode).toBe(status);
|
||||
expect(res.json().errorCode).toBe('INVALID_INPUT');
|
||||
expect(world.defaults[OWNER][CASE]).toBe('g-core');
|
||||
});
|
||||
|
||||
it('404s a case that does not exist (or is not the caller’s), for both verbs', async () => {
|
||||
expect((await get('nosuchcase')).statusCode).toBe(404);
|
||||
expect((await put('g-core', 'nosuchcase')).statusCode).toBe(404);
|
||||
expect(world.defaults[OWNER]).toBeUndefined();
|
||||
});
|
||||
|
||||
it('accepts a remote case and a Docker case by name', async () => {
|
||||
await writeFile(
|
||||
join(getDataDir(), 'remote-hosts.json'),
|
||||
JSON.stringify([{ id: 'remote1', label: 'Remote', host: '10.0.0.5', username: 'dev' }])
|
||||
);
|
||||
await writeFile(
|
||||
join(getDataDir(), 'remote-cases.json'),
|
||||
JSON.stringify([{ name: 'cdgremote', type: 'remote', hostId: 'remote1', remotePath: '/home/dev/work' }])
|
||||
);
|
||||
await writeFile(
|
||||
join(getDataDir(), 'docker-cases.json'),
|
||||
JSON.stringify([{ name: 'cdgdocker', type: 'docker', hostId: 'docker1', hostWorkspacePath: caseDir }])
|
||||
);
|
||||
expect((await put('g-core', 'cdgremote')).statusCode).toBe(200);
|
||||
expect((await put('g-ops', 'cdgdocker')).statusCode).toBe(200);
|
||||
expect(world.defaults[OWNER]).toMatchObject({ cdgremote: 'g-core', cdgdocker: 'g-ops' });
|
||||
});
|
||||
|
||||
it('DELETE /api/cases/:name forgets the mapping', async () => {
|
||||
await put('g-ops');
|
||||
const res = await harness.app.inject({ method: 'DELETE', url: `/api/cases/${CASE}` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(CASE in world.defaults[OWNER]).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('case default group: multi-user scoping', () => {
|
||||
afterEach(() => {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("stores a non-admin's choice under their own owner key and validates against their own groups", async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const harness = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
try {
|
||||
harness.ctx.sessions.clear();
|
||||
const world = attachRealLayout(harness);
|
||||
world.layouts.alice = {
|
||||
version: 1,
|
||||
updatedAt: '2026-10-21T00:00:00.000Z',
|
||||
groups: [{ id: 'g-alice', name: 'Alice', refs: [] }],
|
||||
ungrouped: [],
|
||||
};
|
||||
world.layouts.bob = {
|
||||
version: 1,
|
||||
updatedAt: '2026-10-21T00:00:00.000Z',
|
||||
groups: [{ id: 'g-bob', name: 'Bob', refs: [] }],
|
||||
ungrouped: [],
|
||||
};
|
||||
const { resolveCasesDir } = await import('../../src/web/route-helpers.js');
|
||||
const bobCases = resolveCasesDir({ username: 'bob', role: 'user' } as never);
|
||||
await mkdir(join(bobCases, 'bobcase'), { recursive: true });
|
||||
|
||||
const read = await harness.app.inject({ method: 'GET', url: '/api/cases/bobcase/default-group' });
|
||||
expect(read.json().data.groups).toEqual([{ id: 'g-bob', name: 'Bob' }]);
|
||||
const foreign = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/cases/bobcase/default-group',
|
||||
payload: { groupId: 'g-alice' },
|
||||
});
|
||||
expect(foreign.statusCode).toBe(400);
|
||||
const own = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/cases/bobcase/default-group',
|
||||
payload: { groupId: 'g-bob' },
|
||||
});
|
||||
expect(own.statusCode).toBe(200);
|
||||
expect(world.defaults).toEqual({ bob: { bobcase: 'g-bob' } });
|
||||
safeRmHomeTree(join(bobCases, '..'));
|
||||
} finally {
|
||||
await harness.app.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,555 @@
|
||||
/**
|
||||
* @fileoverview POST /api/cases/:name/rename: a local case moves with its name, a linked case renames its
|
||||
* alias (and, on request, its real folder), live sessions are listed and only stopped on request, and the
|
||||
* registries (caseOrder, lastUsedCase, linked-cases.json) and Claude's history follow. Real filesystem under
|
||||
* test/setup.ts's temp HOME; every folder is removed through safeRmHomeTree. Port: N/A (app.inject()).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
realpathSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { basename, dirname, join } from 'node:path';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerCaseRoutes } from '../../src/web/routes/case-routes.js';
|
||||
import { dataPath } from '../../src/config/instance.js';
|
||||
import { SETTINGS_PATH, resolveCasesDir } from '../../src/web/route-helpers.js';
|
||||
import { caseSessionSettled, claudeProjectDirName } from '../../src/case-rename.js';
|
||||
import { Session } from '../../src/session.js';
|
||||
import { safeRmHomeTree } from '../mocks/index.js';
|
||||
import { mutateLinkedCases } from '../../src/web/linked-cases-writer.js';
|
||||
import { mutateSettingsFile } from '../../src/web/settings-writer.js';
|
||||
|
||||
const LINKED = () => dataPath('linked-cases.json');
|
||||
const CASES_DIR = () => join(homedir(), 'codeman-cases');
|
||||
const sandboxed = () => basename(homedir()).startsWith('codeman-vitest-');
|
||||
let work = '';
|
||||
let claudeCfg = '';
|
||||
const made: string[] = [];
|
||||
|
||||
const linked = (): Record<string, string> => (existsSync(LINKED()) ? JSON.parse(readFileSync(LINKED(), 'utf8')) : {});
|
||||
/**
|
||||
* The registry is replaced by renaming a temp file over it, which a read-only file does not stop, so a
|
||||
* failed registry write is injected at that rename. `before` runs first (another writer landing then).
|
||||
*/
|
||||
const failRegistryWrite = (before?: () => Promise<unknown>, alsoFail?: (from: string) => boolean) => {
|
||||
const realRename = fs.rename;
|
||||
return vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {
|
||||
if (to === LINKED()) {
|
||||
if (before) await before();
|
||||
throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
|
||||
}
|
||||
if (alsoFail?.(String(from))) throw Object.assign(new Error('resource busy'), { code: 'EBUSY' });
|
||||
return realRename(from, to);
|
||||
});
|
||||
};
|
||||
/**
|
||||
* Runs `during` right after `folder` moved: past every check the route makes before it writes the
|
||||
* registry, and before that write starts. Every other rename goes through untouched.
|
||||
*/
|
||||
const afterFolderMove = (folder: string, during: () => Promise<unknown>) => {
|
||||
const realRename = fs.rename;
|
||||
return vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {
|
||||
await realRename(from, to);
|
||||
if (from === folder) await during();
|
||||
});
|
||||
};
|
||||
const settings = (): Record<string, unknown> => JSON.parse(readFileSync(SETTINGS_PATH, 'utf8'));
|
||||
const rename = (app: Awaited<ReturnType<typeof createRouteTestHarness>>['app'], name: string, payload: object) =>
|
||||
app.inject({ method: 'POST', url: `/api/cases/${name}/rename`, payload });
|
||||
const localCase = (name: string) => {
|
||||
const dir = join(CASES_DIR(), name);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
writeFileSync(join(dir, 'CLAUDE.md'), name);
|
||||
made.push(dir);
|
||||
return dir;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
if (!sandboxed()) throw new Error('case-rename-routes.test.ts renames folders: run it via npm test');
|
||||
safeRmHomeTree(LINKED());
|
||||
work = realpathSync(mkdtempSync(join(homedir(), 'case-rename-')));
|
||||
claudeCfg = join(work, 'claude-config');
|
||||
process.env.CLAUDE_CONFIG_DIR = claudeCfg;
|
||||
mkdirSync(join(homedir(), '.codeman'), { recursive: true });
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ caseOrder: ['keep', 'alpha', 'tail'], lastUsedCase: 'alpha' }));
|
||||
});
|
||||
afterEach(() => {
|
||||
delete process.env.CLAUDE_CONFIG_DIR;
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
for (const dir of made.splice(0)) safeRmHomeTree(dir);
|
||||
if (work) safeRmHomeTree(work);
|
||||
work = '';
|
||||
if (sandboxed()) safeRmHomeTree(LINKED());
|
||||
});
|
||||
|
||||
describe('POST /api/cases/:name/rename (a case under the cases directory)', () => {
|
||||
it('moves the folder, keeps its place in the order, follows lastUsedCase and carries Claude history', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const oldDir = localCase('alpha');
|
||||
mkdirSync(join(claudeCfg, 'projects', claudeProjectDirName(oldDir)), { recursive: true });
|
||||
writeFileSync(join(claudeCfg, 'projects', claudeProjectDirName(oldDir), 'c.jsonl'), '{}');
|
||||
|
||||
const res = await rename(app, 'alpha', { newName: 'beta' });
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const newDir = join(CASES_DIR(), 'beta');
|
||||
made.push(newDir);
|
||||
expect(res.json().data).toMatchObject({ oldName: 'alpha', newName: 'beta', newPath: newDir, folderMoved: true });
|
||||
expect(existsSync(oldDir)).toBe(false);
|
||||
expect(readFileSync(join(newDir, 'CLAUDE.md'), 'utf8')).toBe('alpha');
|
||||
expect(settings()).toMatchObject({ caseOrder: ['keep', 'beta', 'tail'], lastUsedCase: 'beta' });
|
||||
expect(existsSync(join(claudeCfg, 'projects', claudeProjectDirName(newDir), 'c.jsonl'))).toBe(true);
|
||||
});
|
||||
|
||||
it('carries Claude history into the project directory a deleted case of the new name left behind', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const oldDir = localCase('alpha');
|
||||
const newDir = join(CASES_DIR(), 'beta');
|
||||
const oldKey = join(claudeCfg, 'projects', claudeProjectDirName(oldDir));
|
||||
const newKey = join(claudeCfg, 'projects', claudeProjectDirName(newDir));
|
||||
mkdirSync(oldKey, { recursive: true });
|
||||
writeFileSync(join(oldKey, 'conv-alpha.jsonl'), '{}');
|
||||
// case delete never removes Claude Code's history, so an earlier "beta" left its project directory
|
||||
mkdirSync(newKey, { recursive: true });
|
||||
writeFileSync(join(newKey, 'conv-old-beta.jsonl'), '{}');
|
||||
|
||||
const res = await rename(app, 'alpha', { newName: 'beta' });
|
||||
made.push(newDir);
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(existsSync(join(newKey, 'conv-alpha.jsonl'))).toBe(true);
|
||||
expect(existsSync(join(newKey, 'conv-old-beta.jsonl'))).toBe(true);
|
||||
expect(existsSync(oldKey)).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses a dangling symlink at the new folder before it stops any session', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const oldDir = localCase('alpha');
|
||||
const target = join(CASES_DIR(), 'beta');
|
||||
symlinkSync(join(work, 'nowhere'), target);
|
||||
made.push(target);
|
||||
(ctx.sessions as Map<string, unknown>).set('s1', { id: 's1', name: 'w1', workingDir: oldDir });
|
||||
|
||||
const res = await rename(app, 'alpha', { newName: 'beta', stopSessions: true });
|
||||
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json().errorCode).toBe('ALREADY_EXISTS');
|
||||
expect(ctx.cleanupSession).not.toHaveBeenCalled();
|
||||
expect(existsSync(oldDir)).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses a name that is taken (local or linked), the same name, or one that is not allowed', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
localCase('alpha');
|
||||
localCase('taken');
|
||||
const target = join(work, 'elsewhere');
|
||||
mkdirSync(target);
|
||||
writeFileSync(LINKED(), JSON.stringify({ lk: target }));
|
||||
expect((await rename(app, 'alpha', { newName: 'taken' })).statusCode).toBe(409);
|
||||
expect((await rename(app, 'alpha', { newName: 'lk' })).statusCode).toBe(409);
|
||||
expect((await rename(app, 'alpha', { newName: 'alpha' })).statusCode).toBe(400);
|
||||
expect((await rename(app, 'alpha', { newName: '../evil' })).statusCode).toBe(400);
|
||||
expect((await rename(app, 'nope', { newName: 'whatever' })).statusCode).toBe(404);
|
||||
expect(existsSync(join(CASES_DIR(), 'alpha'))).toBe(true);
|
||||
});
|
||||
|
||||
it('lists the live sessions that have the folder open and does not touch it until told to stop them', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const oldDir = localCase('alpha');
|
||||
(ctx.sessions as Map<string, unknown>).set('s-live', {
|
||||
id: 's-live',
|
||||
name: 'w1-alpha',
|
||||
workingDir: join(oldDir, 'sub'),
|
||||
});
|
||||
|
||||
const refused = await rename(app, 'alpha', { newName: 'beta' });
|
||||
expect(refused.statusCode).toBe(409);
|
||||
expect(refused.json()).toMatchObject({ requiresStop: true, sessions: [{ id: 's-live', name: 'w1-alpha' }] });
|
||||
expect(existsSync(oldDir)).toBe(true);
|
||||
expect(ctx.cleanupSession).not.toHaveBeenCalled();
|
||||
|
||||
const done = await rename(app, 'alpha', { newName: 'beta', stopSessions: true });
|
||||
made.push(join(CASES_DIR(), 'beta'));
|
||||
expect(done.statusCode).toBe(200);
|
||||
expect(done.json().data.stoppedSessions).toBe(1);
|
||||
expect(ctx.cleanupSession).toHaveBeenCalledWith('s-live', true, 'case_rename');
|
||||
expect(existsSync(join(CASES_DIR(), 'beta'))).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses to move a folder a session is still being created in, since it can neither list nor stop it', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const oldDir = localCase('alpha');
|
||||
// Constructed but not in ctx.sessions yet: the gap a create spends awaiting the layout lock and settings.
|
||||
const session = new Session({ workingDir: join(oldDir, 'sub') });
|
||||
try {
|
||||
const busy = await rename(app, 'alpha', { newName: 'beta', stopSessions: true });
|
||||
expect(busy.statusCode).toBe(409);
|
||||
expect(busy.json()).toMatchObject({ errorCode: 'CONFLICT', renameCode: 'BUSY' });
|
||||
expect(existsSync(oldDir)).toBe(true);
|
||||
expect(ctx.cleanupSession).not.toHaveBeenCalled();
|
||||
// once registered it is an open session like any other: listed, and stopped only on request
|
||||
(ctx.sessions as Map<string, unknown>).set(session.id, session);
|
||||
caseSessionSettled(session);
|
||||
const listed = await rename(app, 'alpha', { newName: 'beta' });
|
||||
expect(listed.statusCode).toBe(409);
|
||||
expect(listed.json()).toMatchObject({ requiresStop: true, sessions: [{ id: session.id }] });
|
||||
} finally {
|
||||
caseSessionSettled(session);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not stop a remote session whose remote path equals the local folder', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const dir = localCase('alpha');
|
||||
(ctx.sessions as Map<string, unknown>).set('s-remote', { id: 's-remote', name: 'r', workingDir: dir, remote: {} });
|
||||
const res = await rename(app, 'alpha', { newName: 'beta' });
|
||||
made.push(join(CASES_DIR(), 'beta'));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(ctx.cleanupSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("carries the owner's default session group to the new name", async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
localCase('alpha');
|
||||
vi.mocked(ctx.tabLayouts.caseDefaultGroup).mockResolvedValueOnce({ groupId: 'g1', groups: [] });
|
||||
const res = await rename(app, 'alpha', { newName: 'beta' });
|
||||
made.push(join(CASES_DIR(), 'beta'));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(ctx.tabLayouts.setCaseDefaultGroup).toHaveBeenCalledWith(expect.any(String), 'beta', 'g1');
|
||||
expect(ctx.tabLayouts.forgetCaseDefaultGroup).toHaveBeenCalledWith(expect.any(String), 'alpha');
|
||||
});
|
||||
|
||||
it('answers a folder that appears at the target with ALREADY_EXISTS and keeps renameCode', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
localCase('alpha');
|
||||
localCase('beta');
|
||||
const res = await rename(app, 'alpha', { newName: 'beta' });
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json().errorCode).toBe('ALREADY_EXISTS');
|
||||
});
|
||||
|
||||
it('does not touch a case whose name merely starts with the same letters', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
localCase('alpha');
|
||||
const sibling = localCase('alpha2');
|
||||
(ctx.sessions as Map<string, unknown>).set('s-other', { id: 's-other', name: 'x', workingDir: sibling });
|
||||
const res = await rename(app, 'alpha', { newName: 'beta' });
|
||||
made.push(join(CASES_DIR(), 'beta'));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(ctx.cleanupSession).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/cases/:name/rename (a linked case)', () => {
|
||||
it('renames only the alias by default: the real folder and its sessions are left alone', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const real = join(work, 'my-project');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real, other: join(work, 'o') }));
|
||||
(ctx.sessions as Map<string, unknown>).set('s1', { id: 's1', name: 'w1', workingDir: real });
|
||||
|
||||
const res = await rename(app, 'proj', { newName: 'renamed' });
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data).toMatchObject({ folderMoved: false, newPath: real, stoppedSessions: 0 });
|
||||
expect(linked()).toEqual({ other: join(work, 'o'), renamed: real });
|
||||
expect(existsSync(real)).toBe(true);
|
||||
expect(ctx.cleanupSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renames only the alias while a session is being created in the folder, which an alias rename leaves alone', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const real = join(work, 'my-project');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real }));
|
||||
const session = new Session({ workingDir: real });
|
||||
try {
|
||||
expect((await rename(app, 'proj', { newName: 'renamed' })).statusCode).toBe(200);
|
||||
expect((await rename(app, 'renamed', { newName: 'moved', renameFolder: true })).json()).toMatchObject({
|
||||
renameCode: 'BUSY',
|
||||
});
|
||||
expect(existsSync(real)).toBe(true);
|
||||
} finally {
|
||||
caseSessionSettled(session);
|
||||
}
|
||||
});
|
||||
|
||||
it('renames the real folder too, next to the old one, when asked', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const real = join(work, 'my-project');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real }));
|
||||
|
||||
const res = await rename(app, 'proj', { newName: 'renamed', renameFolder: true });
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(existsSync(real)).toBe(false);
|
||||
expect(existsSync(join(work, 'renamed'))).toBe(true);
|
||||
expect(linked()).toEqual({ renamed: join(work, 'renamed') });
|
||||
});
|
||||
|
||||
it('puts the folder and settings.json back when the registry cannot be written', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const real = join(work, 'my-project');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real }));
|
||||
const seeded = {
|
||||
caseOrder: ['a', 'proj', 'b'],
|
||||
lastUsedCase: 'proj',
|
||||
lastPickedCase: 'proj',
|
||||
caseSettings: { proj: { agentTeams: true, opusContext1m: false } },
|
||||
};
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify(seeded));
|
||||
// the registry reads fine but cannot be written: the rename must undo the folder move
|
||||
const spy = failRegistryWrite();
|
||||
let res;
|
||||
try {
|
||||
res = await rename(app, 'proj', { newName: 'renamed', renameFolder: true });
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(existsSync(real)).toBe(true);
|
||||
expect(linked()).toEqual({ proj: real });
|
||||
expect(existsSync(join(work, 'renamed'))).toBe(false);
|
||||
// settings.json is written first, so it must be put back too
|
||||
expect(settings()).toEqual(seeded);
|
||||
});
|
||||
|
||||
it('puts back only the keys it wrote, keeping a settings write made in between', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const real = join(work, 'my-project');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real }));
|
||||
const entry = { agentTeams: true, opusContext1m: false };
|
||||
writeFileSync(
|
||||
SETTINGS_PATH,
|
||||
JSON.stringify({
|
||||
caseOrder: ['a', 'proj', 'b'],
|
||||
lastUsedCase: 'proj',
|
||||
lastPickedCase: 'proj',
|
||||
caseSettings: { proj: entry },
|
||||
})
|
||||
);
|
||||
// Another writer (a settings save, and a per-case save from another device) lands after the rename wrote
|
||||
// settings.json and before the registry write fails.
|
||||
const spy = failRegistryWrite(() =>
|
||||
mutateSettingsFile((current) => ({
|
||||
...current,
|
||||
agentSkillEnabled: true,
|
||||
caseSettings: { ...(current.caseSettings as object), other: { agentTeams: false, opusContext1m: true } },
|
||||
}))
|
||||
);
|
||||
try {
|
||||
const res = await rename(app, 'proj', { newName: 'renamed', renameFolder: true });
|
||||
expect(res.statusCode).toBe(500);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
expect(settings()).toEqual({
|
||||
caseOrder: ['a', 'proj', 'b'],
|
||||
lastUsedCase: 'proj',
|
||||
lastPickedCase: 'proj',
|
||||
caseSettings: { proj: entry, other: { agentTeams: false, opusContext1m: true } },
|
||||
agentSkillEnabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
describe('when the registry changes after the first check', () => {
|
||||
let real = '';
|
||||
type App = Awaited<ReturnType<typeof createRouteTestHarness>>['app'];
|
||||
const renameRacing = async (app: App, during: () => Promise<unknown>) => {
|
||||
const spy = afterFolderMove(real, during);
|
||||
try {
|
||||
return await rename(app, 'proj', { newName: 'renamed', renameFolder: true });
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
};
|
||||
const expectFolderAndSettingsBack = () => {
|
||||
expect(existsSync(real)).toBe(true);
|
||||
expect(existsSync(join(work, 'renamed'))).toBe(false);
|
||||
expect(settings()).toEqual({ caseOrder: ['a', 'proj', 'b'], lastUsedCase: 'proj' });
|
||||
};
|
||||
beforeEach(() => {
|
||||
real = join(work, 'my-project');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real }));
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ caseOrder: ['a', 'proj', 'b'], lastUsedCase: 'proj' }));
|
||||
});
|
||||
|
||||
it('a name linked meanwhile is 409 EXISTS: the link stands and the rename is undone', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const other = join(work, 'other');
|
||||
mkdirSync(other);
|
||||
const res = await renameRacing(app, () =>
|
||||
app.inject({ method: 'POST', url: '/api/cases/link', payload: { name: 'renamed', path: other } })
|
||||
);
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toMatchObject({ errorCode: 'ALREADY_EXISTS', renameCode: 'EXISTS', stoppedSessions: 0 });
|
||||
expect(linked()).toEqual({ proj: real, renamed: other });
|
||||
expectFolderAndSettingsBack();
|
||||
});
|
||||
|
||||
it('an old entry unlinked meanwhile is 409 BUSY: the rename does not bring it back', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const res = await renameRacing(app, () => app.inject({ method: 'DELETE', url: '/api/cases/proj' }));
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toMatchObject({ errorCode: 'CONFLICT', renameCode: 'BUSY', stoppedSessions: 0 });
|
||||
expect(linked()).toEqual({});
|
||||
expectFolderAndSettingsBack();
|
||||
});
|
||||
|
||||
it('an old entry pointed at another folder meanwhile is 409 BUSY: that entry is kept', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const other = join(work, 'other');
|
||||
const res = await renameRacing(app, () => mutateLinkedCases((current) => ({ ...current, proj: other })));
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toMatchObject({ errorCode: 'CONFLICT', renameCode: 'BUSY' });
|
||||
expect(linked()).toEqual({ proj: other });
|
||||
expectFolderAndSettingsBack();
|
||||
});
|
||||
|
||||
it('a registry that stopped parsing is refused 409 CONFLICT and left byte for byte', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const torn = `{ "proj": "${real}" }tail"`;
|
||||
const res = await renameRacing(app, async () => writeFileSync(LINKED(), torn));
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toMatchObject({ errorCode: 'CONFLICT', stoppedSessions: 0 });
|
||||
expect(res.json().error).toContain('is not a valid JSON object');
|
||||
expect(res.json()).not.toHaveProperty('renameCode');
|
||||
expect(readFileSync(LINKED(), 'utf8')).toBe(torn);
|
||||
expectFolderAndSettingsBack();
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses to rename while settings.json is not a JSON object, leaving the folder and the file alone', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const oldDir = localCase('alpha');
|
||||
const torn = '{\n "agentSkillEnabled": true\n}tail"\n}';
|
||||
writeFileSync(SETTINGS_PATH, torn);
|
||||
const res = await rename(app, 'alpha', { newName: 'beta' });
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toEqual({
|
||||
success: false,
|
||||
errorCode: 'CONFLICT',
|
||||
error: `${SETTINGS_PATH} is not a valid JSON object, so this change was not saved (saving would have replaced every other setting in it). Fix or delete the file, or restore it from a config backup, then try again.`,
|
||||
});
|
||||
expect(existsSync(oldDir)).toBe(true);
|
||||
expect(existsSync(join(CASES_DIR(), 'beta'))).toBe(false);
|
||||
expect(readFileSync(SETTINGS_PATH, 'utf8')).toBe(torn);
|
||||
});
|
||||
|
||||
it('checks settings.json before it stops any session, so none is ended for a rename that cannot complete', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const oldDir = localCase('alpha');
|
||||
const torn = '{\n "agentSkillEnabled": true\n}tail"\n}';
|
||||
writeFileSync(SETTINGS_PATH, torn);
|
||||
(ctx.sessions as Map<string, unknown>).set('s1', { id: 's1', name: 'w1', workingDir: oldDir });
|
||||
|
||||
const res = await rename(app, 'alpha', { newName: 'beta', stopSessions: true });
|
||||
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json().errorCode).toBe('CONFLICT');
|
||||
expect(res.json().error).toContain('is not a valid JSON object');
|
||||
expect(ctx.cleanupSession).not.toHaveBeenCalled();
|
||||
expect(existsSync(oldDir)).toBe(true);
|
||||
expect(existsSync(join(CASES_DIR(), 'beta'))).toBe(false);
|
||||
expect(readFileSync(SETTINGS_PATH, 'utf8')).toBe(torn);
|
||||
});
|
||||
|
||||
it('says where the folder is when it cannot be moved back', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const real = join(work, 'my-project');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real }));
|
||||
const moved = join(work, 'renamed');
|
||||
const spy = failRegistryWrite(undefined, (from) => from === moved);
|
||||
try {
|
||||
const res = await rename(app, 'proj', { newName: 'renamed', renameFolder: true });
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.json().error).toContain(`is now at ${moved}`);
|
||||
expect(existsSync(moved)).toBe(true);
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('reports the sessions it stopped when the rename fails after stopping them', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const real = join(work, 'my-project');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real }));
|
||||
(ctx.sessions as Map<string, unknown>).set('s1', { id: 's1', name: 'w1', workingDir: real });
|
||||
const spy = failRegistryWrite();
|
||||
let res;
|
||||
try {
|
||||
res = await rename(app, 'proj', { newName: 'renamed', renameFolder: true, stopSessions: true });
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(res.json().stoppedSessions).toBe(1);
|
||||
expect(ctx.cleanupSession).toHaveBeenCalledWith('s1', true, 'case_rename');
|
||||
expect(existsSync(real)).toBe(true);
|
||||
});
|
||||
|
||||
it('puts the folder and the registry back when settings.json cannot be written', async () => {
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes);
|
||||
const real = join(work, 'my-project');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real, other: join(work, 'x') }));
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ caseOrder: ['proj'] }));
|
||||
// settings.json is replaced by renaming a temp file over it, which a read-only file does not stop,
|
||||
// so the failure is injected at that rename.
|
||||
const realRename = fs.rename;
|
||||
const spy = vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {
|
||||
if (to === SETTINGS_PATH) throw Object.assign(new Error('permission denied'), { code: 'EACCES' });
|
||||
return realRename(from, to);
|
||||
});
|
||||
let res;
|
||||
try {
|
||||
res = await rename(app, 'proj', { newName: 'renamed', renameFolder: true });
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
}
|
||||
expect(res.statusCode).toBe(500);
|
||||
expect(existsSync(real)).toBe(true);
|
||||
expect(linked()).toEqual({ proj: real, other: join(work, 'x') });
|
||||
// The failed write leaves no temp file behind.
|
||||
expect(readdirSync(dirname(SETTINGS_PATH)).filter((n) => n.startsWith('settings.json.'))).toEqual([]);
|
||||
});
|
||||
|
||||
it('answers 404 for a linked case a non-admin cannot see in multi-user mode', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
const real = join(work, 'p');
|
||||
mkdirSync(real);
|
||||
writeFileSync(LINKED(), JSON.stringify({ proj: real }));
|
||||
const res = await rename(app, 'proj', { newName: 'renamed' });
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(linked()).toEqual({ proj: real });
|
||||
});
|
||||
|
||||
it('leaves the server-wide settings.json alone when a non-admin renames their own case', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
const bobsDir = join(resolveCasesDir({ username: 'bob', role: 'user' } as never), 'alpha');
|
||||
mkdirSync(bobsDir, { recursive: true });
|
||||
made.push(dirname(bobsDir));
|
||||
const before = readFileSync(SETTINGS_PATH, 'utf8');
|
||||
const res = await rename(app, 'alpha', { newName: 'bobs' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(existsSync(join(dirname(bobsDir), 'bobs'))).toBe(true);
|
||||
expect(readFileSync(SETTINGS_PATH, 'utf8')).toBe(before);
|
||||
});
|
||||
});
|
||||
@@ -54,6 +54,12 @@ vi.mock('node:fs/promises', () => ({
|
||||
throw err;
|
||||
}),
|
||||
writeFile: vi.fn(async () => {}),
|
||||
// What the linked-cases writer needs to replace the registry atomically (temp file + rename).
|
||||
realpath: vi.fn(async (p: string) => p),
|
||||
mkdir: vi.fn(async () => undefined),
|
||||
chmod: vi.fn(async () => {}),
|
||||
rename: vi.fn(async () => {}),
|
||||
rm: vi.fn(async () => {}),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -704,6 +710,7 @@ describe('case-routes', () => {
|
||||
});
|
||||
// linked-cases.json doesn't exist yet
|
||||
mockedReadFile.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
|
||||
mockedStat.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* @fileoverview A backup pass reads the backup folder once: one directory listing and one read per
|
||||
* manifest, shared by the recorded-retention fallback, the change check and the prune. Each used to
|
||||
* list the folder itself, which on a network folder meant every manifest read three times every five
|
||||
* minutes (found in review of #661).
|
||||
*
|
||||
* ⚠️ test/setup.ts gives the whole FILE one temp HOME. Port: N/A (no server).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const rec = vi.hoisted(() => ({ dir: '', calls: [] as string[] }));
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs')>();
|
||||
const record = <F extends (...a: never[]) => unknown>(name: string, real: F): F =>
|
||||
((path: unknown, ...rest: unknown[]) => {
|
||||
if (rec.dir && String(path).startsWith(rec.dir)) rec.calls.push(`${name} ${String(path)}`);
|
||||
return (real as unknown as (...a: unknown[]) => unknown)(path, ...rest);
|
||||
}) as unknown as F;
|
||||
const wrapped = {
|
||||
...actual,
|
||||
readdirSync: record('readdirSync', actual.readdirSync),
|
||||
readFileSync: record('readFileSync', actual.readFileSync),
|
||||
};
|
||||
return { ...wrapped, default: wrapped };
|
||||
});
|
||||
|
||||
import { runConfigBackup } from '../../src/web/routes/config-backup-routes.js';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { createConfigBackup, defaultConfigBackupDir, listConfigBackups } from '../../src/config-backup.js';
|
||||
|
||||
const dir = () => defaultConfigBackupDir(getDataDir());
|
||||
const DAY = 86_400_000;
|
||||
const BASE = Date.UTC(2025, 0, 1);
|
||||
|
||||
beforeEach(() => {
|
||||
rec.dir = '';
|
||||
rec.calls.length = 0;
|
||||
rmSync(dir(), { recursive: true, force: true });
|
||||
mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
rec.dir = '';
|
||||
rmSync(dir(), { recursive: true, force: true });
|
||||
rmSync(SETTINGS_PATH, { force: true });
|
||||
});
|
||||
|
||||
describe('one backup pass', () => {
|
||||
it('lists the folder once and reads each manifest once', async () => {
|
||||
// Only the OLDEST snapshot recorded a retention, so the fallback has to look through every one.
|
||||
for (let i = 0; i < 6; i++) {
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: `v${i}` }));
|
||||
createConfigBackup({
|
||||
dataDir: getDataDir(),
|
||||
backupDir: dir(),
|
||||
reason: 'auto',
|
||||
now: BASE + i * DAY,
|
||||
...(i === 0 && { keepCount: 100, keepDays: 0 }),
|
||||
});
|
||||
}
|
||||
// A change (so the pass writes a snapshot and then prunes) and no retention keys (the fallback reads).
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: 'changed' }));
|
||||
rec.dir = dir();
|
||||
const out = await runConfigBackup('auto');
|
||||
rec.dir = '';
|
||||
|
||||
expect(out?.result.status).toBe('created');
|
||||
expect(out?.removed).toEqual([]); // the recorded 100 / no age limit, not the defaults
|
||||
expect(rec.calls.filter((c) => c.startsWith('readdirSync'))).toHaveLength(1);
|
||||
const manifestReads = rec.calls.filter((c) => c.startsWith('readFileSync') && c.endsWith('manifest.json'));
|
||||
expect(manifestReads).toHaveLength(6);
|
||||
expect(new Set(manifestReads).size).toBe(6);
|
||||
expect(listConfigBackups(dir())).toHaveLength(7);
|
||||
});
|
||||
|
||||
it('counts the snapshot it just made when it prunes', async () => {
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepCount: 2, configBackupKeepDays: 0, v: 0 }));
|
||||
for (let i = 0; i < 3; i++) {
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepCount: 2, configBackupKeepDays: 0, v: i }));
|
||||
createConfigBackup({ dataDir: getDataDir(), backupDir: dir(), reason: 'auto', now: BASE + i * DAY });
|
||||
}
|
||||
const before = listConfigBackups(dir()).map((b) => b.id);
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepCount: 2, configBackupKeepDays: 0, v: 9 }));
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.result.status).toBe('created');
|
||||
const kept = listConfigBackups(dir()).map((b) => b.id);
|
||||
// keep 2: the new one and the newest before it; the two older ones go
|
||||
expect(kept).toEqual([(out?.result as { id: string }).id, before[0]]);
|
||||
expect(out?.removed.sort()).toEqual([before[1], before[2]].sort());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,346 @@
|
||||
/**
|
||||
* @fileoverview /api/config-backups: list, back up now, restore. Settings are read fresh from
|
||||
* settings.json, so a folder or retention change applies on the next request.
|
||||
*
|
||||
* ⚠️ test/setup.ts gives the whole FILE one temp HOME (and so one data dir). Port: N/A (inject()).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerConfigBackupRoutes, runConfigBackup } from '../../src/web/routes/config-backup-routes.js';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { createConfigBackup, defaultConfigBackupDir, listConfigBackups } from '../../src/config-backup.js';
|
||||
import { intentStore } from '../../src/intent-store.js';
|
||||
|
||||
let custom: string;
|
||||
const settings = (extra: Record<string, unknown> = {}) => {
|
||||
mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: 'before', ...extra }));
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
custom = mkdtempSync(join(tmpdir(), 'cfg-backup-route-'));
|
||||
rmSync(defaultConfigBackupDir(getDataDir()), { recursive: true, force: true });
|
||||
settings();
|
||||
});
|
||||
afterEach(() => {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
rmSync(custom, { recursive: true, force: true });
|
||||
rmSync(SETTINGS_PATH, { force: true });
|
||||
rmSync(defaultConfigBackupDir(getDataDir()), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('/api/config-backups', () => {
|
||||
it('lists the effective settings, the default folder and the tracked files', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const res = await app.inject({ method: 'GET', url: '/api/config-backups' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const d = res.json().data;
|
||||
expect(d.settings).toEqual({ enabled: true, dir: null, keepCount: 20, keepDays: 30 });
|
||||
expect(d.dir).toBe(defaultConfigBackupDir(getDataDir()));
|
||||
expect(d.tracked).toContain('settings.json');
|
||||
expect(d.backups).toEqual([]);
|
||||
});
|
||||
|
||||
it('backs up now into the default folder and lists it', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const made = await app.inject({ method: 'POST', url: '/api/config-backups' });
|
||||
expect(made.statusCode).toBe(200);
|
||||
expect(made.json().data.status).toBe('created');
|
||||
const list = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data;
|
||||
expect(list.backups).toHaveLength(1);
|
||||
expect(list.backups[0].reason).toBe('manual');
|
||||
expect(list.backups[0].files.map((f: { name: string }) => f.name)).toContain('settings.json');
|
||||
// Names and sizes only, never content.
|
||||
expect(JSON.stringify(list)).not.toContain('before');
|
||||
});
|
||||
|
||||
it('follows a custom folder and retention from settings on the next request', async () => {
|
||||
const dir = join(custom, 'snap');
|
||||
settings({ configBackupDir: dir, configBackupKeepCount: 2, configBackupKeepDays: 0 });
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupDir: dir, configBackupKeepCount: 2, i }));
|
||||
await app.inject({ method: 'POST', url: '/api/config-backups' });
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
}
|
||||
const d = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data;
|
||||
expect(d.dir).toBe(dir);
|
||||
expect(d.backups).toHaveLength(2);
|
||||
expect(existsSync(defaultConfigBackupDir(getDataDir()))).toBe(false);
|
||||
});
|
||||
|
||||
it('restores a backup, reports what needs a restart and keeps a pre-restore copy', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
writeFileSync(join(dirname(SETTINGS_PATH), 'clis.json'), '{"schemaVersion":1,"clis":{}}', { mode: 0o600 });
|
||||
const id = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: 'polluted' }));
|
||||
writeFileSync(join(dirname(SETTINGS_PATH), 'clis.json'), '{"clis":{"evil":{}}}');
|
||||
|
||||
const res = await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const d = res.json().data;
|
||||
expect(d.restored).toEqual(expect.arrayContaining(['settings.json', 'clis.json']));
|
||||
expect(d.restartRequired).not.toContain('clis.json'); // reloaded by the restore itself
|
||||
expect(d.restartRequired).toContain('settings.json'); // its watcher toggles are not re-run by a restore
|
||||
expect(d.safetySnapshot).toBeTruthy();
|
||||
expect(JSON.parse(readFileSync(SETTINGS_PATH, 'utf8')).displayName).toBe('before');
|
||||
});
|
||||
|
||||
it('a restore that fails partway names what it restored, what failed and the pre-restore copy', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const clis = join(dirname(SETTINGS_PATH), 'clis.json');
|
||||
writeFileSync(clis, '{"schemaVersion":1,"clis":{}}', { mode: 0o600 });
|
||||
const id = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ displayName: 'polluted' }));
|
||||
// A file the server cannot replace: settings.json (first in the list) goes back, clis.json cannot.
|
||||
rmSync(clis);
|
||||
mkdirSync(clis);
|
||||
try {
|
||||
const res = await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
expect(res.statusCode).toBe(500);
|
||||
const body = res.json();
|
||||
expect(body).toMatchObject({ success: false, errorCode: 'OPERATION_FAILED' });
|
||||
expect(body.error).toContain('clis.json');
|
||||
expect(body.data.restored).toContain('settings.json');
|
||||
expect(body.data.failed.map((f: { name: string }) => f.name)).toEqual(['clis.json']);
|
||||
expect(body.data.restartRequired).toContain('settings.json');
|
||||
expect(JSON.parse(readFileSync(SETTINGS_PATH, 'utf8')).displayName).toBe('before');
|
||||
// The undo copy exists, holds the state the restore replaced, and is the one named.
|
||||
const safety = body.data.safetySnapshot;
|
||||
expect(safety).toBeTruthy();
|
||||
expect(body.error).toContain(safety);
|
||||
const listed = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data.backups;
|
||||
expect(listed.find((b: { id: string }) => b.id === safety)?.reason).toBe('pre-restore');
|
||||
} finally {
|
||||
rmSync(clis, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('a restored discord.json reaches the running bridge (it caches its config)', async () => {
|
||||
const reloadDiscord = vi.fn(async () => undefined);
|
||||
const { app } = await createRouteTestHarness((a) => registerConfigBackupRoutes(a, { reloadDiscord }));
|
||||
writeFileSync(join(dirname(SETTINGS_PATH), 'discord.json'), '{"enabled":false}', { mode: 0o600 });
|
||||
const id = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
writeFileSync(join(dirname(SETTINGS_PATH), 'discord.json'), '{"enabled":true}', { mode: 0o600 });
|
||||
const res = await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
expect(res.json().data.restored).toContain('discord.json');
|
||||
expect(reloadDiscord).toHaveBeenCalledTimes(1);
|
||||
// A restore that does not carry the file leaves the bridge alone.
|
||||
rmSync(join(dirname(SETTINGS_PATH), 'discord.json'), { force: true });
|
||||
const id2 = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
await app.inject({ method: 'POST', url: `/api/config-backups/${id2}/restore` });
|
||||
expect(reloadDiscord).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('a restored intents.json is not reverted by the next captured prompt', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const dir = mkdtempSync(join(tmpdir(), 'cfg-backup-intent-'));
|
||||
try {
|
||||
intentStore.recordPrompt(undefined, dir, 's1', 'first prompt about the build pipeline');
|
||||
const id = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
intentStore.recordPrompt(undefined, dir, 's1', 'second prompt about the build pipeline');
|
||||
await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
intentStore.recordPrompt(undefined, dir, 's1', 'third prompt about the build pipeline');
|
||||
expect(intentStore.getProfile(undefined, dir).recentPrompts).toHaveLength(2);
|
||||
} finally {
|
||||
intentStore.deleteProfile(undefined, dir);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses a custom folder whose parent is missing instead of creating it', async () => {
|
||||
settings({ configBackupDir: join(custom, 'no', 'such', 'dir') });
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const res = await app.inject({ method: 'POST', url: '/api/config-backups' });
|
||||
expect(res.statusCode).toBe(503);
|
||||
expect(existsSync(join(custom, 'no'))).toBe(false);
|
||||
});
|
||||
|
||||
it('answers 404 for an unknown backup and 404 for a traversal attempt', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
for (const id of ['cfg-19990101-000000', '..%2F..%2Fetc', 'photos']) {
|
||||
const res = await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
expect(res.statusCode, id).toBe(404);
|
||||
}
|
||||
});
|
||||
|
||||
it('is admin only in multi-user mode: a non-admin is refused on every verb', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes, {
|
||||
authUser: { username: 'bob', role: 'user' },
|
||||
});
|
||||
for (const [method, url] of [
|
||||
['GET', '/api/config-backups'],
|
||||
['POST', '/api/config-backups'],
|
||||
['POST', '/api/config-backups/cfg-20261001-120000/restore'],
|
||||
['GET', '/api/config-backups/diff?from=cfg-20261001-120000'],
|
||||
] as const) {
|
||||
expect((await app.inject({ method, url })).statusCode, `${method} ${url}`).toBe(403);
|
||||
}
|
||||
});
|
||||
|
||||
it('multi-user: a restore is written to the admin audit log', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes, {
|
||||
authUser: { username: 'root', role: 'admin' },
|
||||
});
|
||||
const id = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data.id;
|
||||
await app.inject({ method: 'POST', url: `/api/config-backups/${id}/restore` });
|
||||
const auditPath = join(getDataDir(), 'admin-audit.jsonl');
|
||||
const written = () => existsSync(auditPath) && readFileSync(auditPath, 'utf8').includes('config_backup_restore');
|
||||
for (let i = 0; i < 40 && !written(); i++) await new Promise((r) => setTimeout(r, 25));
|
||||
const last = JSON.parse(readFileSync(auditPath, 'utf8').trim().split('\n').pop()!);
|
||||
expect(last).toMatchObject({ admin: 'root', action: 'config_backup_restore', target: id });
|
||||
expect(last.detail.restored).toContain('settings.json');
|
||||
rmSync(auditPath, { force: true });
|
||||
});
|
||||
|
||||
it('multi-user: an admin is allowed', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes, {
|
||||
authUser: { username: 'root', role: 'admin' },
|
||||
});
|
||||
expect((await app.inject({ method: 'GET', url: '/api/config-backups' })).json().success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/config-backups/diff', () => {
|
||||
it('compares a backup with the running config, defaulting `to` to current', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const made = (await app.inject({ method: 'POST', url: '/api/config-backups' })).json().data;
|
||||
settings({ displayName: 'after' });
|
||||
const res = await app.inject({ method: 'GET', url: `/api/config-backups/diff?from=${made.id}` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const d = res.json().data;
|
||||
expect(d.to).toBe('current');
|
||||
expect(d.files.find((f: { name: string }) => f.name === 'settings.json').changes).toEqual([
|
||||
{ path: 'displayName', kind: 'changed', before: '"before"', after: '"after"' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('400 without `from`, 404 for an unknown backup', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
expect((await app.inject({ method: 'GET', url: '/api/config-backups/diff' })).statusCode).toBe(400);
|
||||
const missing = await app.inject({ method: 'GET', url: '/api/config-backups/diff?from=cfg-20200101-000000' });
|
||||
expect(missing.statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('retention survives an unreadable or reset settings.json', () => {
|
||||
const DAY = 86_400_000;
|
||||
const BASE = Date.UTC(2025, 0, 1);
|
||||
const dir = () => defaultConfigBackupDir(getDataDir());
|
||||
/** 30 snapshots a day apart, made under a long-history retention (100 copies, no age limit). */
|
||||
function seed(withKeys = true) {
|
||||
settings({ configBackupKeepCount: 100, configBackupKeepDays: 0 });
|
||||
for (let i = 0; i < 30; i++) {
|
||||
writeFileSync(
|
||||
SETTINGS_PATH,
|
||||
JSON.stringify(
|
||||
withKeys
|
||||
? { displayName: `v${i}`, configBackupKeepCount: 100, configBackupKeepDays: 0 }
|
||||
: { displayName: `v${i}` }
|
||||
)
|
||||
);
|
||||
createConfigBackup({
|
||||
dataDir: getDataDir(),
|
||||
backupDir: dir(),
|
||||
reason: 'auto',
|
||||
now: BASE + i * DAY,
|
||||
keepCount: 100,
|
||||
keepDays: 0,
|
||||
});
|
||||
}
|
||||
expect(listConfigBackups(dir())).toHaveLength(30);
|
||||
}
|
||||
|
||||
it('a settings.json that does not parse still gets a snapshot but prunes nothing', async () => {
|
||||
seed();
|
||||
writeFileSync(SETTINGS_PATH, '{ "displayName": "half-written", }');
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.result.status).toBe('created');
|
||||
expect(out?.removed).toEqual([]);
|
||||
expect(listConfigBackups(dir())).toHaveLength(31);
|
||||
});
|
||||
|
||||
it('a reset settings.json prunes with the retention the newest snapshot recorded, not the defaults', async () => {
|
||||
seed();
|
||||
writeFileSync(SETTINGS_PATH, '{}');
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.result.status).toBe('created');
|
||||
// aged manifests (a year old) and keepDays 0: the defaults (20 copies, 30 days) would leave 20
|
||||
expect(listConfigBackups(dir())).toHaveLength(31);
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
'a restore after a reset keeps the retention (the backup %s the four keys)',
|
||||
async (withKeys) => {
|
||||
seed(withKeys);
|
||||
const oldest = listConfigBackups(dir()).at(-1)!.id;
|
||||
writeFileSync(SETTINGS_PATH, '{}'); // the reset
|
||||
expect((await runConfigBackup('auto'))?.removed).toEqual([]);
|
||||
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const res = await app.inject({ method: 'POST', url: `/api/config-backups/${oldest}/restore` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
// the restored file carries the retention, or the recorded one still applies via the pre-restore copy
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.removed).toEqual([]);
|
||||
expect(listConfigBackups(dir()).length).toBeGreaterThanOrEqual(32);
|
||||
const status = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data.settings;
|
||||
expect(status).toMatchObject({ keepCount: 100, keepDays: 0 }); // what the form shows is what the pass uses
|
||||
}
|
||||
);
|
||||
|
||||
it("re-entering a custom folder after a reset finds that folder's recorded retention", async () => {
|
||||
const folder = join(custom, 'kept');
|
||||
settings({ configBackupDir: folder, configBackupKeepCount: 100, configBackupKeepDays: 0 });
|
||||
for (let i = 0; i < 30; i++) {
|
||||
createConfigBackup({
|
||||
dataDir: getDataDir(),
|
||||
backupDir: folder,
|
||||
reason: 'auto',
|
||||
force: true,
|
||||
now: BASE + i * DAY,
|
||||
keepCount: 100,
|
||||
keepDays: 0,
|
||||
});
|
||||
}
|
||||
writeFileSync(SETTINGS_PATH, '{}'); // the reset drops the folder too
|
||||
await runConfigBackup('auto'); // goes to the default folder, which holds none of those manifests
|
||||
// the user enters the folder again and saves; the form no longer sends retention it only displayed
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupDir: folder, configBackupEnabled: true }));
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const reported = (await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data.settings;
|
||||
expect(reported).toMatchObject({ keepCount: 100, keepDays: 0 });
|
||||
const out = await runConfigBackup('auto');
|
||||
expect(out?.removed).toEqual([]);
|
||||
expect(listConfigBackups(folder).length).toBeGreaterThanOrEqual(30);
|
||||
});
|
||||
|
||||
it('only the retention key the file lacks falls back to the recorded one', async () => {
|
||||
seed();
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepDays: 3650 }));
|
||||
await runConfigBackup('auto');
|
||||
expect(listConfigBackups(dir())).toHaveLength(31); // keepCount 100 from the manifests, not the default 20
|
||||
});
|
||||
|
||||
it('a settings.json that sets the retention still wins', async () => {
|
||||
seed();
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupKeepCount: 5, configBackupKeepDays: 0 }));
|
||||
await runConfigBackup('auto');
|
||||
expect(listConfigBackups(dir())).toHaveLength(5);
|
||||
});
|
||||
|
||||
it('listing never creates config-backup-id', async () => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const idFile = join(getDataDir(), 'config-backup-id');
|
||||
rmSync(idFile, { force: true });
|
||||
expect((await app.inject({ method: 'GET', url: '/api/config-backups' })).json().data.backups).toEqual([]);
|
||||
expect(existsSync(idFile)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* @fileoverview A custom backup folder that stops answering (a network mount) must never be listed or
|
||||
* read before the bounded probe says it is there: GET, Back up now, diff and restore answer 503 without
|
||||
* touching it.
|
||||
* With only `configBackupDir` in settings.json the recorded-retention fallback would otherwise
|
||||
* `readdirSync` the folder first (found in review of #661).
|
||||
*
|
||||
* ⚠️ test/setup.ts gives the whole FILE one temp HOME. Port: N/A (inject()).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const dead = vi.hoisted(() => ({ dir: '', touched: [] as string[] }));
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('node:fs')>();
|
||||
const record = <F extends (...a: never[]) => unknown>(name: string, real: F): F =>
|
||||
((path: unknown, ...rest: unknown[]) => {
|
||||
if (dead.dir && String(path).startsWith(dead.dir)) dead.touched.push(`${name} ${String(path)}`);
|
||||
return (real as unknown as (...a: unknown[]) => unknown)(path, ...rest);
|
||||
}) as unknown as F;
|
||||
const wrapped = {
|
||||
...actual,
|
||||
readdirSync: record('readdirSync', actual.readdirSync),
|
||||
readFileSync: record('readFileSync', actual.readFileSync),
|
||||
statSync: record('statSync', actual.statSync),
|
||||
lstatSync: record('lstatSync', actual.lstatSync),
|
||||
existsSync: record('existsSync', actual.existsSync),
|
||||
};
|
||||
return { ...wrapped, default: wrapped };
|
||||
});
|
||||
|
||||
vi.mock('../../src/utils/bounded-path-probe.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/utils/bounded-path-probe.js')>();
|
||||
return {
|
||||
...actual,
|
||||
probePathKind: async (path: string, options?: { pastCap?: boolean }) =>
|
||||
dead.dir && path.startsWith(dead.dir) ? 'unknown' : actual.probePathKind(path, options),
|
||||
};
|
||||
});
|
||||
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerConfigBackupRoutes } from '../../src/web/routes/config-backup-routes.js';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { configBackupOrigin } from '../../src/config-backup.js';
|
||||
|
||||
let root: string;
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'cfg-backup-dead-'));
|
||||
dead.dir = join(root, 'mount');
|
||||
dead.touched.length = 0;
|
||||
configBackupOrigin(getDataDir()); // an instance that already has an id: the fallback has something to look for
|
||||
mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
|
||||
// Only the folder: no retention keys, the shape that makes the recorded-retention fallback want to read it.
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify({ configBackupDir: dead.dir }));
|
||||
});
|
||||
afterEach(() => {
|
||||
dead.dir = '';
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
rmSync(SETTINGS_PATH, { force: true });
|
||||
});
|
||||
|
||||
describe('a custom backup folder that does not answer', () => {
|
||||
it.each([
|
||||
['GET', '/api/config-backups'],
|
||||
['POST', '/api/config-backups'],
|
||||
['GET', '/api/config-backups/diff?from=cfg-20261001-120000'],
|
||||
['POST', '/api/config-backups/cfg-20261001-120000/restore'],
|
||||
] as const)('%s %s answers 503 without reading the folder', async (method, url) => {
|
||||
const { app } = await createRouteTestHarness(registerConfigBackupRoutes);
|
||||
const res = await app.inject({ method, url });
|
||||
expect(res.statusCode).toBe(503);
|
||||
expect(dead.touched).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -8,10 +8,13 @@
|
||||
* been bypassed.
|
||||
* Port: N/A (app.inject, no real port needed)
|
||||
*/
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
|
||||
import { readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||||
import { dataPath, getDataDir } from '../../src/config/instance.js';
|
||||
import { customModelHostsPath, readCustomModelHosts, type CustomModelHost } from '../../src/custom-model-hosts.js';
|
||||
import { registerCustomModelRoutes } from '../../src/web/routes/custom-model-routes.js';
|
||||
import { webviewFetch } from '../../src/web/webview-egress.js';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
|
||||
vi.mock('../../src/web/webview-egress.js', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../src/web/webview-egress.js')>(
|
||||
@@ -417,3 +420,440 @@ describe('apiKey is never handed back to the browser', () => {
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('context-length discovery from the /v1/models listing', () => {
|
||||
// The gateway path (a Bifrost in front of llama-swap, an OpenRouter-style server):
|
||||
// no /running, no /props, just a per-model `context_length` or `context_window` in the
|
||||
// model listing. Distinct ports per test keep the file's shared data dir unambiguous.
|
||||
afterEach(() => {
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
type StoredHost = { id: string; modelContextLengths?: Record<string, number>; defaultContextLength?: number };
|
||||
|
||||
type HarnessApp = RouteTestHarness['app'];
|
||||
|
||||
async function endpointWith(id: string, port: number, extra: Record<string, unknown> = {}): Promise<HarnessApp> {
|
||||
const { app } = await setup();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id, label: 'A', baseUrl: `http://localhost:${port}`, ...extra },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
return app;
|
||||
}
|
||||
|
||||
async function storedHost(app: HarnessApp, id: string): Promise<StoredHost | undefined> {
|
||||
const list = await app.inject({ method: 'GET', url: '/api/model-endpoints' });
|
||||
return (list.json() as StoredHost[]).find((h) => h.id === id);
|
||||
}
|
||||
|
||||
it('reads context_length (preferred) then context_window from each entry into modelContextLengths', async () => {
|
||||
const app = await endpointWith('ep-ctx-listed', 8101);
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: [
|
||||
{ id: 'both', context_length: 131072, context_window: 32768 },
|
||||
{ id: 'window-only', context_window: 8192 },
|
||||
{ id: 'no-figure' },
|
||||
],
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
);
|
||||
|
||||
const discover = await app.inject({ method: 'POST', url: '/api/model-endpoints/ep-ctx-listed/discover-models' });
|
||||
expect(discover.json().success).toBe(true);
|
||||
|
||||
const stored = await storedHost(app, 'ep-ctx-listed');
|
||||
expect(stored?.modelContextLengths).toEqual({ both: 131072, 'window-only': 8192 });
|
||||
});
|
||||
|
||||
it('ignores non-numeric, zero, negative and absurd listed values; the schema bound itself is still accepted', async () => {
|
||||
const app = await endpointWith('ep-ctx-bad', 8102);
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
data: [
|
||||
{ id: 'string', context_length: '131072' },
|
||||
{ id: 'zero', context_window: 0 },
|
||||
{ id: 'negative', context_length: -10 },
|
||||
{ id: 'over-bound', context_length: 100_000_001 },
|
||||
{ id: 'fractional', context_window: 16384.5 },
|
||||
{ id: 'at-bound', context_length: 100_000_000 },
|
||||
],
|
||||
}),
|
||||
{ status: 200 }
|
||||
)
|
||||
);
|
||||
|
||||
await app.inject({ method: 'POST', url: '/api/model-endpoints/ep-ctx-bad/discover-models' });
|
||||
|
||||
const stored = await storedHost(app, 'ep-ctx-bad');
|
||||
expect(stored?.modelContextLengths).toEqual({ 'at-bound': 100_000_000 });
|
||||
});
|
||||
|
||||
it('prefers the /running launch command over the listed figure for a loaded model', async () => {
|
||||
const app = await endpointWith('ep-ctx-cmd', 8103);
|
||||
fetchMock.mockImplementation(async (url: URL) => {
|
||||
if (url.pathname === '/v1/models') {
|
||||
return new Response(
|
||||
JSON.stringify({ data: [{ id: 'cmd-wins', status: { value: 'loaded' }, context_length: 131072 }] }),
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
if (url.pathname === '/running') {
|
||||
return new Response(
|
||||
JSON.stringify({ running: [{ model: 'cmd-wins', state: 'ready', cmd: 'llama-server --ctx-size 16384' }] }),
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
if (url.pathname === '/props') return new Response('nope', { status: 404 });
|
||||
throw new Error(`unexpected request in this test: ${url.href}`);
|
||||
});
|
||||
|
||||
await app.inject({ method: 'POST', url: '/api/model-endpoints/ep-ctx-cmd/discover-models' });
|
||||
|
||||
const stored = await storedHost(app, 'ep-ctx-cmd');
|
||||
expect(stored?.modelContextLengths).toEqual({ 'cmd-wins': 16384 });
|
||||
});
|
||||
|
||||
it('keeps a previously learned value the fresh listing says nothing about, and discovery never touches defaultContextLength', async () => {
|
||||
const app = await endpointWith('ep-ctx-keep', 8104, {
|
||||
models: ['re-listed', 'untouched'],
|
||||
modelContextLengths: { 're-listed': 16384, untouched: 4096 },
|
||||
defaultContextLength: 65536,
|
||||
});
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ data: [{ id: 're-listed', context_length: 32768 }, { id: 'untouched' }] }), {
|
||||
status: 200,
|
||||
})
|
||||
);
|
||||
|
||||
await app.inject({ method: 'POST', url: '/api/model-endpoints/ep-ctx-keep/discover-models' });
|
||||
|
||||
const stored = await storedHost(app, 'ep-ctx-keep');
|
||||
expect(stored?.modelContextLengths).toEqual({ 're-listed': 32768, untouched: 4096 });
|
||||
expect(stored?.defaultContextLength).toBe(65536);
|
||||
});
|
||||
});
|
||||
|
||||
describe('defaultContextLength (the user-set fallback discovery never overwrites)', () => {
|
||||
afterEach(() => {
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
it('stores it on create, updates it on PUT, and a PUT without it clears it', async () => {
|
||||
const { app } = await setup();
|
||||
const create = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id: 'ep-defctx', label: 'A', baseUrl: 'http://localhost:8105', defaultContextLength: 131072 },
|
||||
});
|
||||
expect(create.json().data.host.defaultContextLength).toBe(131072);
|
||||
|
||||
const update = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/model-endpoints/ep-defctx',
|
||||
payload: { label: 'A', baseUrl: 'http://localhost:8105', defaultContextLength: 32768 },
|
||||
});
|
||||
expect(update.json().data.host.defaultContextLength).toBe(32768);
|
||||
|
||||
const cleared = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/model-endpoints/ep-defctx',
|
||||
payload: { label: 'A', baseUrl: 'http://localhost:8105' },
|
||||
});
|
||||
expect(cleared.json().data.host.defaultContextLength).toBeUndefined();
|
||||
});
|
||||
|
||||
it('rejects zero, negative, fractional, over-the-bound and non-numeric values', async () => {
|
||||
const { app } = await setup();
|
||||
for (const defaultContextLength of [0, -1, 1.5, 100_000_001, '131072']) {
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id: 'ep-defctx-bad', label: 'A', baseUrl: 'http://localhost:8106', defaultContextLength },
|
||||
});
|
||||
expect(res.json().success, String(defaultContextLength)).toBe(false);
|
||||
expect(res.json().errorCode, String(defaultContextLength)).toBe('INVALID_INPUT');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('every write goes through the serialized writer', () => {
|
||||
const HOSTS = () => customModelHostsPath(getDataDir());
|
||||
|
||||
beforeEach(() => {
|
||||
rmSync(HOSTS(), { force: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fetchMock.mockReset();
|
||||
rmSync(HOSTS(), { force: true });
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('ten creates sent at once all land (each used to read, change and write on its own)', async () => {
|
||||
const { app } = await setup();
|
||||
const ids = Array.from({ length: 10 }, (_, i) => `burst${i}`);
|
||||
const responses = await Promise.all(
|
||||
ids.map((id) =>
|
||||
app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id, label: id, baseUrl: 'http://localhost:8200', apiKey: `sk-${id}` },
|
||||
})
|
||||
)
|
||||
);
|
||||
for (const res of responses) expect(res.json().success).toBe(true);
|
||||
const stored = await readCustomModelHosts(getDataDir());
|
||||
expect(stored.map((host) => host.id).sort()).toEqual([...ids].sort());
|
||||
// Every key survived: none of the writes replaced the list with its own record.
|
||||
for (const host of stored) expect(host.apiKey).toBe(`sk-${host.id}`);
|
||||
});
|
||||
|
||||
it('two creates of one id sent at once: one is stored, the other is told it exists', async () => {
|
||||
const { app } = await setup();
|
||||
const create = (label: string) =>
|
||||
app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id: 'race', label, baseUrl: 'http://localhost:8201' },
|
||||
});
|
||||
const [first, second] = await Promise.all([create('one'), create('two')]);
|
||||
expect([first.json().success, second.json().success].sort()).toEqual([false, true]);
|
||||
expect([first.json().errorCode, second.json().errorCode]).toContain('ALREADY_EXISTS');
|
||||
const stored = await readCustomModelHosts(getDataDir());
|
||||
expect(stored).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('a discovery that takes a moment does not undo an edit made while it ran', async () => {
|
||||
const { app } = await setup();
|
||||
await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id: 'slow', label: 'Before', baseUrl: 'http://localhost:8202' },
|
||||
});
|
||||
let answer: (response: Response) => void = () => {};
|
||||
fetchMock.mockImplementation(
|
||||
(async () => new Promise<Response>((resolve) => (answer = resolve))) as unknown as typeof webviewFetch
|
||||
);
|
||||
const discovering = app.inject({ method: 'POST', url: '/api/model-endpoints/slow/discover-models' });
|
||||
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalled());
|
||||
|
||||
// The endpoint is renamed while the probe is still out.
|
||||
const renamed = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/model-endpoints/slow',
|
||||
payload: { label: 'After', baseUrl: 'http://localhost:8202' },
|
||||
});
|
||||
expect(renamed.json().success).toBe(true);
|
||||
|
||||
answer(new Response(JSON.stringify({ data: [{ id: 'qwen3' }] }), { status: 200 }));
|
||||
expect((await discovering).json()).toEqual({ success: true, data: { models: ['qwen3'] } });
|
||||
|
||||
const [stored] = await readCustomModelHosts(getDataDir());
|
||||
// Both changes are there: the new name and the discovered list.
|
||||
expect(stored.label).toBe('After');
|
||||
expect(stored.models).toEqual(['qwen3']);
|
||||
});
|
||||
|
||||
it('an endpoint deleted while its discovery ran stays deleted', async () => {
|
||||
const { app } = await setup();
|
||||
await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id: 'gone', label: 'Gone', baseUrl: 'http://localhost:8203' },
|
||||
});
|
||||
let answer: (response: Response) => void = () => {};
|
||||
fetchMock.mockImplementation(
|
||||
(async () => new Promise<Response>((resolve) => (answer = resolve))) as unknown as typeof webviewFetch
|
||||
);
|
||||
const discovering = app.inject({ method: 'POST', url: '/api/model-endpoints/gone/discover-models' });
|
||||
await vi.waitFor(() => expect(fetchMock).toHaveBeenCalled());
|
||||
await app.inject({ method: 'DELETE', url: '/api/model-endpoints/gone' });
|
||||
answer(new Response(JSON.stringify({ data: [{ id: 'qwen3' }] }), { status: 200 }));
|
||||
expect((await discovering).json()).toMatchObject({ success: false, errorCode: 'NOT_FOUND' });
|
||||
expect(await readCustomModelHosts(getDataDir())).toEqual([]);
|
||||
});
|
||||
|
||||
it('deleting an id that is not saved leaves the file as it is', async () => {
|
||||
const { app } = await setup();
|
||||
await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id: 'keep', label: 'Keep', baseUrl: 'http://localhost:8204' },
|
||||
});
|
||||
const before = { text: readFileSync(HOSTS(), 'utf8'), mtime: statSync(HOSTS()).mtimeMs };
|
||||
const res = await app.inject({ method: 'DELETE', url: '/api/model-endpoints/never-saved' });
|
||||
expect(res.json()).toEqual({ success: true, data: { id: 'never-saved' } });
|
||||
expect(readFileSync(HOSTS(), 'utf8')).toBe(before.text);
|
||||
expect(statSync(HOSTS()).mtimeMs).toBe(before.mtime);
|
||||
});
|
||||
|
||||
describe('a store that does not parse', () => {
|
||||
const BROKEN = '[{"id":"mine","label":"Mine","baseUrl":"http://localhost:9","apiKey":"sk-keep-me"},';
|
||||
|
||||
beforeEach(() => {
|
||||
writeFileSync(HOSTS(), BROKEN);
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['create', 'POST', '/api/model-endpoints', { id: 'new', label: 'New', baseUrl: 'http://localhost:8205' }],
|
||||
['update', 'PUT', '/api/model-endpoints/mine', { label: 'Renamed', baseUrl: 'http://localhost:8205' }],
|
||||
['delete', 'DELETE', '/api/model-endpoints/mine', undefined],
|
||||
] as const)(
|
||||
'%s is refused with 409 and the file is left byte for byte (it used to be replaced by one record)',
|
||||
async (_label, method, url, payload) => {
|
||||
const { app } = await setup();
|
||||
const res = await app.inject({ method, url, ...(payload ? { payload } : {}) });
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toMatchObject({ success: false, errorCode: 'CONFLICT' });
|
||||
expect(res.json().error).toContain('custom-model-hosts.json');
|
||||
// The refusal never repeats the file, which holds a key.
|
||||
expect(res.body).not.toContain('sk-keep-me');
|
||||
expect(readFileSync(HOSTS(), 'utf8')).toBe(BROKEN);
|
||||
}
|
||||
);
|
||||
|
||||
it('reading still answers an empty list, as before', async () => {
|
||||
const { app } = await setup();
|
||||
expect((await app.inject({ method: 'GET', url: '/api/model-endpoints' })).json()).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('the endpoint the local model install manages', () => {
|
||||
const HOSTS = () => customModelHostsPath(getDataDir());
|
||||
const STATE = () => dataPath('local-model.json');
|
||||
|
||||
const RECORD: CustomModelHost = {
|
||||
id: 'local-ollama',
|
||||
label: 'This Mac',
|
||||
baseUrl: 'http://127.0.0.1:11435',
|
||||
authStyle: 'bearer',
|
||||
models: ['qwen3.6:35b-a3b'],
|
||||
defaultModelId: 'qwen3.6:35b-a3b',
|
||||
defaultContextLength: 131072,
|
||||
};
|
||||
|
||||
/** The state file of an installed model whose connection is the record above. */
|
||||
function markManaged(): void {
|
||||
writeFileSync(
|
||||
STATE(),
|
||||
JSON.stringify({
|
||||
schema: 1,
|
||||
state: 'installed',
|
||||
model: { id: 'qwen3.6:35b-a3b', label: 'Qwen3.6 35B-A3B', context: 131072 },
|
||||
cli: { id: 'opencode', label: 'OpenCode' },
|
||||
runtime: { version: '0.40.15', port: 11435, enabled: true },
|
||||
connection: { endpointId: 'local-ollama', flagWasEnabled: false },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
rmSync(STATE(), { force: true });
|
||||
writeFileSync(HOSTS(), JSON.stringify([RECORD]));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
fetchMock.mockReset();
|
||||
rmSync(STATE(), { force: true });
|
||||
rmSync(HOSTS(), { force: true });
|
||||
});
|
||||
|
||||
it('a new endpoint may not take the reserved id, whether or not a model is installed', async () => {
|
||||
rmSync(HOSTS(), { force: true });
|
||||
const { app } = await setup();
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id: 'local-ollama', label: 'Mine', baseUrl: 'http://127.0.0.1:11434' },
|
||||
});
|
||||
expect(res.json()).toEqual({
|
||||
success: false,
|
||||
error: 'This endpoint id is reserved for the model Codeman runs on this Mac. Pick another id.',
|
||||
errorCode: 'INVALID_INPUT',
|
||||
});
|
||||
expect(await readCustomModelHosts(getDataDir())).toEqual([]);
|
||||
});
|
||||
|
||||
it('while it is managed it is not edited: its port stays the runtime Codeman supervises', async () => {
|
||||
markManaged();
|
||||
const { app } = await setup();
|
||||
const res = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/model-endpoints/local-ollama',
|
||||
payload: { label: 'This Mac', baseUrl: 'http://192.168.1.99:11434' },
|
||||
});
|
||||
expect(res.json()).toEqual({
|
||||
success: false,
|
||||
error:
|
||||
'This endpoint belongs to the model Codeman runs on this Mac. Change or remove it in the local model window.',
|
||||
errorCode: 'INVALID_INPUT',
|
||||
});
|
||||
expect(await readCustomModelHosts(getDataDir())).toEqual([RECORD]);
|
||||
});
|
||||
|
||||
it('while it is managed it is not deleted from here: the runtime would keep running without it', async () => {
|
||||
markManaged();
|
||||
const { app } = await setup();
|
||||
const res = await app.inject({ method: 'DELETE', url: '/api/model-endpoints/local-ollama' });
|
||||
expect(res.json()).toMatchObject({ success: false, errorCode: 'INVALID_INPUT' });
|
||||
expect(await readCustomModelHosts(getDataDir())).toEqual([RECORD]);
|
||||
});
|
||||
|
||||
it('while it is managed a discovery answers the one model the install checked and asks the runtime nothing', async () => {
|
||||
markManaged();
|
||||
const { app } = await setup();
|
||||
const res = await app.inject({ method: 'POST', url: '/api/model-endpoints/local-ollama/discover-models' });
|
||||
expect(res.json()).toEqual({ success: true, data: { models: ['qwen3.6:35b-a3b'] } });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
expect(await readCustomModelHosts(getDataDir())).toEqual([RECORD]);
|
||||
});
|
||||
|
||||
it('it is listed like any other endpoint', async () => {
|
||||
markManaged();
|
||||
const { app } = await setup();
|
||||
const list = (await app.inject({ method: 'GET', url: '/api/model-endpoints' })).json();
|
||||
expect(list).toEqual([{ ...RECORD, apiKeySet: false }]);
|
||||
});
|
||||
|
||||
it('a record with that id that nobody installed (made by hand) can still be edited and deleted by its owner', async () => {
|
||||
// No state file: this feature wrote nothing, so the record is the person's own.
|
||||
const { app } = await setup();
|
||||
const update = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/model-endpoints/local-ollama',
|
||||
payload: { label: 'My own Ollama', baseUrl: 'http://127.0.0.1:11434' },
|
||||
});
|
||||
expect(update.json().success).toBe(true);
|
||||
expect((await readCustomModelHosts(getDataDir()))[0].label).toBe('My own Ollama');
|
||||
const del = await app.inject({ method: 'DELETE', url: '/api/model-endpoints/local-ollama' });
|
||||
expect(del.json()).toEqual({ success: true, data: { id: 'local-ollama' } });
|
||||
expect(await readCustomModelHosts(getDataDir())).toEqual([]);
|
||||
});
|
||||
|
||||
it('any other endpoint is edited and deleted as before while a model is installed', async () => {
|
||||
markManaged();
|
||||
const { app } = await setup();
|
||||
await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/model-endpoints',
|
||||
payload: { id: 'office', label: 'Office', baseUrl: 'http://localhost:8210' },
|
||||
});
|
||||
const update = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/model-endpoints/office',
|
||||
payload: { label: 'Office GPU', baseUrl: 'http://localhost:8210' },
|
||||
});
|
||||
expect(update.json().data.host.label).toBe('Office GPU');
|
||||
await app.inject({ method: 'DELETE', url: '/api/model-endpoints/office' });
|
||||
expect(await readCustomModelHosts(getDataDir())).toEqual([RECORD]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* @fileoverview The last message a CLI wrote, read through the response viewer's reader (the one the
|
||||
* Discord bridge posts from), with a message that asks SEVERAL questions: every question must come
|
||||
* back whole, in order, on its own line, and survive the split into Discord posts.
|
||||
*
|
||||
* Uses app.inject() with a temporary HOME and CODEX_HOME; no real ports or user transcripts.
|
||||
* Port: N/A
|
||||
*
|
||||
* Covered here: claude (JSONL transcript), codex (rollout), the codex-shaped pane CLIs (opencode,
|
||||
* gemini, antigravity, pi) and copilot (its own pane dialect). deepseek and omp read their own
|
||||
* transcript formats and are covered by their reader's tests.
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
import { splitForDiscord } from '../../src/discord-bridge.js';
|
||||
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
|
||||
|
||||
const QUESTIONS = [
|
||||
'Should the sweep run daily or hourly?',
|
||||
'Do you want archived threads deleted as well?',
|
||||
'Is one channel per Codeman acceptable?',
|
||||
];
|
||||
const INTRO = 'I have three questions before I continue:';
|
||||
const OUTRO = 'Once you answer, I will apply the change.';
|
||||
|
||||
/** The message as the CLI wrote it: an intro, a numbered list of questions, an outro. */
|
||||
const MESSAGE = [INTRO, '', ...QUESTIONS.map((q, i) => `${i + 1}. ${q}`), '', OUTRO].join('\n');
|
||||
|
||||
/** Every question present, in order, each on a line of its own. */
|
||||
function expectWholeQuestions(text: string): void {
|
||||
let from = 0;
|
||||
for (const q of QUESTIONS) {
|
||||
const at = text.indexOf(q, from);
|
||||
expect(at, `missing or out of order: ${q}`).toBeGreaterThanOrEqual(from);
|
||||
from = at + q.length;
|
||||
}
|
||||
const lines = text.split('\n').map((l) => l.trim());
|
||||
for (const [i, q] of QUESTIONS.entries()) expect(lines.some((l) => l.endsWith(q))).toBe(true);
|
||||
expect(text).toContain(INTRO);
|
||||
expect(text).toContain(OUTRO);
|
||||
// What goes to Discord: the same questions after the split, joined back.
|
||||
expectWholeQuestionsAfterSplit(text);
|
||||
}
|
||||
|
||||
function expectWholeQuestionsAfterSplit(text: string): void {
|
||||
const joined = splitForDiscord(text).join('\n');
|
||||
for (const q of QUESTIONS) expect(joined).toContain(q);
|
||||
}
|
||||
|
||||
async function createHarness(): Promise<{ app: FastifyInstance; ctx: MockRouteContext }> {
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
const ctx = createMockRouteContext();
|
||||
registerSessionRoutes(app, ctx);
|
||||
app.addHook('preSerialization', (req, _reply, payload: unknown, done) => {
|
||||
if (!req.url.startsWith('/api') || payload === null || typeof payload !== 'object') return done(null, payload);
|
||||
const p = payload as { success?: unknown };
|
||||
return done(null, p.success === undefined ? { success: true, data: payload } : payload);
|
||||
});
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
return { app, ctx };
|
||||
}
|
||||
|
||||
describe('the last message with several questions, per CLI', () => {
|
||||
let harness: { app: FastifyInstance; ctx: MockRouteContext };
|
||||
let home: string;
|
||||
let prevHome: string | undefined;
|
||||
let prevCodexHome: string | undefined;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let session: any;
|
||||
|
||||
async function lastText(): Promise<string> {
|
||||
const res = await harness.app.inject({ method: 'GET', url: `/api/sessions/${session.id}/last-response` });
|
||||
return JSON.parse(res.body).data.text as string;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
home = mkdtempSync(join(tmpdir(), 'codeman-discord-last-'));
|
||||
prevHome = process.env.HOME;
|
||||
prevCodexHome = process.env.CODEX_HOME;
|
||||
process.env.HOME = home;
|
||||
process.env.CODEX_HOME = join(home, '.codex');
|
||||
harness = await createHarness();
|
||||
session = harness.ctx._session;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (prevHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = prevHome;
|
||||
if (prevCodexHome === undefined) delete process.env.CODEX_HOME;
|
||||
else process.env.CODEX_HOME = prevCodexHome;
|
||||
rmSync(home, { recursive: true, force: true });
|
||||
await harness.app.close();
|
||||
});
|
||||
|
||||
it('claude: reads the whole message from the JSONL transcript', async () => {
|
||||
const id = '40568a29-d4eb-4eb6-b671-8401428e4f39';
|
||||
session.mode = 'claude';
|
||||
session.claudeSessionId = id;
|
||||
session.adoptClaudeSessionId = () => undefined;
|
||||
const dir = join(home, '.claude', 'projects', '-workspace');
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const row = (type: string, text: string, ts: string) => ({
|
||||
type,
|
||||
timestamp: ts,
|
||||
message: { content: [{ type: 'text', text }] },
|
||||
});
|
||||
writeFileSync(
|
||||
join(dir, `${id}.jsonl`),
|
||||
[row('user', 'plan the cleanup', '2026-10-30T00:00:00Z'), row('assistant', MESSAGE, '2026-10-30T00:00:01Z')]
|
||||
.map((e) => JSON.stringify(e))
|
||||
.join('\n')
|
||||
);
|
||||
const text = await lastText();
|
||||
expect(text).toBe(MESSAGE);
|
||||
expectWholeQuestions(text);
|
||||
});
|
||||
|
||||
it('codex: reads the whole message from the rollout', async () => {
|
||||
const uuid = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
||||
const workdir = join(home, 'work');
|
||||
mkdirSync(workdir, { recursive: true });
|
||||
session.mode = 'codex';
|
||||
session.workingDir = workdir;
|
||||
session.codexConfig = { resumeSessionId: uuid };
|
||||
const dir = join(home, '.codex', 'sessions', '2026', '10', '30');
|
||||
mkdirSync(dir, { recursive: true });
|
||||
const file = join(dir, `rollout-2026-10-30T00-00-00-${uuid}.jsonl`);
|
||||
const entries = [
|
||||
{
|
||||
timestamp: '2026-10-30T00:00:00Z',
|
||||
type: 'session_meta',
|
||||
payload: { id: uuid, cwd: workdir, originator: 'codex_cli_rs' },
|
||||
},
|
||||
{
|
||||
timestamp: '2026-10-30T00:00:01Z',
|
||||
type: 'event_msg',
|
||||
payload: { type: 'user_message', message: 'plan the cleanup' },
|
||||
},
|
||||
{
|
||||
timestamp: '2026-10-30T00:00:02Z',
|
||||
type: 'response_item',
|
||||
payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: MESSAGE }] },
|
||||
},
|
||||
];
|
||||
writeFileSync(file, entries.map((e) => JSON.stringify(e)).join('\n') + '\n');
|
||||
utimesSync(file, 1_750_000_000, 1_750_000_000);
|
||||
const text = await lastText();
|
||||
expectWholeQuestions(text);
|
||||
});
|
||||
|
||||
for (const mode of ['opencode', 'gemini', 'antigravity', 'pi'] as const) {
|
||||
it(`${mode}: reads the whole message from the pane`, async () => {
|
||||
session.mode = mode;
|
||||
session.terminalBuffer = [
|
||||
'› plan the cleanup',
|
||||
'',
|
||||
'model · project · main · Ready · Context 100% left',
|
||||
'',
|
||||
'• Called write_file',
|
||||
'',
|
||||
MESSAGE,
|
||||
].join('\n');
|
||||
expectWholeQuestions(await lastText());
|
||||
});
|
||||
}
|
||||
|
||||
it('copilot: reads the whole message from the pane screen', async () => {
|
||||
session.mode = 'copilot';
|
||||
const screen = [
|
||||
' ❯ plan the cleanup 10:01',
|
||||
'',
|
||||
` ● ${INTRO}`,
|
||||
'',
|
||||
...QUESTIONS.map((q, i) => ` ${i + 1}. ${q}`),
|
||||
'',
|
||||
` ${OUTRO}`,
|
||||
'',
|
||||
' ~/project Session: 1 AIC used',
|
||||
'────────────────────────────────',
|
||||
' ❯ ',
|
||||
'────────────────────────────────',
|
||||
' ← open sidebar · / commands · ? help',
|
||||
].join('\n');
|
||||
harness.ctx.mux = { ...(harness.ctx.mux as object), capturePaneText: () => screen } as typeof harness.ctx.mux;
|
||||
expectWholeQuestions(await lastText());
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,354 @@
|
||||
/**
|
||||
* @fileoverview /api/discord: the bot token is a bearer secret, so it is never returned and the
|
||||
* settings routes are admin only in multi-user mode. Port: N/A (app.inject()).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdirSync, mkdtempSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { _resetNotifyBuckets, registerDiscordRoutes } from '../../src/web/routes/discord-routes.js';
|
||||
import { DiscordBridge, discordConfigPath, readDiscordConfig, type DiscordFetch } from '../../src/discord-bridge.js';
|
||||
|
||||
const TOKEN = 'MTA1.secret.token-value-1234567890';
|
||||
const FULL = {
|
||||
enabled: true,
|
||||
token: TOKEN,
|
||||
guildId: '111111111111111111',
|
||||
parentChannelId: '222222222222222222',
|
||||
allowedUserIds: ['333333333333333333'],
|
||||
};
|
||||
|
||||
let dir: string;
|
||||
let fetchImpl: ReturnType<typeof vi.fn<DiscordFetch>>;
|
||||
|
||||
async function harness(authUser?: { username: string; role: 'admin' | 'user' }) {
|
||||
const bridge = new DiscordBridge({
|
||||
configDir: dir,
|
||||
fetchImpl,
|
||||
sendInput: async () => true,
|
||||
socketFactory: () => ({ send() {}, close() {}, on() {} }),
|
||||
});
|
||||
const h = await createRouteTestHarness(
|
||||
(app, ctx) => registerDiscordRoutes(app, { bridge, configDir: dir, ctx, hostTitle: () => 'codeman:test' }),
|
||||
authUser ? { authUser } : undefined
|
||||
);
|
||||
return { ...h, bridge };
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
_resetNotifyBuckets();
|
||||
dir = mkdtempSync(join(tmpdir(), 'discord-routes-'));
|
||||
fetchImpl = vi.fn<DiscordFetch>(
|
||||
async () => new Response(JSON.stringify({ id: '444444444444444444' }), { status: 200 })
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('/api/discord', () => {
|
||||
it('starts disabled with no token', async () => {
|
||||
const { app } = await harness();
|
||||
const data = (await app.inject({ method: 'GET', url: '/api/discord' })).json().data;
|
||||
expect(data).toMatchObject({ enabled: false, hasToken: false, tokenMasked: '', gateway: 'off' });
|
||||
expect(data).not.toHaveProperty('token');
|
||||
});
|
||||
|
||||
it('saves, masks the token in every response and writes the file 0600', async () => {
|
||||
const { app, bridge } = await harness();
|
||||
const put = await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
expect(put.statusCode).toBe(200);
|
||||
expect(put.body).not.toContain('secret');
|
||||
expect(put.json().data).toMatchObject({ enabled: true, hasToken: true });
|
||||
const get = await app.inject({ method: 'GET', url: '/api/discord' });
|
||||
expect(get.body).not.toContain('secret');
|
||||
expect(statSync(discordConfigPath(dir)).mode & 0o777).toBe(0o600);
|
||||
expect((await readDiscordConfig(dir)).token).toBe(TOKEN);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('keeps the token when only an option changes, and clears it on an empty string', async () => {
|
||||
const { app, bridge } = await harness();
|
||||
await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/discord',
|
||||
payload: { pingMode: 'all', onSessionDelete: 'delete', staleThreads: 'archive' },
|
||||
});
|
||||
const cfg = await readDiscordConfig(dir);
|
||||
expect(cfg).toMatchObject({ token: TOKEN, pingMode: 'all', onSessionDelete: 'delete', staleThreads: 'archive' });
|
||||
const cleared = await app.inject({ method: 'PUT', url: '/api/discord', payload: { enabled: false, token: '' } });
|
||||
expect(cleared.json().data.hasToken).toBe(false);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('stores startupHint (default on) and returns it', async () => {
|
||||
const { app, bridge } = await harness();
|
||||
const first = (await app.inject({ method: 'GET', url: '/api/discord' })).json().data;
|
||||
expect(first).toMatchObject({ startupHint: true });
|
||||
const put = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/discord',
|
||||
payload: { startupHint: false },
|
||||
});
|
||||
expect(put.json().data).toMatchObject({ startupHint: false });
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('refuses a bad id, an incomplete enable, and unknown fields', async () => {
|
||||
const { app } = await harness();
|
||||
const bad = await app.inject({ method: 'PUT', url: '/api/discord', payload: { guildId: 'not-a-number' } });
|
||||
expect(bad.statusCode).toBe(400);
|
||||
const incomplete = await app.inject({ method: 'PUT', url: '/api/discord', payload: { enabled: true } });
|
||||
expect(incomplete.statusCode).toBe(400);
|
||||
const extra = await app.inject({ method: 'PUT', url: '/api/discord', payload: { nope: 1 } });
|
||||
expect(extra.statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('POST /test needs a saved token, then posts to the parent channel', async () => {
|
||||
const { app, bridge } = await harness();
|
||||
expect((await app.inject({ method: 'POST', url: '/api/discord/test' })).statusCode).toBe(400);
|
||||
await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
const res = await app.inject({ method: 'POST', url: '/api/discord/test' });
|
||||
expect(res.json().data.ok).toBe(true);
|
||||
expect(String(fetchImpl.mock.calls.at(-1)![0])).toContain('/channels/222222222222222222/messages');
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('is admin only in multi-user mode', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await harness({ username: 'bob', role: 'user' });
|
||||
expect((await app.inject({ method: 'GET', url: '/api/discord' })).statusCode).toBe(403);
|
||||
expect((await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL })).statusCode).toBe(403);
|
||||
expect((await app.inject({ method: 'POST', url: '/api/discord/test' })).statusCode).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/sessions/:id/discord-notify', () => {
|
||||
const url = '/api/sessions/test-session-1/discord-notify';
|
||||
it('is refused while the bridge is off, and posts into the session thread once on', async () => {
|
||||
const { app, bridge } = await harness();
|
||||
const url = `/api/sessions/test-session-1/discord-notify`;
|
||||
const off = await app.inject({ method: 'POST', url, payload: { message: 'press reset' } });
|
||||
expect(off.statusCode).toBe(409);
|
||||
await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
const on = await app.inject({ method: 'POST', url, payload: { message: 'press reset', urgent: true } });
|
||||
expect(on.json().data.ok).toBe(true);
|
||||
const sent = fetchImpl.mock.calls.map((c) => String(c[1].body));
|
||||
expect(sent.some((b) => b.includes('press reset') && b.includes('<@333333333333333333>'))).toBe(true);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('accepts a unique 8-character session id prefix (Docker exports it cut), not an ambiguous or short one', async () => {
|
||||
const { app, bridge, ctx } = await harness();
|
||||
await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
const ok = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-ses/discord-notify',
|
||||
payload: { message: 'hi' },
|
||||
});
|
||||
expect(ok.statusCode).toBe(200);
|
||||
ctx.sessions.set('test-session-2', ctx.sessions.get('test-session-1')!);
|
||||
const ambiguous = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-ses/discord-notify',
|
||||
payload: { message: 'hi' },
|
||||
});
|
||||
expect(ambiguous.statusCode).toBe(404);
|
||||
const short = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test/discord-notify',
|
||||
payload: { message: 'hi' },
|
||||
});
|
||||
expect(short.statusCode).toBe(404);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it("does not reveal another user's session through its id prefix (multi-user)", async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app, bridge, ctx } = await harness({ username: 'bob', role: 'user' });
|
||||
(ctx.sessions.get('test-session-1') as unknown as { owner: string }).owner = 'alice';
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-ses/discord-notify',
|
||||
payload: { message: 'hi' },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(res.json().error).not.toContain('test-session-1');
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('lets two different deliberate messages from one tab through within 3 s (neither is lost)', async () => {
|
||||
const { app, bridge } = await harness();
|
||||
await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
const first = await app.inject({ method: 'POST', url, payload: { message: 'first thing' } });
|
||||
const second = await app.inject({ method: 'POST', url, payload: { message: 'second thing' } });
|
||||
expect(first.statusCode).toBe(200);
|
||||
expect(second.statusCode).toBe(200);
|
||||
expect(second.json().data.deduped).toBeUndefined();
|
||||
const sent = fetchImpl.mock.calls.map((c) => String(c[1].body));
|
||||
expect(sent.filter((b) => b.includes('first thing') || b.includes('second thing'))).toHaveLength(2);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('answers 200 with data.ok false when Discord refuses the post, which the CLI turns into exit 1', async () => {
|
||||
const { app, bridge } = await harness();
|
||||
await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
fetchImpl.mockImplementation(async () => new Response(JSON.stringify({ code: 0 }), { status: 401 }));
|
||||
const res = await app.inject({ method: 'POST', url, payload: { message: 'help' } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data).toMatchObject({ ok: false, status: 401 });
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('answers 429 RATE_LIMITED once a tab posts more than its share in a minute', async () => {
|
||||
const { app, bridge } = await harness();
|
||||
await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
const codes: number[] = [];
|
||||
for (let i = 0; i < 8; i++) {
|
||||
codes.push(
|
||||
(await app.inject({ method: 'POST', url, payload: { message: `ping ${i}`, urgent: true } })).statusCode
|
||||
);
|
||||
}
|
||||
expect(codes.slice(0, 6)).toEqual([200, 200, 200, 200, 200, 200]);
|
||||
expect(codes.slice(6)).toEqual([429, 429]);
|
||||
const limited = await app.inject({ method: 'POST', url, payload: { message: 'again' } });
|
||||
expect(limited.json().errorCode).toBe('RATE_LIMITED');
|
||||
expect(limited.headers['retry-after']).toBe('60');
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('does not spend rate-limit tokens on a request refused for its file', async () => {
|
||||
const { app, bridge } = await harness();
|
||||
await app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
for (let i = 0; i < 8; i++) {
|
||||
const bad = await app.inject({ method: 'POST', url, payload: { message: 'x', file: 'no-such-file.txt' } });
|
||||
expect(bad.statusCode).toBe(400);
|
||||
}
|
||||
expect((await app.inject({ method: 'POST', url, payload: { message: 'still allowed' } })).statusCode).toBe(200);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('rejects an empty or oversized message', async () => {
|
||||
const { app } = await harness();
|
||||
const url = `/api/sessions/test-session-1/discord-notify`;
|
||||
expect((await app.inject({ method: 'POST', url, payload: { message: '' } })).statusCode).toBe(400);
|
||||
expect((await app.inject({ method: 'POST', url, payload: { message: 'x'.repeat(2000) } })).statusCode).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('discord-notify with a file', () => {
|
||||
let work: string;
|
||||
let outside: string;
|
||||
const url = '/api/sessions/test-session-1/discord-notify';
|
||||
|
||||
async function ready() {
|
||||
const h = await harness();
|
||||
(h.ctx.sessions.get('test-session-1') as unknown as { workingDir: string }).workingDir = work;
|
||||
await h.app.inject({ method: 'PUT', url: '/api/discord', payload: FULL });
|
||||
return h;
|
||||
}
|
||||
const post = (app: Awaited<ReturnType<typeof harness>>['app'], file: string) =>
|
||||
app.inject({ method: 'POST', url, payload: { message: 'log attached', file } });
|
||||
|
||||
beforeEach(() => {
|
||||
work = mkdtempSync(join(tmpdir(), 'discord-work-'));
|
||||
outside = mkdtempSync(join(tmpdir(), 'discord-outside-'));
|
||||
writeFileSync(join(work, 'run.log'), 'hello');
|
||||
writeFileSync(join(outside, 'secret.txt'), 'nope');
|
||||
});
|
||||
afterEach(() => {
|
||||
rmSync(work, { recursive: true, force: true });
|
||||
rmSync(outside, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('uploads a file inside the session folder as multipart', async () => {
|
||||
const { app, bridge } = await ready();
|
||||
const res = await post(app, join(work, 'run.log'));
|
||||
expect(res.json().data.ok).toBe(true);
|
||||
const form = fetchImpl.mock.calls.map((c) => c[1].body).find((b) => b instanceof FormData) as FormData;
|
||||
expect((form.get('files[0]') as File).name).toBe('run.log');
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a relative path', () => 'run.log'],
|
||||
['a file outside the folder', () => join(outside, 'secret.txt')],
|
||||
['the folder itself', () => work],
|
||||
['a missing file', () => join(work, 'nope.log')],
|
||||
])('refuses %s', async (_n, path) => {
|
||||
const { app, bridge } = await ready();
|
||||
const res = await post(app, path());
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(fetchImpl.mock.calls.some((c) => c[1].body instanceof FormData)).toBe(false);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a .env file', () => ['.env', 'TOKEN=x']],
|
||||
['a private key under .ssh', () => ['.ssh/id_ed25519', 'key']],
|
||||
['Codeman state with the bot token', () => ['.codeman/discord.json', '{}']],
|
||||
])('refuses %s even inside the session folder, as with a home directory', async (_n, entry) => {
|
||||
const [rel, body] = entry();
|
||||
mkdirSync(dirname(join(work, rel)), { recursive: true });
|
||||
writeFileSync(join(work, rel), body);
|
||||
const { app, bridge } = await ready();
|
||||
const res = await post(app, join(work, rel));
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/credentials/);
|
||||
expect(fetchImpl.mock.calls.some((c) => c[1].body instanceof FormData)).toBe(false);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('refuses a symlink inside the folder that points at a blocked file', async () => {
|
||||
writeFileSync(join(work, '.env'), 'TOKEN=x');
|
||||
symlinkSync(join(work, '.env'), join(work, 'notes.txt'));
|
||||
const { app, bridge } = await ready();
|
||||
const res = await post(app, join(work, 'notes.txt'));
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(fetchImpl.mock.calls.some((c) => c[1].body instanceof FormData)).toBe(false);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('refuses to send when the session folder is not a directory it can probe', async () => {
|
||||
const { app, ctx, bridge } = await ready();
|
||||
(ctx.sessions.get('test-session-1') as unknown as { workingDir: string }).workingDir = join(work, 'run.log');
|
||||
const res = await post(app, join(work, 'run.log'));
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/session folder/);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('probes the file before realpath: a path that is not a regular file is refused', async () => {
|
||||
const { app, bridge } = await ready();
|
||||
mkdirSync(join(work, 'dir'));
|
||||
expect((await post(app, join(work, 'dir'))).json().error).toMatch(/Not a regular file/);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('refuses a symlink that points outside the folder', async () => {
|
||||
const { app, bridge } = await ready();
|
||||
mkdirSync(join(work, 'sub'));
|
||||
symlinkSync(join(outside, 'secret.txt'), join(work, 'sub', 'link.txt'));
|
||||
expect((await post(app, join(work, 'sub', 'link.txt'))).statusCode).toBe(400);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('refuses a file over 8 MB', async () => {
|
||||
const { app, bridge } = await ready();
|
||||
writeFileSync(join(work, 'big.bin'), Buffer.alloc(8 * 1024 * 1024 + 1));
|
||||
const res = await post(app, join(work, 'big.bin'));
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/8 MB/);
|
||||
bridge.stop();
|
||||
});
|
||||
|
||||
it('refuses a file for a remote session', async () => {
|
||||
const { app, bridge, ctx } = await ready();
|
||||
(ctx.sessions.get('test-session-1') as unknown as { remote: object }).remote = { label: 'box' };
|
||||
expect((await post(app, join(work, 'run.log'))).statusCode).toBe(400);
|
||||
bridge.stop();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,293 @@
|
||||
/**
|
||||
* @fileoverview The edit history panel's API (GET/POST /api/sessions/:id/edits…): a real
|
||||
* EditHistorySync and store over a fake transcript reader. Port: N/A (app.inject()).
|
||||
*/
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { hunksToUnified, registerEditHistoryRoutes, relativeTo } from '../../src/web/routes/edit-history-routes.js';
|
||||
import { EditHistorySync, NO_TRANSCRIPT, type EditHistorySyncDeps } from '../../src/web/edit-history-sync.js';
|
||||
import { EditHistoryStore } from '../../src/edit-history-store.js';
|
||||
import type { EditSources } from '../../src/edit-history-local-source.js';
|
||||
|
||||
const T0 = Date.parse('2026-10-15T20:00:00.000Z');
|
||||
let dir: string;
|
||||
let session: Record<string, unknown>;
|
||||
|
||||
function editLine(id: string, ts: number, path: string, extra: Record<string, unknown> = {}): string {
|
||||
return (
|
||||
JSON.stringify({
|
||||
type: 'user',
|
||||
timestamp: new Date(ts).toISOString(),
|
||||
cwd: '/w',
|
||||
message: { role: 'user', content: [{ tool_use_id: id, type: 'tool_result', content: 'ok' }] },
|
||||
toolUseResult: {
|
||||
filePath: path,
|
||||
oldString: 'a',
|
||||
newString: 'b',
|
||||
structuredPatch: [{ oldStart: 4, oldLines: 1, newStart: 4, newLines: 2, lines: ['-a', '+b', '+c'] }],
|
||||
},
|
||||
...extra,
|
||||
}) + '\n'
|
||||
);
|
||||
}
|
||||
|
||||
function sources(main: string, sub?: string): EditSources {
|
||||
const files = [{ relPath: 'main', size: Buffer.byteLength(main), startOffset: 0, chunk: Buffer.from(main) }];
|
||||
const metas: Record<string, string> = {};
|
||||
if (sub) {
|
||||
files.push({
|
||||
relPath: 'subagents/agent-a1.jsonl',
|
||||
size: Buffer.byteLength(sub),
|
||||
startOffset: 0,
|
||||
chunk: Buffer.from(sub),
|
||||
});
|
||||
metas.a1 = JSON.stringify({
|
||||
description: 'Fix it',
|
||||
agentType: 'coding',
|
||||
worktreePath: '/w/.claude/worktrees/agent-a1',
|
||||
worktreeBranch: 'worktree-agent-a1',
|
||||
});
|
||||
}
|
||||
return { transcriptId: 'conv1', files, metas };
|
||||
}
|
||||
|
||||
async function setup(
|
||||
deps: Partial<EditHistorySyncDeps> = {},
|
||||
opts: { authUser?: { username: string; role: 'admin' | 'user' } } = {}
|
||||
) {
|
||||
const read = vi.fn(async () => sources(editLine('t1', T0, '/w/src/a.ts')));
|
||||
const sync = new EditHistorySync({
|
||||
transcriptPath: async () => '/p/conv1.jsonl',
|
||||
readSources: read,
|
||||
probe: async (_session, p) => p.map(() => null),
|
||||
loadStore: async (id) => {
|
||||
const store = await EditHistoryStore.load(id, { dir, debounceMs: 0 });
|
||||
opened.push(store);
|
||||
return store;
|
||||
},
|
||||
deleteStore: (id) => EditHistoryStore.delete(id, { dir }),
|
||||
sweepStores: async () => 0,
|
||||
...deps,
|
||||
});
|
||||
const h = await createRouteTestHarness((app, ctx) => registerEditHistoryRoutes(app, ctx, sync), {
|
||||
authUser: opts.authUser,
|
||||
});
|
||||
session = h.ctx._session as unknown as Record<string, unknown>;
|
||||
session.workingDir = '/w';
|
||||
session.mode = 'claude';
|
||||
session.claudeSessionId = 'conv1';
|
||||
return { ...h, read, sync };
|
||||
}
|
||||
|
||||
/** Stores the tests opened; removed before the temp dir, so no late save recreates it. */
|
||||
const opened: EditHistoryStore[] = [];
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'edit-routes-'));
|
||||
});
|
||||
afterEach(async () => {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
await Promise.all(opened.splice(0).map((s) => s.remove()));
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const URL = '/api/sessions/test-session-1/edits';
|
||||
|
||||
describe('GET /api/sessions/:id/edits', () => {
|
||||
it('syncs on ?sync=1 and lists entries without diffs, paths relative to the workspace', async () => {
|
||||
const { app } = await setup();
|
||||
const res = await app.inject({ method: 'GET', url: `${URL}?sync=1` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = res.json().data;
|
||||
expect(data).toMatchObject({ state: 'ok', backfillTruncated: false, agents: {} });
|
||||
expect(data.entries).toEqual([
|
||||
expect.objectContaining({
|
||||
id: 't1',
|
||||
path: '/w/src/a.ts',
|
||||
relPath: 'src/a.ts',
|
||||
tool: 'Edit',
|
||||
added: 2,
|
||||
removed: 1,
|
||||
}),
|
||||
]);
|
||||
expect(data.entries[0]).not.toHaveProperty('hunks');
|
||||
});
|
||||
|
||||
it('starts the sync before it loads the store (a deletion right after the session check stops the sync)', async () => {
|
||||
const { app, sync } = await setup();
|
||||
const calls: string[] = [];
|
||||
const syncFn = sync.sync.bind(sync);
|
||||
const getStore = sync.getStore.bind(sync);
|
||||
vi.spyOn(sync, 'sync').mockImplementation((...a) => (calls.push('sync'), syncFn(...a)));
|
||||
vi.spyOn(sync, 'getStore').mockImplementation((...a) => (calls.push('getStore'), getStore(...a)));
|
||||
await app.inject({ method: 'GET', url: `${URL}?sync=1` });
|
||||
await app.inject({ method: 'POST', url: `${URL}/older` });
|
||||
expect(calls).toEqual(['sync', 'getStore', 'sync', 'getStore']);
|
||||
});
|
||||
|
||||
it('without sync=1 answers from the store and does not read', async () => {
|
||||
const { app, read } = await setup();
|
||||
const res = await app.inject({ method: 'GET', url: URL });
|
||||
expect(res.json().data).toMatchObject({ state: 'ok', entries: [] });
|
||||
expect(read).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('labels subagent entries and shows their paths relative to the worktree', async () => {
|
||||
const sub = editLine('t9', T0 + 5, '/w/.claude/worktrees/agent-a1/lib/x.ts', { isSidechain: true, agentId: 'a1' });
|
||||
const read = vi.fn(async () => sources(editLine('t1', T0, '/w/src/a.ts'), sub));
|
||||
const { app } = await setup({ readSources: read });
|
||||
const data = (await app.inject({ method: 'GET', url: `${URL}?sync=1` })).json().data;
|
||||
expect(data.agents).toEqual({
|
||||
a1: { description: 'Fix it', agentType: 'coding', worktreeBranch: 'worktree-agent-a1' },
|
||||
});
|
||||
expect(data.entries.find((e: { id: string }) => e.id === 't9')).toMatchObject({
|
||||
agentId: 'a1',
|
||||
relPath: 'lib/x.ts',
|
||||
});
|
||||
});
|
||||
|
||||
it('a read error answers unavailable with the stored entries', async () => {
|
||||
let fail = false;
|
||||
const read = vi.fn(async () => {
|
||||
if (fail) throw new Error('EACCES: permission denied');
|
||||
return sources(editLine('t1', T0, '/w/src/a.ts'));
|
||||
});
|
||||
const { app } = await setup({ readSources: read });
|
||||
await app.inject({ method: 'GET', url: `${URL}?sync=1` });
|
||||
fail = true;
|
||||
const data = (await app.inject({ method: 'GET', url: `${URL}?sync=1` })).json().data;
|
||||
expect(data).toMatchObject({ state: 'unavailable', reason: 'EACCES: permission denied' });
|
||||
expect(data.entries).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('hands the reader the session ids and its own CLAUDE_CONFIG_DIR', async () => {
|
||||
const seen: unknown[] = [];
|
||||
const { app } = await setup({
|
||||
transcriptPath: async (s) => {
|
||||
seen.push({ id: s.id, claudeSessionId: s.claudeSessionId, claudeConfigDir: s.claudeConfigDir });
|
||||
return '/p/conv1.jsonl';
|
||||
},
|
||||
});
|
||||
session.claudeConfigDirOverride = '/cfg/alt ';
|
||||
await app.inject({ method: 'GET', url: `${URL}?sync=1` });
|
||||
expect(seen).toEqual([{ id: 'test-session-1', claudeSessionId: 'conv1', claudeConfigDir: '/cfg/alt' }]);
|
||||
});
|
||||
|
||||
it('a session without a transcript yet answers unavailable (no-transcript)', async () => {
|
||||
const { app, read } = await setup({ transcriptPath: async () => null });
|
||||
const data = (await app.inject({ method: 'GET', url: `${URL}?sync=1` })).json().data;
|
||||
expect(data).toMatchObject({ state: 'unavailable', reason: NO_TRANSCRIPT, entries: [] });
|
||||
expect(read).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['docker', { docker: { image: 'x' } }],
|
||||
['mode', { mode: 'shell' }],
|
||||
])('answers unsupported (%s) without reading or loading a store', async (reason, patch) => {
|
||||
const loadStore = vi.fn(async (id: string) => EditHistoryStore.load(id, { dir, debounceMs: 0 }));
|
||||
const { app, read } = await setup({ loadStore });
|
||||
Object.assign(session, patch);
|
||||
const empty = { state: 'unsupported', reason, backfillTruncated: false, agents: {}, entries: [] };
|
||||
for (const url of [URL, `${URL}?sync=1`]) {
|
||||
expect((await app.inject({ method: 'GET', url })).json().data).toEqual(empty);
|
||||
}
|
||||
expect((await app.inject({ method: 'POST', url: `${URL}/older` })).json().data).toEqual(empty);
|
||||
expect((await app.inject({ method: 'GET', url: `${URL}/t1` })).statusCode).toBe(404);
|
||||
expect(read).not.toHaveBeenCalled();
|
||||
expect(loadStore).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('404s an unknown session', async () => {
|
||||
const { app } = await setup();
|
||||
expect((await app.inject({ method: 'GET', url: '/api/sessions/nope/edits' })).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('multi-user: another user’s session is not found and nothing is read', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app, read } = await setup({}, { authUser: { username: 'bob', role: 'user' } });
|
||||
session.owner = 'alice';
|
||||
const res = await app.inject({ method: 'GET', url: `${URL}?sync=1` });
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(read).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/sessions/:id/edits/:entryId', () => {
|
||||
it('returns the diff as unified text', async () => {
|
||||
const { app } = await setup();
|
||||
await app.inject({ method: 'GET', url: `${URL}?sync=1` });
|
||||
const res = await app.inject({ method: 'GET', url: `${URL}/t1` });
|
||||
expect(res.json().data).toEqual({ diff: '@@ -4,1 +4,2 @@\n-a\n+b\n+c', truncated: false });
|
||||
});
|
||||
|
||||
it('404s an edit the session does not have', async () => {
|
||||
const { app } = await setup();
|
||||
expect((await app.inject({ method: 'GET', url: `${URL}/missing` })).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('multi-user: another user’s diff is not found', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await setup({}, { authUser: { username: 'bob', role: 'user' } });
|
||||
await app.inject({ method: 'GET', url: `${URL}?sync=1` });
|
||||
session.owner = 'alice';
|
||||
expect((await app.inject({ method: 'GET', url: `${URL}/t1` })).statusCode).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/sessions/:id/edits/older', () => {
|
||||
it('reads the next older block and lists the result', async () => {
|
||||
const lines = [0, 1, 2, 3].map((i) => editLine(`t${i}`, T0 + i, `/w/${i}.ts`)).join('');
|
||||
const full = Buffer.from(lines);
|
||||
const read = vi.fn(
|
||||
async (
|
||||
_session: unknown,
|
||||
_path: string,
|
||||
requests: readonly { relPath: string; offset: number; len?: number }[],
|
||||
budget: number
|
||||
) => {
|
||||
const req = requests.find((r) => r.relPath === 'main');
|
||||
const start = req ? req.offset : full.length - budget;
|
||||
const len = req?.len ?? full.length - start;
|
||||
return {
|
||||
transcriptId: 'conv1',
|
||||
metas: {},
|
||||
files: [{ relPath: 'main', size: full.length, startOffset: start, chunk: full.subarray(start, start + len) }],
|
||||
};
|
||||
}
|
||||
);
|
||||
const { app } = await setup({ readSources: read, budget: 400 });
|
||||
const first = (await app.inject({ method: 'GET', url: `${URL}?sync=1` })).json().data;
|
||||
expect(first.backfillTruncated).toBe(true);
|
||||
const older = (await app.inject({ method: 'POST', url: `${URL}/older` })).json().data;
|
||||
expect(older.entries.length).toBeGreaterThan(first.entries.length);
|
||||
});
|
||||
|
||||
it('reads a remote session, handing the reader that session', async () => {
|
||||
const { app, read } = await setup();
|
||||
session.remote = { host: 'huff' };
|
||||
const data = (await app.inject({ method: 'GET', url: `${URL}?sync=1` })).json().data;
|
||||
expect(data).toMatchObject({ state: 'ok', entries: [{ path: '/w/src/a.ts' }] });
|
||||
expect(read).toHaveBeenCalledTimes(1);
|
||||
expect((read.mock.calls[0] as unknown[])[0]).toMatchObject({ id: session.id, remote: { host: 'huff' } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('helpers', () => {
|
||||
it('relativeTo strips only a real directory prefix', () => {
|
||||
expect(relativeTo('/w/a/b.ts', '/w')).toBe('a/b.ts');
|
||||
expect(relativeTo('/w/a/b.ts', '/w/')).toBe('a/b.ts');
|
||||
expect(relativeTo('/wx/b.ts', '/w')).toBe('/wx/b.ts');
|
||||
expect(relativeTo('/w/b.ts', undefined)).toBe('/w/b.ts');
|
||||
});
|
||||
|
||||
it('hunksToUnified writes one header per hunk', () => {
|
||||
expect(
|
||||
hunksToUnified([
|
||||
{ oldStart: 1, oldLines: 1, newStart: 1, newLines: 1, lines: ['-x', '+y'] },
|
||||
{ oldStart: 9, oldLines: 0, newStart: 9, newLines: 1, lines: ['+z'] },
|
||||
])
|
||||
).toBe('@@ -1,1 +1,1 @@\n-x\n+y\n@@ -9,0 +9,1 @@\n+z');
|
||||
});
|
||||
});
|
||||
@@ -99,11 +99,30 @@ describe('clampExternalCliBypassForOwner — multi-user mode', () => {
|
||||
undefined,
|
||||
{ alwaysApprove: true, model: 'grok-4.5' }
|
||||
);
|
||||
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: false, model: 'gpt-5' });
|
||||
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: false, networkAccess: false, model: 'gpt-5' });
|
||||
expect(out.antigravityConfig).toEqual({ dangerouslySkipPermissions: false, model: 'gemini-3-pro' });
|
||||
expect(out.grokConfig).toEqual({ alwaysApprove: false, model: 'grok-4.5' });
|
||||
});
|
||||
|
||||
it("forces a non-granted owner's copilot --yolo off and keeps the model", async () => {
|
||||
const out = await _clampExternalCliBypassForOwner(
|
||||
'peon',
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ allowAll: true, model: 'claude-sonnet-5.5' }
|
||||
);
|
||||
expect(out.copilotConfig).toEqual({ allowAll: false, model: 'claude-sonnet-5.5' });
|
||||
});
|
||||
|
||||
it('leaves copilot absent when nothing was sent (a bare copilot is already Manual Approval)', async () => {
|
||||
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined, undefined);
|
||||
expect(out.copilotConfig).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps a non-granted owner's codex reasoning effort while forcing bypass off", async () => {
|
||||
// The clamp rewrites one field and must carry the rest; a clamp rebuilt from named
|
||||
// fields would drop the effort here without a word.
|
||||
@@ -115,7 +134,26 @@ describe('clampExternalCliBypassForOwner — multi-user mode', () => {
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: false, reasoningEffort: 'xhigh' });
|
||||
expect(out.codexConfig).toEqual({
|
||||
dangerouslyBypassApprovals: false,
|
||||
networkAccess: false,
|
||||
reasoningEffort: 'xhigh',
|
||||
});
|
||||
});
|
||||
|
||||
it("forces a non-granted owner's codex network access off, as when the launch default filled it", async () => {
|
||||
// applyLaunchDefaults runs BEFORE this clamp, so App Settings → Allow network access
|
||||
// arrives here as an ordinary `networkAccess: true` in a sent config. It widens the
|
||||
// sandbox to every host, so a non-granted owner must not get it.
|
||||
const out = await _clampExternalCliBypassForOwner(
|
||||
'peon',
|
||||
{ networkAccess: true },
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: false, networkAccess: false });
|
||||
});
|
||||
|
||||
it('leaves codex/antigravity/grok absent when nothing was sent (they already spawn safe)', async () => {
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
/**
|
||||
* @fileoverview `DELETE /api/sessions/:id/files?path=`, the Files panel's delete button (salvaged
|
||||
* from #529).
|
||||
*
|
||||
* Real temp workspace, no fs mock, like test/routes/file-write-routes.test.ts: the thing under
|
||||
* test is what the route does to real files, and the defect it fixes (a delete of
|
||||
* `AGENTS.md -> CLAUDE.md` removed CLAUDE.md, because the confinement check hands back the
|
||||
* realpath) only shows against a real symlink. Each refusal also checks that nothing on disk moved.
|
||||
*
|
||||
* Uses app.inject() — no real HTTP ports needed.
|
||||
* Port: N/A (app.inject doesn't open ports)
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
realpathSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
|
||||
describe('DELETE /api/sessions/:id/files (real fs)', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let base: string;
|
||||
let workDir: string;
|
||||
let outsideDir: string;
|
||||
|
||||
const del = (path: string, h: RouteTestHarness = harness) =>
|
||||
h.app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/sessions/${h.ctx._sessionId}/files?path=${encodeURIComponent(path)}`,
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerFileRoutes);
|
||||
// realpath: tmpdir() can hold a symlinked component (macOS /tmp), and the fixtures compare paths.
|
||||
base = realpathSync(mkdtempSync(join(tmpdir(), 'codeman-delete-')));
|
||||
workDir = join(base, 'ws');
|
||||
outsideDir = join(base, 'outside');
|
||||
mkdirSync(workDir);
|
||||
mkdirSync(outsideDir);
|
||||
harness.ctx._session.workingDir = workDir;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
rmSync(base, { recursive: true, force: true });
|
||||
rmSync(SETTINGS_PATH, { force: true });
|
||||
});
|
||||
|
||||
it('deletes a regular file and answers the path it was given', async () => {
|
||||
mkdirSync(join(workDir, 'src'));
|
||||
writeFileSync(join(workDir, 'src', 'old.ts'), 'x');
|
||||
writeFileSync(join(workDir, 'keep.ts'), 'y');
|
||||
|
||||
const res = await del('src/old.ts');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ success: true, data: { path: 'src/old.ts' } });
|
||||
expect(existsSync(join(workDir, 'src', 'old.ts'))).toBe(false);
|
||||
expect(existsSync(join(workDir, 'src'))).toBe(true);
|
||||
expect(readFileSync(join(workDir, 'keep.ts'), 'utf8')).toBe('y');
|
||||
});
|
||||
|
||||
it('deletes a file whose name carries quotes and other characters a shell or a URL cares about', async () => {
|
||||
const name = "x'-alert(1)-' & #?.txt";
|
||||
writeFileSync(join(workDir, name), 'x');
|
||||
|
||||
const res = await del(name);
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(existsSync(join(workDir, name))).toBe(false);
|
||||
});
|
||||
|
||||
describe('symbolic links are refused, never followed', () => {
|
||||
it('leaves both the link and its target when asked to delete AGENTS.md -> CLAUDE.md', async () => {
|
||||
writeFileSync(join(workDir, 'CLAUDE.md'), '# rules');
|
||||
symlinkSync('CLAUDE.md', join(workDir, 'AGENTS.md'));
|
||||
|
||||
const res = await del('AGENTS.md');
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().error).toMatch(/symbolic link/i);
|
||||
expect(readFileSync(join(workDir, 'CLAUDE.md'), 'utf8')).toBe('# rules');
|
||||
expect(lstatSync(join(workDir, 'AGENTS.md')).isSymbolicLink()).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses a link to a folder, which the listing shows as a file row', async () => {
|
||||
mkdirSync(join(workDir, 'real'));
|
||||
writeFileSync(join(workDir, 'real', 'a.txt'), 'a');
|
||||
symlinkSync('real', join(workDir, 'alias'));
|
||||
|
||||
const res = await del('alias');
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(readFileSync(join(workDir, 'real', 'a.txt'), 'utf8')).toBe('a');
|
||||
expect(lstatSync(join(workDir, 'alias')).isSymbolicLink()).toBe(true);
|
||||
});
|
||||
|
||||
it('answers 404 for a link that leads out of the workspace, and leaves its target', async () => {
|
||||
writeFileSync(join(outsideDir, 'secret.txt'), 'secret');
|
||||
symlinkSync(join(outsideDir, 'secret.txt'), join(workDir, 'leak.txt'));
|
||||
|
||||
const res = await del('leak.txt');
|
||||
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(readFileSync(join(outsideDir, 'secret.txt'), 'utf8')).toBe('secret');
|
||||
});
|
||||
|
||||
it('deletes a plain file reached through a linked folder inside the workspace', async () => {
|
||||
mkdirSync(join(workDir, 'real'));
|
||||
writeFileSync(join(workDir, 'real', 'b.txt'), 'b');
|
||||
symlinkSync('real', join(workDir, 'alias'));
|
||||
|
||||
const res = await del('alias/b.txt');
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(existsSync(join(workDir, 'real', 'b.txt'))).toBe(false);
|
||||
expect(lstatSync(join(workDir, 'alias')).isSymbolicLink()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a file under .git with 403, also when .git is reached through a linked folder', async () => {
|
||||
mkdirSync(join(workDir, '.git'));
|
||||
writeFileSync(join(workDir, '.git', 'config'), '[core]');
|
||||
symlinkSync('.git', join(workDir, 'gitdir'));
|
||||
|
||||
for (const path of ['.git/config', 'gitdir/config']) {
|
||||
const res = await del(path);
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.json().success).toBe(false);
|
||||
}
|
||||
expect(readFileSync(join(workDir, '.git', 'config'), 'utf8')).toBe('[core]');
|
||||
});
|
||||
|
||||
it('refuses a sensitive file with 403', async () => {
|
||||
writeFileSync(join(workDir, '.env'), 'TOKEN=abc');
|
||||
|
||||
const res = await del('.env');
|
||||
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(readFileSync(join(workDir, '.env'), 'utf8')).toBe('TOKEN=abc');
|
||||
});
|
||||
|
||||
it('answers 404 for a path that climbs out of the workspace', async () => {
|
||||
writeFileSync(join(outsideDir, 'victim.txt'), 'v');
|
||||
|
||||
for (const path of ['../outside/victim.txt', join(outsideDir, 'victim.txt')]) {
|
||||
const res = await del(path);
|
||||
expect(res.statusCode).toBe(404);
|
||||
}
|
||||
expect(readFileSync(join(outsideDir, 'victim.txt'), 'utf8')).toBe('v');
|
||||
});
|
||||
|
||||
it('answers 404 for a file that does not exist', async () => {
|
||||
expect((await del('nope.txt')).statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('refuses a directory with 400', async () => {
|
||||
mkdirSync(join(workDir, 'src'));
|
||||
writeFileSync(join(workDir, 'src', 'a.ts'), 'a');
|
||||
|
||||
const res = await del('src');
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(readFileSync(join(workDir, 'src', 'a.ts'), 'utf8')).toBe('a');
|
||||
});
|
||||
|
||||
it('refuses a missing or repeated path parameter with 400', async () => {
|
||||
const missing = await harness.app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/files`,
|
||||
});
|
||||
expect(missing.statusCode).toBe(400);
|
||||
writeFileSync(join(workDir, 'a.txt'), 'a');
|
||||
const repeated = await harness.app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/files?path=a.txt&path=a.txt`,
|
||||
});
|
||||
expect(repeated.statusCode).toBe(400);
|
||||
expect(existsSync(join(workDir, 'a.txt'))).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses a remote (SSH) session before looking at the local twin of its folder', async () => {
|
||||
// The local folder of the same absolute name is exactly the hazard: validation would resolve
|
||||
// against it and the delete would land here while the user meant the remote file.
|
||||
writeFileSync(join(workDir, 'twin.txt'), 'local');
|
||||
harness.ctx._session.remote = {
|
||||
hostId: 'host-1',
|
||||
label: 'testhost',
|
||||
host: '192.0.2.10',
|
||||
username: 'j',
|
||||
remotePath: workDir,
|
||||
};
|
||||
|
||||
const res = await del('twin.txt');
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/remote/i);
|
||||
expect(readFileSync(join(workDir, 'twin.txt'), 'utf8')).toBe('local');
|
||||
});
|
||||
|
||||
it('refuses an adopted session, whose folder is not a workspace of ours', async () => {
|
||||
writeFileSync(join(workDir, 'shared.txt'), 'tmp');
|
||||
harness.ctx._session.isAdopted = true;
|
||||
|
||||
const res = await del('shared.txt');
|
||||
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/adopted/i);
|
||||
expect(readFileSync(join(workDir, 'shared.txt'), 'utf8')).toBe('tmp');
|
||||
});
|
||||
|
||||
describe('a worktree outside the session folder', () => {
|
||||
let sibling: string;
|
||||
|
||||
beforeEach(() => {
|
||||
sibling = join(base, 'ws-feature');
|
||||
mkdirSync(join(sibling, 'src'), { recursive: true });
|
||||
writeFileSync(join(sibling, 'src', 'feature.ts'), 'feature');
|
||||
Object.assign(harness.ctx._session, {
|
||||
liveWorktree: { name: 'ws-feature', path: sibling, outside: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('deletes an absolute path inside it, as the other file routes serve it', async () => {
|
||||
const res = await del(join(sibling, 'src', 'feature.ts'));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(existsSync(join(sibling, 'src', 'feature.ts'))).toBe(false);
|
||||
});
|
||||
|
||||
it('does not reach it with a relative path, which resolves against the session folder only', async () => {
|
||||
const res = await del('../ws-feature/src/feature.ts');
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(existsSync(join(sibling, 'src', 'feature.ts'))).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses a symlink in it that leads out of it, and leaves the target', async () => {
|
||||
writeFileSync(join(outsideDir, 'key.txt'), 'secret');
|
||||
symlinkSync(join(outsideDir, 'key.txt'), join(sibling, 'leak.txt'));
|
||||
|
||||
const res = await del(join(sibling, 'leak.txt'));
|
||||
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(readFileSync(join(outsideDir, 'key.txt'), 'utf8')).toBe('secret');
|
||||
});
|
||||
|
||||
it('reaches nothing there once it is no longer an outside worktree', async () => {
|
||||
Object.assign(harness.ctx._session, { liveWorktree: { name: 'ws-feature', path: sibling } });
|
||||
expect((await del(join(sibling, 'src', 'feature.ts'))).statusCode).toBe(404);
|
||||
expect(existsSync(join(sibling, 'src', 'feature.ts'))).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['workspace confinement is turned on', () => ({ attachmentConfineToWorkspace: true })],
|
||||
['its parent folder is blocked', () => ({ attachmentBlockedPaths: [base] })],
|
||||
])('deletes nothing there once %s', async (_label, settings) => {
|
||||
mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify(settings()));
|
||||
|
||||
const res = await del(join(sibling, 'src', 'feature.ts'));
|
||||
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(readFileSync(join(sibling, 'src', 'feature.ts'), 'utf8')).toBe('feature');
|
||||
});
|
||||
});
|
||||
|
||||
describe('multi-user mode', () => {
|
||||
let prevMultiUser: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
prevMultiUser = process.env.CODEMAN_MULTIUSER;
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (prevMultiUser === undefined) delete process.env.CODEMAN_MULTIUSER;
|
||||
else process.env.CODEMAN_MULTIUSER = prevMultiUser;
|
||||
});
|
||||
|
||||
it("answers 404 for another user's session and deletes nothing", async () => {
|
||||
const bob = await createRouteTestHarness(registerFileRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
try {
|
||||
bob.ctx._session.workingDir = workDir;
|
||||
(bob.ctx._session as unknown as { owner?: string }).owner = 'alice';
|
||||
writeFileSync(join(workDir, 'alice.txt'), 'mine');
|
||||
|
||||
const res = await del('alice.txt', bob);
|
||||
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(readFileSync(join(workDir, 'alice.txt'), 'utf8')).toBe('mine');
|
||||
} finally {
|
||||
await bob.app.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('lets the owner delete in their own session', async () => {
|
||||
const bob = await createRouteTestHarness(registerFileRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
try {
|
||||
bob.ctx._session.workingDir = workDir;
|
||||
(bob.ctx._session as unknown as { owner?: string }).owner = 'bob';
|
||||
writeFileSync(join(workDir, 'bob.txt'), 'mine');
|
||||
|
||||
expect((await del('bob.txt', bob)).statusCode).toBe(200);
|
||||
expect(existsSync(join(workDir, 'bob.txt'))).toBe(false);
|
||||
} finally {
|
||||
await bob.app.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Cross-workspace attachment extensions with real files.
|
||||
* Port: N/A (app.inject doesn't open ports)
|
||||
*/
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { attachmentRegistry } from '../../src/attachment-registry.js';
|
||||
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
|
||||
describe('cross-workspace attachment extensions (real fs)', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let workDir: string;
|
||||
let outsideDir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.stubEnv('CODEMAN_ATTACHMENT_CONFINE', undefined);
|
||||
vi.stubEnv('CODEMAN_ATTACHMENT_BLOCKED_PATHS', undefined);
|
||||
harness = await createRouteTestHarness(registerFileRoutes);
|
||||
workDir = realpathSync(mkdtempSync(join(tmpdir(), 'codeman-attachment-ws-')));
|
||||
outsideDir = realpathSync(mkdtempSync(join(tmpdir(), 'codeman-attachment-out-')));
|
||||
harness.ctx._session.workingDir = workDir;
|
||||
attachmentRegistry.clearSession(harness.ctx._sessionId);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
attachmentRegistry.clearSession(harness.ctx._sessionId);
|
||||
rmSync(workDir, { recursive: true, force: true });
|
||||
rmSync(outsideDir, { recursive: true, force: true });
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
it.each(['prod.env', 'CONFIG.ENV', 'unsupported.xyz'])(
|
||||
'refuses outside %s as an unsupported attachment without an id',
|
||||
async (fileName) => {
|
||||
const path = join(outsideDir, fileName);
|
||||
writeFileSync(path, 'FIXTURE_ONLY=value\n');
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/attachments`,
|
||||
payload: { path },
|
||||
});
|
||||
const body = res.json();
|
||||
|
||||
expect.soft(res.statusCode).toBe(400);
|
||||
expect.soft(body.success).toBe(false);
|
||||
expect.soft(body.errorCode).toBe('INVALID_INPUT');
|
||||
expect.soft(body.data?.attachmentId).toBe(undefined);
|
||||
expect.soft(body.attachmentId).toBe(undefined);
|
||||
}
|
||||
);
|
||||
|
||||
it('registers outside notes.md with default attachment settings', async () => {
|
||||
const path = join(outsideDir, 'notes.md');
|
||||
const content = '# Outside notes\n';
|
||||
writeFileSync(path, content);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/attachments`,
|
||||
payload: { path },
|
||||
});
|
||||
const body = res.json();
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.fileName).toBe('notes.md');
|
||||
expect(body.data.extension).toBe('md');
|
||||
expect(body.data.size).toBe(Buffer.byteLength(content));
|
||||
|
||||
const raw = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/attachments/${body.data.attachmentId}/raw`,
|
||||
});
|
||||
expect(raw.statusCode).toBe(200);
|
||||
expect(raw.body).toBe(content);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
/**
|
||||
* @fileoverview `GET /api/sessions/:id/files?root=live` (#765).
|
||||
*
|
||||
* The listing starts at the worktree the pane is in, and every `path` stays relative to
|
||||
* `workingDir`: that is what keeps the preview, raw and edit routes working unchanged, inside the
|
||||
* same confinement. Real filesystem on purpose, since the walk is the thing under test.
|
||||
*/
|
||||
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
|
||||
|
||||
const PREFIX = '.claude/worktrees/probe';
|
||||
|
||||
describe('Files panel listing of a live worktree', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let repo: string;
|
||||
let worktree: string;
|
||||
/** Removed after each test: a folder of the server user's outside the session folder. */
|
||||
let outside: string | undefined;
|
||||
|
||||
const list = async (query = '') => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/files?depth=5${query}`,
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
return res.json().data;
|
||||
};
|
||||
const names = (nodes: Array<{ name: string }>) => nodes.map((node) => node.name);
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerFileRoutes);
|
||||
repo = mkdtempSync(join(homedir(), 'live-worktree-route-'));
|
||||
worktree = join(repo, PREFIX);
|
||||
mkdirSync(join(repo, 'src'), { recursive: true });
|
||||
mkdirSync(join(worktree, 'src'), { recursive: true });
|
||||
writeFileSync(join(repo, 'src', 'main-only.ts'), 'main');
|
||||
writeFileSync(join(worktree, 'src', 'worktree-only.ts'), 'worktree');
|
||||
Object.assign(harness.ctx._session, {
|
||||
workingDir: repo,
|
||||
liveWorktree: { name: 'probe', path: worktree },
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
rmSync(repo, { recursive: true, force: true });
|
||||
if (outside) rmSync(outside, { recursive: true, force: true });
|
||||
outside = undefined;
|
||||
});
|
||||
|
||||
/** A folder outside the session folder, holding a visible and a hidden file and a subfolder. */
|
||||
const makeOutsideFolder = () => {
|
||||
outside = mkdtempSync(join(homedir(), 'live-worktree-outside-'));
|
||||
mkdirSync(join(outside, 'inner'));
|
||||
writeFileSync(join(outside, '.hidden-outside'), 'secret');
|
||||
writeFileSync(join(outside, 'inner', 'outside-file.txt'), 'secret');
|
||||
return outside;
|
||||
};
|
||||
const expectSessionFolderListing = (data: {
|
||||
root: string;
|
||||
worktree: unknown;
|
||||
tree: Array<{ name: string; children?: Array<{ path: string }> }>;
|
||||
}) => {
|
||||
expect(data.root).toBe(repo);
|
||||
expect(JSON.stringify(data.tree)).not.toContain('outside');
|
||||
expect(data.tree.find((node) => node.name === 'src')?.children?.[0].path).toBe('src/main-only.ts');
|
||||
// Kept so the panel's comparison with the session's state settles instead of reloading forever.
|
||||
expect(data.worktree).toEqual({ name: 'probe', path: worktree });
|
||||
};
|
||||
|
||||
it('lists the worktree with paths relative to the session folder', async () => {
|
||||
const data = await list('&root=live');
|
||||
expect(data.root).toBe(worktree);
|
||||
expect(data.worktree).toEqual({ name: 'probe', path: worktree });
|
||||
expect(names(data.tree)).toEqual(['src']);
|
||||
expect(data.tree[0].path).toBe(`${PREFIX}/src`);
|
||||
expect(data.tree[0].children[0].path).toBe(`${PREFIX}/src/worktree-only.ts`);
|
||||
});
|
||||
|
||||
it('lists an inside worktree for root=live-any, the root the Files panel sends', async () => {
|
||||
const data = await list('&root=live-any');
|
||||
expect(data.root).toBe(worktree);
|
||||
expect(data.worktree).toEqual({ name: 'probe', path: worktree });
|
||||
expect(names(data.tree)).toEqual(['src']);
|
||||
expect(data.tree[0].path).toBe(`${PREFIX}/src`);
|
||||
expect(data.tree[0].children[0].path).toBe(`${PREFIX}/src/worktree-only.ts`);
|
||||
});
|
||||
|
||||
it('walks the session folder for root=live-any when a symlink replaced the worktree', async () => {
|
||||
rmSync(worktree, { recursive: true });
|
||||
symlinkSync(makeOutsideFolder(), worktree);
|
||||
expectSessionFolderListing(await list('&root=live-any&showHidden=true'));
|
||||
});
|
||||
|
||||
it('does not need hidden files on, though the worktree lives under a dot folder', async () => {
|
||||
const data = await list('&root=live&showHidden=false');
|
||||
expect(data.totalFiles).toBe(1);
|
||||
});
|
||||
|
||||
it('keeps the session folder without the parameter, and still reports the worktree', async () => {
|
||||
const data = await list();
|
||||
expect(data.root).toBe(repo);
|
||||
expect(data.worktree).toEqual({ name: 'probe', path: worktree });
|
||||
expect(names(data.tree)).toEqual(['src']);
|
||||
expect(data.tree[0].children[0].path).toBe('src/main-only.ts');
|
||||
});
|
||||
|
||||
it('answers exactly as before for a session in no worktree', async () => {
|
||||
Object.assign(harness.ctx._session, { liveWorktree: undefined });
|
||||
const data = await list('&root=live');
|
||||
expect(data).toEqual(await list());
|
||||
expect(data.root).toBe(repo);
|
||||
expect('worktree' in data).toBe(false);
|
||||
});
|
||||
|
||||
it('falls back to the session folder when the worktree has gone, keeping the report', async () => {
|
||||
rmSync(worktree, { recursive: true });
|
||||
const data = await list('&root=live');
|
||||
expect(data.root).toBe(repo);
|
||||
// Kept so the panel's comparison with the session's state settles instead of reloading forever.
|
||||
expect(data.worktree).toEqual({ name: 'probe', path: worktree });
|
||||
});
|
||||
|
||||
it('walks the session folder when a symlink replaced the worktree with a folder outside it', async () => {
|
||||
rmSync(worktree, { recursive: true });
|
||||
symlinkSync(makeOutsideFolder(), worktree);
|
||||
expectSessionFolderListing(await list('&root=live&showHidden=true'));
|
||||
});
|
||||
|
||||
it('does not find anything outside the session folder through such a symlink when searching', async () => {
|
||||
rmSync(worktree, { recursive: true });
|
||||
symlinkSync(makeOutsideFolder(), worktree);
|
||||
const data = await list(`&root=live&showHidden=true&q=${encodeURIComponent('outside')}`);
|
||||
expect(data.root).toBe(repo);
|
||||
expect(data.matches).toEqual([]);
|
||||
});
|
||||
|
||||
it('walks the session folder when a parent of the worktree is the symlink', async () => {
|
||||
const parent = join(repo, '.claude/worktrees');
|
||||
rmSync(parent, { recursive: true });
|
||||
mkdirSync(join(makeOutsideFolder(), 'probe'));
|
||||
writeFileSync(join(outside as string, 'probe', 'outside-file.txt'), 'secret');
|
||||
symlinkSync(outside as string, parent);
|
||||
expectSessionFolderListing(await list('&root=live&showHidden=true'));
|
||||
});
|
||||
|
||||
it('walks the session folder when the worktree path is a symlink back to that folder', async () => {
|
||||
rmSync(worktree, { recursive: true });
|
||||
symlinkSync(repo, worktree);
|
||||
expectSessionFolderListing(await list('&root=live'));
|
||||
});
|
||||
|
||||
it('still lists a worktree of a workspace reached through a symlink, in the workspace spelling', async () => {
|
||||
const link = `${repo}-link`;
|
||||
symlinkSync(repo, link);
|
||||
try {
|
||||
const spelled = join(link, PREFIX);
|
||||
Object.assign(harness.ctx._session, {
|
||||
workingDir: link,
|
||||
liveWorktree: { name: 'probe', path: spelled },
|
||||
});
|
||||
const data = await list('&root=live');
|
||||
expect(data.root).toBe(spelled);
|
||||
expect(data.tree[0].children[0].path).toBe(`${PREFIX}/src/worktree-only.ts`);
|
||||
} finally {
|
||||
rmSync(link);
|
||||
}
|
||||
});
|
||||
|
||||
it('searches the worktree: the query reads paths in the listing, the result in the session folder', async () => {
|
||||
const data = await list(`&root=live&q=${encodeURIComponent('src/*.ts')}`);
|
||||
expect(data.root).toBe(worktree);
|
||||
expect(data.matches.map((match: { path: string }) => match.path)).toEqual([`${PREFIX}/src/worktree-only.ts`]);
|
||||
expect(data.worktree).toEqual({ name: 'probe', path: worktree });
|
||||
});
|
||||
|
||||
it('walks a large worktree in fair rounds, and the paths stay relative to the session folder', async () => {
|
||||
mkdirSync(join(worktree, 'a-bulk'));
|
||||
mkdirSync(join(worktree, 'z-later'));
|
||||
for (let index = 0; index < 5100; index++) {
|
||||
writeFileSync(join(worktree, 'a-bulk', `item-${index}.txt`), '');
|
||||
}
|
||||
writeFileSync(join(worktree, 'z-later', 'needle.ts'), 'x');
|
||||
// The main checkout must play no part: this is the folder a walk seeded wrongly would list.
|
||||
writeFileSync(join(repo, 'src', 'needle.ts'), 'main');
|
||||
|
||||
const data = await list('&root=live');
|
||||
expect(data.root).toBe(worktree);
|
||||
expect(data.truncated).toBe(true);
|
||||
expect(names(data.tree)).toEqual(['a-bulk', 'src', 'z-later']);
|
||||
const [bulk, , later] = data.tree;
|
||||
expect(bulk).toMatchObject({ path: `${PREFIX}/a-bulk`, incomplete: true });
|
||||
expect(bulk.children[0].path.startsWith(`${PREFIX}/a-bulk/`)).toBe(true);
|
||||
expect(later).not.toHaveProperty('incomplete');
|
||||
expect(later.children[0].path).toBe(`${PREFIX}/z-later/needle.ts`);
|
||||
|
||||
// A `/` in the query reads the listing's paths, and only the answer is in workingDir's terms.
|
||||
const found = await list(`&root=live&q=${encodeURIComponent('z-later/*.ts')}`);
|
||||
expect(found.root).toBe(worktree);
|
||||
expect(found.matches.map((match: { path: string }) => match.path)).toEqual([`${PREFIX}/z-later/needle.ts`]);
|
||||
expect(found.truncated).toBe(true);
|
||||
const anywhere = await list('&root=live&q=needle');
|
||||
expect(anywhere.matches.map((match: { path: string }) => match.path)).toEqual([`${PREFIX}/z-later/needle.ts`]);
|
||||
});
|
||||
|
||||
it('serves a listed path through the unchanged preview route', async () => {
|
||||
const path = `${PREFIX}/src/worktree-only.ts`;
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/file-content?path=${encodeURIComponent(path)}`,
|
||||
});
|
||||
expect(res.json().success).toBe(true);
|
||||
expect(res.json().data.content).toBe('worktree');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,331 @@
|
||||
/**
|
||||
* @fileoverview The file routes for a worktree OUTSIDE the session's folder (#765 follow-up).
|
||||
*
|
||||
* A session's outside worktree is a second root: `GET .../files?root=live-any` lists it with
|
||||
* ABSOLUTE paths (`root=live` keeps walking `workingDir`), and the read, raw, edit and download
|
||||
* routes confine an absolute path inside it to it. What must not change: a relative path still resolves against `workingDir` only, a path that
|
||||
* escapes the worktree through a symlink is refused, and a worktree folder replaced by a symlink is
|
||||
* neither listed nor served. Real filesystem on purpose, since realpath is the thing under test.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdirSync, mkdtempSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname } from 'node:path';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
|
||||
// The converter would shell out to pdftoppm/LibreOffice; the route's own path check is under test.
|
||||
vi.mock('../../src/document-thumbnailer.js', () => ({
|
||||
generateFirstPageThumbnail: vi.fn(async () => ({ content: Buffer.from('\x89PNG fake'), contentType: 'image/png' })),
|
||||
}));
|
||||
import { generateFirstPageThumbnail } from '../../src/document-thumbnailer.js';
|
||||
|
||||
const sha256 = (text: string) => createHash('sha256').update(text).digest('hex');
|
||||
|
||||
describe('file routes for a worktree outside the session folder', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let base: string;
|
||||
let repo: string;
|
||||
let sibling: string;
|
||||
let secret: string;
|
||||
|
||||
const sessionUrl = (rest: string) => `/api/sessions/${harness.ctx._sessionId}/${rest}`;
|
||||
const list = async (query = '') => {
|
||||
const res = await harness.app.inject({ method: 'GET', url: sessionUrl(`files?depth=5${query}`) });
|
||||
expect(res.statusCode).toBe(200);
|
||||
return res.json().data;
|
||||
};
|
||||
const readContent = (path: string) =>
|
||||
harness.app.inject({ method: 'GET', url: sessionUrl(`file-content?path=${encodeURIComponent(path)}`) });
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerFileRoutes);
|
||||
base = realpathSync(mkdtempSync(join(tmpdir(), 'outside-worktree-route-')));
|
||||
repo = join(base, 'myapp');
|
||||
sibling = join(base, 'myapp-feature');
|
||||
secret = join(base, 'secret');
|
||||
mkdirSync(join(repo, 'src'), { recursive: true });
|
||||
mkdirSync(join(sibling, 'src'), { recursive: true });
|
||||
mkdirSync(secret);
|
||||
writeFileSync(join(repo, 'src', 'main-only.ts'), 'main');
|
||||
writeFileSync(join(sibling, 'src', 'feature-only.ts'), 'feature');
|
||||
writeFileSync(join(secret, 'key.txt'), 'secret');
|
||||
Object.assign(harness.ctx._session, {
|
||||
workingDir: repo,
|
||||
liveWorktree: { name: 'myapp-feature', path: sibling, outside: true },
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
rmSync(base, { recursive: true, force: true });
|
||||
rmSync(SETTINGS_PATH, { force: true });
|
||||
});
|
||||
|
||||
describe('GET .../files', () => {
|
||||
it('lists the worktree with absolute paths', async () => {
|
||||
const data = await list('&root=live-any');
|
||||
expect(data.root).toBe(sibling);
|
||||
expect(data.worktree).toEqual({ name: 'myapp-feature', path: sibling, outside: true });
|
||||
expect(data.tree[0].path).toBe(join(sibling, 'src'));
|
||||
expect(data.tree[0].children[0].path).toBe(join(sibling, 'src', 'feature-only.ts'));
|
||||
});
|
||||
|
||||
it('searches the worktree, matching on paths relative to it and answering absolute ones', async () => {
|
||||
const data = await list(`&root=live-any&q=${encodeURIComponent('src/feature*')}`);
|
||||
expect(data.matches.map((m: { path: string }) => m.path)).toEqual([join(sibling, 'src', 'feature-only.ts')]);
|
||||
});
|
||||
|
||||
it('keeps walking the session folder, with relative paths, for root=live', async () => {
|
||||
const data = await list('&root=live');
|
||||
expect(data.root).toBe(repo);
|
||||
expect(data.worktree).toBeUndefined();
|
||||
expect(data.tree[0].children[0].path).toBe('src/main-only.ts');
|
||||
expect(JSON.stringify(data.tree)).not.toContain('feature-only.ts');
|
||||
});
|
||||
|
||||
it('keeps the session folder, with relative paths, without the parameter', async () => {
|
||||
const data = await list();
|
||||
expect(data.root).toBe(repo);
|
||||
expect(data.worktree).toBeUndefined();
|
||||
expect(data.tree[0].children[0].path).toBe('src/main-only.ts');
|
||||
});
|
||||
|
||||
it('falls back to the session folder once a symlink has taken the worktree folder’s place', async () => {
|
||||
renameSync(sibling, `${sibling}-moved`);
|
||||
symlinkSync(secret, sibling);
|
||||
const data = await list('&root=live-any');
|
||||
expect(data.root).toBe(repo);
|
||||
expect(JSON.stringify(data.tree)).not.toContain('key.txt');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET .../file-content', () => {
|
||||
it('serves an absolute path inside the worktree', async () => {
|
||||
const res = await readContent(join(sibling, 'src', 'feature-only.ts'));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.stringify(res.json())).toContain('feature');
|
||||
});
|
||||
|
||||
it('refuses a sensitive file in the worktree on file-content and file-raw, and serves its neighbours', async () => {
|
||||
writeFileSync(join(sibling, '.env'), 'TOKEN=abc');
|
||||
mkdirSync(join(sibling, '.aws'));
|
||||
writeFileSync(join(sibling, '.aws', 'credentials'), 'aws_secret=abc');
|
||||
writeFileSync(join(sibling, 'plain.ts'), 'plain');
|
||||
for (const blocked of [join(sibling, '.env'), join(sibling, '.aws', 'credentials')]) {
|
||||
const content = await readContent(blocked);
|
||||
expect(content.json().success).toBe(false);
|
||||
expect(content.body).not.toContain('abc');
|
||||
const raw = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: sessionUrl(`file-raw?path=${encodeURIComponent(blocked)}`),
|
||||
});
|
||||
expect(raw.statusCode).not.toBe(200);
|
||||
expect(raw.body).not.toContain('abc');
|
||||
}
|
||||
const plain = await readContent(join(sibling, 'plain.ts'));
|
||||
expect(plain.json().success).toBe(true);
|
||||
const plainRaw = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: sessionUrl(`file-raw?path=${encodeURIComponent(join(sibling, 'plain.ts'))}`),
|
||||
});
|
||||
expect(plainRaw.statusCode).toBe(200);
|
||||
expect(plainRaw.body).toBe('plain');
|
||||
});
|
||||
|
||||
// The editor's own gate lets a dotenv file through (#796), so for a file in an outside
|
||||
// worktree `validateLocalSessionFilePath()` is the ONLY refusal on the edit path.
|
||||
it('refuses to open or save a dotenv file in the worktree through the editor', async () => {
|
||||
const target = join(sibling, '.env');
|
||||
writeFileSync(target, 'TOKEN=abc');
|
||||
const edit = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: sessionUrl(`file-content?edit=1&path=${encodeURIComponent(target)}`),
|
||||
});
|
||||
expect(edit.json().success).toBe(false);
|
||||
expect(edit.body).not.toContain('abc');
|
||||
|
||||
const put = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: sessionUrl('file-content'),
|
||||
payload: { path: target, content: 'TOKEN=changed', baseHash: sha256('TOKEN=abc') },
|
||||
});
|
||||
expect(put.statusCode).not.toBe(200);
|
||||
expect(put.json().success).toBe(false);
|
||||
expect(readFileSync(target, 'utf8')).toBe('TOKEN=abc');
|
||||
|
||||
// The same file in the session's own folder is the one #796 opened.
|
||||
writeFileSync(join(repo, '.env'), 'TOKEN=abc');
|
||||
const own = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: sessionUrl('file-content'),
|
||||
payload: { path: '.env', content: 'TOKEN=changed', baseHash: sha256('TOKEN=abc') },
|
||||
});
|
||||
expect(own.statusCode).toBe(200);
|
||||
expect(readFileSync(join(repo, '.env'), 'utf8')).toBe('TOKEN=changed');
|
||||
});
|
||||
|
||||
it('still resolves a relative path against the session folder only', async () => {
|
||||
expect((await readContent('src/main-only.ts')).statusCode).toBe(200);
|
||||
const escaped = await readContent('../myapp-feature/src/feature-only.ts');
|
||||
expect(JSON.stringify(escaped.json())).not.toContain('"feature"');
|
||||
expect(escaped.json().success).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses a symlink in the worktree that leads out of it', async () => {
|
||||
symlinkSync(join(secret, 'key.txt'), join(sibling, 'leak.txt'));
|
||||
const res = await readContent(join(sibling, 'leak.txt'));
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(JSON.stringify(res.json())).not.toContain('"secret"');
|
||||
});
|
||||
|
||||
it('serves a symlink in the worktree that leads into the session folder', async () => {
|
||||
symlinkSync(join(repo, 'src', 'main-only.ts'), join(sibling, 'main-link.ts'));
|
||||
const res = await readContent(join(sibling, 'main-link.ts'));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().success).toBe(true);
|
||||
});
|
||||
|
||||
it('serves nothing from the folder once a symlink has taken its place', async () => {
|
||||
renameSync(sibling, `${sibling}-moved`);
|
||||
symlinkSync(secret, sibling);
|
||||
const res = await readContent(join(sibling, 'key.txt'));
|
||||
expect(res.json().success).toBe(false);
|
||||
});
|
||||
|
||||
it('serves nothing outside the session folder once the worktree is not outside', async () => {
|
||||
Object.assign(harness.ctx._session, { liveWorktree: { name: 'myapp-feature', path: sibling } });
|
||||
const res = await readContent(join(sibling, 'src', 'feature-only.ts'));
|
||||
expect(res.json().success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('file-raw, download and edit', () => {
|
||||
it('streams an absolute path inside the worktree from file-raw and download', async () => {
|
||||
const target = join(sibling, 'src', 'feature-only.ts');
|
||||
const raw = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: sessionUrl(`file-raw?path=${encodeURIComponent(target)}`),
|
||||
});
|
||||
expect(raw.statusCode).toBe(200);
|
||||
expect(raw.body).toBe('feature');
|
||||
const download = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/download?sessionId=${harness.ctx._sessionId}&path=${encodeURIComponent(target)}`,
|
||||
});
|
||||
expect(download.statusCode).toBe(200);
|
||||
expect(download.body).toBe('feature');
|
||||
});
|
||||
|
||||
it('edits a file inside the worktree in place', async () => {
|
||||
const target = join(sibling, 'notes.md');
|
||||
writeFileSync(target, 'before\n');
|
||||
const res = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: sessionUrl('file-content'),
|
||||
payload: { path: target, content: 'after\n', baseHash: sha256('before\n') },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(readFileSync(target, 'utf8')).toBe('after\n');
|
||||
});
|
||||
|
||||
it('refuses to edit through a symlink that leads out of the worktree', async () => {
|
||||
symlinkSync(join(secret, 'key.txt'), join(sibling, 'leak.md'));
|
||||
const res = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: sessionUrl('file-content'),
|
||||
payload: { path: join(sibling, 'leak.md'), content: 'pwned', baseHash: sha256('secret') },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(readFileSync(join(secret, 'key.txt'), 'utf8')).toBe('secret');
|
||||
});
|
||||
});
|
||||
|
||||
describe('file-preview and file-thumbnail', () => {
|
||||
const preview = (path: string) =>
|
||||
harness.app.inject({ method: 'GET', url: sessionUrl(`file-preview?path=${encodeURIComponent(path)}`) });
|
||||
const thumbnail = (path: string) =>
|
||||
harness.app.inject({ method: 'GET', url: sessionUrl(`file-thumbnail?path=${encodeURIComponent(path)}`) });
|
||||
|
||||
beforeEach(() => {
|
||||
vi.mocked(generateFirstPageThumbnail).mockClear();
|
||||
writeFileSync(join(sibling, 'doc.pdf'), '%PDF-1.4 fake');
|
||||
writeFileSync(join(sibling, 'pic.png'), 'png');
|
||||
});
|
||||
|
||||
it('answers file-preview for an absolute path inside the worktree', async () => {
|
||||
const res = await preview(join(sibling, 'doc.pdf'));
|
||||
expect(res.statusCode).toBeGreaterThanOrEqual(300);
|
||||
expect(res.statusCode).toBeLessThan(400);
|
||||
expect(res.headers.location).toContain('/file-raw?path=');
|
||||
});
|
||||
|
||||
it('serves file-thumbnail for an absolute path inside the worktree', async () => {
|
||||
const res = await thumbnail(join(sibling, 'pic.png'));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['content-type']).toContain('image/png');
|
||||
expect(generateFirstPageThumbnail).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses both once a symlink has taken the worktree folder’s place', async () => {
|
||||
writeFileSync(join(secret, 'doc.pdf'), '%PDF-1.4 fake');
|
||||
writeFileSync(join(secret, 'pic.png'), 'png');
|
||||
renameSync(sibling, `${sibling}-moved`);
|
||||
symlinkSync(secret, sibling);
|
||||
expect((await preview(join(sibling, 'doc.pdf'))).statusCode).toBe(404);
|
||||
expect((await thumbnail(join(sibling, 'pic.png'))).statusCode).toBe(404);
|
||||
expect(generateFirstPageThumbnail).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
describe('the attachment guard, judged again on every request', () => {
|
||||
const target = () => join(sibling, 'src', 'feature-only.ts');
|
||||
const writeSettings = (settings: Record<string, unknown>) => {
|
||||
mkdirSync(dirname(SETTINGS_PATH), { recursive: true });
|
||||
writeFileSync(SETTINGS_PATH, JSON.stringify(settings));
|
||||
};
|
||||
const get = (route: string) =>
|
||||
harness.app.inject({ method: 'GET', url: sessionUrl(`${route}?path=${encodeURIComponent(target())}`) });
|
||||
|
||||
it('serves the worktree while no guard rule applies', async () => {
|
||||
writeSettings({});
|
||||
expect((await get('file-raw')).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['workspace confinement is turned on', () => ({ attachmentConfineToWorkspace: true })],
|
||||
['the worktree’s parent folder is blocked', () => ({ attachmentBlockedPaths: [base] })],
|
||||
])('stops serving it once %s', async (_label, settings) => {
|
||||
writeSettings(settings());
|
||||
|
||||
const content = await get('file-content');
|
||||
expect(content.json().success).toBe(false);
|
||||
expect(content.body).not.toContain('feature');
|
||||
expect((await get('file-raw')).statusCode).toBe(404);
|
||||
|
||||
const before = readFileSync(target(), 'utf8');
|
||||
const put = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: sessionUrl('file-content'),
|
||||
payload: { path: target(), content: 'changed', baseHash: sha256(before) },
|
||||
});
|
||||
expect(put.statusCode).toBe(404);
|
||||
expect(readFileSync(target(), 'utf8')).toBe(before);
|
||||
|
||||
const download = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/download?sessionId=${harness.ctx._sessionId}&path=${encodeURIComponent(target())}`,
|
||||
});
|
||||
expect(download.statusCode).toBe(404);
|
||||
|
||||
// The listing walks the session folder, and keeps reporting the worktree so the panel settles.
|
||||
const data = await list('&root=live-any');
|
||||
expect(data.root).toBe(repo);
|
||||
expect(data.tree[0].children[0].path).toBe('src/main-only.ts');
|
||||
expect(data.worktree).toEqual({ name: 'myapp-feature', path: sibling, outside: true });
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1125,5 +1125,26 @@ describe('file-routes', () => {
|
||||
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('refuses a workspace dotenv download without reading or streaming its content', async () => {
|
||||
const content = 'TEST_DOWNLOAD_VALUE=must-stay-private';
|
||||
const path = `${harness.ctx._session.workingDir}/.env`;
|
||||
mockedReadFile.mockImplementation(async (requestedPath) =>
|
||||
String(requestedPath) === path ? (content as never) : ('{}' as never)
|
||||
);
|
||||
mockedCreateReadStream.mockImplementation(() => Readable.from([Buffer.from(content)]) as never);
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/download?sessionId=${harness.ctx._sessionId}&path=.env`,
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().data).toBeUndefined();
|
||||
expect(res.headers['content-disposition']).toBeUndefined();
|
||||
expect(mockedCreateReadStream.mock.calls).toEqual([]);
|
||||
expect(mockedReadFile.mock.calls.filter(([requestedPath]) => String(requestedPath) === path)).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -91,4 +91,231 @@ describe('files endpoint search mode', () => {
|
||||
expect(body.data.matches).toHaveLength(1);
|
||||
expect(body.data.matches[0]).toMatchObject({ name: 'nested', type: 'directory' });
|
||||
});
|
||||
|
||||
it('shares the scan budget across sibling folders in both tree and search modes', async () => {
|
||||
const bulk = join(root, 'a-bulk');
|
||||
const middle = join(root, 'm-middle');
|
||||
const later = join(root, 'z-later');
|
||||
mkdirSync(bulk);
|
||||
mkdirSync(middle);
|
||||
mkdirSync(later);
|
||||
for (let index = 0; index < 5100; index++) {
|
||||
writeFileSync(join(bulk, `item-${index}.txt`), '');
|
||||
}
|
||||
writeFileSync(join(middle, 'middle.ts'), 'x\n');
|
||||
writeFileSync(join(later, 'needle.ts'), 'x\n');
|
||||
|
||||
try {
|
||||
const tree = await get('');
|
||||
const treePaths = tree.data.tree.map((entry: { path: string }) => entry.path);
|
||||
expect(treePaths).toContain('a-bulk');
|
||||
expect(treePaths).toContain('m-middle');
|
||||
expect(treePaths).toContain('src');
|
||||
expect(treePaths).toContain('z-later');
|
||||
expect(tree.data.truncated).toBe(true);
|
||||
expect(tree.data.totalFiles + tree.data.totalDirectories).toBeLessThanOrEqual(5000);
|
||||
|
||||
const node = (path: string) => tree.data.tree.find((entry: { path: string }) => entry.path === path);
|
||||
expect(node('a-bulk').incomplete).toBe(true);
|
||||
expect(node('a-bulk').children.length).toBeGreaterThan(0);
|
||||
// Finished folders do not carry the key at all, not even as false.
|
||||
expect(node('z-later')).not.toHaveProperty('incomplete');
|
||||
expect(node('z-later').children.map((entry: { path: string }) => entry.path)).toEqual([
|
||||
join('z-later', 'needle.ts'),
|
||||
]);
|
||||
expect(node('m-middle')).not.toHaveProperty('incomplete');
|
||||
|
||||
const search = await get('?q=needle');
|
||||
expect(search.data.matches.map((match: { path: string }) => match.path)).toContain(join('z-later', 'needle.ts'));
|
||||
expect(search.data.truncated).toBe(true);
|
||||
} finally {
|
||||
rmSync(bulk, { recursive: true, force: true });
|
||||
rmSync(middle, { recursive: true, force: true });
|
||||
rmSync(later, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('adds nothing to a listing that fits the budget', async () => {
|
||||
const { data } = await get('');
|
||||
|
||||
expect(data.truncated).toBe(false);
|
||||
expect(JSON.stringify(data)).not.toContain('incomplete');
|
||||
const dir = data.tree.find((entry: { name: string }) => entry.name === 'src');
|
||||
expect(Object.keys(dir)).toEqual(['name', 'path', 'type', 'children']);
|
||||
const file = data.tree.find((entry: { name: string }) => entry.name === 'README.md');
|
||||
expect(Object.keys(file)).toEqual(['name', 'path', 'type', 'size', 'extension']);
|
||||
});
|
||||
|
||||
it('flags folders the budget ran out on part way through a round, read or not', async () => {
|
||||
// 3,000 folders use 3,000 of the 5,000 in the first round. The 2,000 left then buy one file
|
||||
// each, so the round ends with 1,000 folders never read: the last of those is the one a budget
|
||||
// check after the shift would drop from the queue, and with it the flag.
|
||||
const wide = mkdtempSync(join(tmpdir(), 'codeman-file-wide-'));
|
||||
for (let index = 0; index < 3000; index++) {
|
||||
const dir = join(wide, `dir-${String(index).padStart(4, '0')}`);
|
||||
mkdirSync(dir);
|
||||
writeFileSync(join(dir, 'one.txt'), '');
|
||||
writeFileSync(join(dir, 'two.txt'), '');
|
||||
}
|
||||
harness.ctx._session.workingDir = wide;
|
||||
|
||||
try {
|
||||
const { data } = await get('');
|
||||
expect(data.truncated).toBe(true);
|
||||
expect(data.tree).toHaveLength(3000);
|
||||
expect(data.tree.filter((node: { incomplete?: boolean }) => node.incomplete === true)).toHaveLength(3000);
|
||||
const sizes = data.tree.map((node: { children: unknown[] }) => node.children.length);
|
||||
expect(sizes.filter((size: number) => size === 1)).toHaveLength(2000);
|
||||
expect(sizes.filter((size: number) => size === 0)).toHaveLength(1000);
|
||||
} finally {
|
||||
rmSync(wide, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('copes with the root itself being unfinished, and its subfolders still get read', async () => {
|
||||
// The root has no node to flag. Its files stop the walk, but only after the folder it found.
|
||||
const wide = mkdtempSync(join(tmpdir(), 'codeman-file-root-'));
|
||||
mkdirSync(join(wide, 'first'));
|
||||
writeFileSync(join(wide, 'first', 'inside.txt'), '');
|
||||
for (let index = 0; index < 5100; index++) {
|
||||
writeFileSync(join(wide, `item-${index}.txt`), '');
|
||||
}
|
||||
harness.ctx._session.workingDir = wide;
|
||||
|
||||
try {
|
||||
const { data } = await get('');
|
||||
expect(data.truncated).toBe(true);
|
||||
expect(data.totalFiles + data.totalDirectories).toBe(5000);
|
||||
expect(data.tree[0]).toMatchObject({ name: 'first', children: [{ name: 'inside.txt' }] });
|
||||
expect(data.tree[0]).not.toHaveProperty('incomplete');
|
||||
|
||||
const search = await get('?q=inside');
|
||||
expect(search.data.matches.map((match: { path: string }) => match.path)).toEqual([join('first', 'inside.txt')]);
|
||||
expect(search.data.truncated).toBe(true);
|
||||
} finally {
|
||||
rmSync(wide, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('does not let a large folder alone in its round starve the subfolders it holds', async () => {
|
||||
// One level below the walk root, with a second level of subfolder to reach.
|
||||
const wide = mkdtempSync(join(tmpdir(), 'codeman-file-sole-'));
|
||||
mkdirSync(join(wide, 'repo', 'src', 'lib'), { recursive: true });
|
||||
writeFileSync(join(wide, 'repo', 'src', 'lib', 'needle.ts'), '');
|
||||
for (let index = 0; index < 5100; index++) {
|
||||
writeFileSync(join(wide, 'repo', `item-${index}.txt`), '');
|
||||
}
|
||||
harness.ctx._session.workingDir = wide;
|
||||
|
||||
try {
|
||||
const { data } = await get('?q=needle');
|
||||
expect(data.matches.map((match: { path: string }) => match.path)).toEqual([
|
||||
join('repo', 'src', 'lib', 'needle.ts'),
|
||||
]);
|
||||
expect(data.truncated).toBe(true);
|
||||
} finally {
|
||||
rmSync(wide, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('does not let large sibling folders starve the subfolders they hold', async () => {
|
||||
// Two in a round, so "alone in its round" is not what makes this go wrong: each folder's
|
||||
// equal share used to be spent on its own files, leaving nothing for what it had just found.
|
||||
const wide = mkdtempSync(join(tmpdir(), 'codeman-file-pair-'));
|
||||
for (const name of ['a-big', 'b-big']) {
|
||||
mkdirSync(join(wide, name, 'src'), { recursive: true });
|
||||
writeFileSync(join(wide, name, 'src', 'needle.ts'), '');
|
||||
for (let index = 0; index < 5100; index++) {
|
||||
writeFileSync(join(wide, name, `item-${index}.txt`), '');
|
||||
}
|
||||
}
|
||||
harness.ctx._session.workingDir = wide;
|
||||
|
||||
try {
|
||||
const { data } = await get('?q=needle');
|
||||
expect(data.matches.map((match: { path: string }) => match.path).sort()).toEqual([
|
||||
join('a-big', 'src', 'needle.ts'),
|
||||
join('b-big', 'src', 'needle.ts'),
|
||||
]);
|
||||
} finally {
|
||||
rmSync(wide, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('calls a workspace of exactly 5,000 nodes finished', async () => {
|
||||
const exact = mkdtempSync(join(tmpdir(), 'codeman-file-exact-'));
|
||||
mkdirSync(join(exact, 'empty'));
|
||||
for (let index = 0; index < 4999; index++) {
|
||||
writeFileSync(join(exact, `item-${index}.txt`), '');
|
||||
}
|
||||
harness.ctx._session.workingDir = exact;
|
||||
|
||||
try {
|
||||
const { data } = await get('');
|
||||
expect(data.totalFiles + data.totalDirectories).toBe(5000);
|
||||
expect(data.truncated).toBe(false);
|
||||
expect(JSON.stringify(data)).not.toContain('incomplete');
|
||||
} finally {
|
||||
rmSync(exact, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('does not flag a folder whose only unread entries are ones the listing leaves out', async () => {
|
||||
// 3,000 folders leave 2,000 of the budget, which buys each of the first 2,000 its `src`. All
|
||||
// that is left unread in them is `vendor` and `.hidden`, which would never be listed anyway.
|
||||
const wide = mkdtempSync(join(tmpdir(), 'codeman-file-excluded-'));
|
||||
for (let index = 0; index < 3000; index++) {
|
||||
const dir = join(wide, `dir-${String(index).padStart(4, '0')}`);
|
||||
mkdirSync(join(dir, 'src'), { recursive: true });
|
||||
mkdirSync(join(dir, 'vendor'));
|
||||
writeFileSync(join(dir, '.hidden'), '');
|
||||
}
|
||||
harness.ctx._session.workingDir = wide;
|
||||
|
||||
try {
|
||||
const { data } = await get('');
|
||||
expect(data.truncated).toBe(true);
|
||||
expect(data.tree[0].children.map((node: { name: string }) => node.name)).toEqual(['src']);
|
||||
expect(data.tree[0]).not.toHaveProperty('incomplete');
|
||||
expect(data.tree[2999]).toMatchObject({ incomplete: true, children: [] });
|
||||
} finally {
|
||||
rmSync(wide, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('returns search results shallow-first', async () => {
|
||||
const deep = join(root, 'a-deep', 'b', 'c');
|
||||
mkdirSync(deep, { recursive: true });
|
||||
mkdirSync(join(root, 'z-shallow'));
|
||||
writeFileSync(join(deep, 'order-probe.ts'), 'x\n');
|
||||
writeFileSync(join(root, 'z-shallow', 'order-probe.ts'), 'x\n');
|
||||
|
||||
try {
|
||||
const { data } = await get('?q=order-probe');
|
||||
expect(data.matches.map((match: { path: string }) => match.path)).toEqual([
|
||||
join('z-shallow', 'order-probe.ts'),
|
||||
join('a-deep', 'b', 'c', 'order-probe.ts'),
|
||||
]);
|
||||
} finally {
|
||||
rmSync(join(root, 'a-deep'), { recursive: true, force: true });
|
||||
rmSync(join(root, 'z-shallow'), { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('stops at the match limit and says so', async () => {
|
||||
const many = mkdtempSync(join(tmpdir(), 'codeman-file-many-'));
|
||||
for (let index = 0; index < 1100; index++) {
|
||||
writeFileSync(join(many, `hit-${index}.txt`), '');
|
||||
}
|
||||
harness.ctx._session.workingDir = many;
|
||||
|
||||
try {
|
||||
const { data } = await get('?q=hit-');
|
||||
expect(data.matches).toHaveLength(1000);
|
||||
expect(data.matchCount).toBe(1000);
|
||||
expect(data.truncated).toBe(true);
|
||||
} finally {
|
||||
rmSync(many, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* GET /api/sessions/:id/files: what one listing costs the server.
|
||||
*
|
||||
* test/routes/file-search-mode.test.ts pins what the walk returns, on real folders. This file pins
|
||||
* what it reads, which is where a real tree cannot go: 100 folders of 50,000 files is minutes of
|
||||
* setup, and a dead network mount cannot be made in a test. So `fs.readdir` and `fs.stat` are
|
||||
* stubbed here, on the one object the route and the bounded probe both call through.
|
||||
*
|
||||
* Port: none (app.inject).
|
||||
*/
|
||||
import { Dirent, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
|
||||
|
||||
const UV_DIRENT_FILE = 1;
|
||||
const UV_DIRENT_DIR = 2;
|
||||
const dirent = (name: string, type: number, parent: string): Dirent =>
|
||||
new (Dirent as unknown as new (name: string, type: number, path: string) => Dirent)(name, type, parent);
|
||||
|
||||
describe('files endpoint read bounds', () => {
|
||||
let harness: RouteTestHarness;
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerFileRoutes);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
const get = async (query: string) => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${harness.ctx._sessionId}/files${query}`,
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
return JSON.parse(res.body).data;
|
||||
};
|
||||
|
||||
describe('over a workspace far bigger than the budget', () => {
|
||||
const FOLDERS = 100;
|
||||
const FILES_EACH = 50_000;
|
||||
const WORKSPACE = '/virtual/ws';
|
||||
let entriesServed = 0;
|
||||
|
||||
beforeEach(() => {
|
||||
entriesServed = 0;
|
||||
const folders = Array.from({ length: FOLDERS }, (_, index) =>
|
||||
dirent(`class-${String(index).padStart(5, '0')}`, UV_DIRENT_DIR, WORKSPACE)
|
||||
);
|
||||
const files = Array.from({ length: FILES_EACH }, (_, index) =>
|
||||
dirent(`image-${String(index).padStart(8, '0')}.jpg`, UV_DIRENT_FILE, 'x')
|
||||
);
|
||||
vi.spyOn(fs, 'readdir').mockImplementation((async (path: string) => {
|
||||
const entries = path === WORKSPACE ? folders : files;
|
||||
entriesServed += entries.length;
|
||||
return [...entries];
|
||||
}) as never);
|
||||
vi.spyOn(fs, 'stat').mockImplementation((async (path: string) => ({
|
||||
size: 1,
|
||||
isDirectory: () => !String(path).endsWith('.jpg'),
|
||||
})) as never);
|
||||
harness.ctx._session.workingDir = WORKSPACE;
|
||||
});
|
||||
|
||||
it('stops reading once it has read 250,000 entries, not at the end of the workspace', async () => {
|
||||
const data = await get('');
|
||||
|
||||
// Past the ceiling by at most the folder that crossed it.
|
||||
expect(entriesServed).toBeLessThanOrEqual(250_000 + FILES_EACH);
|
||||
// What was read is still used, up to the budget, and nothing unread passes as empty.
|
||||
expect(data.totalFiles + data.totalDirectories).toBe(5000);
|
||||
expect(data.truncated).toBe(true);
|
||||
expect(data.tree).toHaveLength(FOLDERS);
|
||||
for (const folder of data.tree) expect(folder.incomplete).toBe(true);
|
||||
expect(data.tree.filter((folder: { children: unknown[] }) => folder.children.length === 0)).toHaveLength(
|
||||
FOLDERS - 5
|
||||
);
|
||||
});
|
||||
|
||||
it('stops a search the same way', async () => {
|
||||
const data = await get('?q=image-00000000');
|
||||
|
||||
expect(entriesServed).toBeLessThanOrEqual(250_000 + FILES_EACH);
|
||||
expect(data.matches.length).toBeGreaterThan(0);
|
||||
expect(data.truncated).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('with a dead mount below the workspace', () => {
|
||||
let workspace: string;
|
||||
let deadFolder: string;
|
||||
let deadReads: number;
|
||||
let releaseStat: (() => void) | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
workspace = mkdtempSync(join(tmpdir(), 'codeman-file-dead-'));
|
||||
deadFolder = join(workspace, 'z-nas');
|
||||
mkdirSync(deadFolder);
|
||||
mkdirSync(join(workspace, 'a-fine'));
|
||||
writeFileSync(join(workspace, 'a-fine', 'needle.ts'), '');
|
||||
harness.ctx._session.workingDir = workspace;
|
||||
|
||||
deadReads = 0;
|
||||
const never = new Promise<never>(() => {});
|
||||
const realReaddir = fs.readdir.bind(fs);
|
||||
const realStat = fs.stat.bind(fs);
|
||||
vi.spyOn(fs, 'readdir').mockImplementation(((path: string, options: never) => {
|
||||
if (path !== deadFolder) return realReaddir(path, options);
|
||||
deadReads++;
|
||||
return never;
|
||||
}) as never);
|
||||
vi.spyOn(fs, 'stat').mockImplementation(((path: string) => {
|
||||
if (path !== deadFolder) return realStat(path);
|
||||
// Settled in afterEach: the probe calls a path stalled for as long as its stat is pending.
|
||||
return new Promise((_resolve, reject) => {
|
||||
releaseStat = () => reject(Object.assign(new Error('gone'), { code: 'EIO' }));
|
||||
});
|
||||
}) as never);
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
releaseStat?.();
|
||||
releaseStat = undefined;
|
||||
await new Promise((settled) => setTimeout(settled, 0));
|
||||
rmSync(workspace, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
const deadline = <T>(work: Promise<T>): Promise<T> =>
|
||||
Promise.race([
|
||||
work,
|
||||
new Promise<T>((_resolve, reject) => {
|
||||
setTimeout(() => reject(new Error('the listing never answered')), 5000).unref();
|
||||
}),
|
||||
]);
|
||||
|
||||
it('answers without it, and costs it one stuck stat however often the panel asks', async () => {
|
||||
const first = await deadline(get(''));
|
||||
|
||||
// Nothing was read from it, so `children: []` alone would pass it off as an empty folder (#516:
|
||||
// unknown is never absent).
|
||||
const dead = first.tree.find((node: { name: string }) => node.name === 'z-nas');
|
||||
expect(dead).toEqual({ name: 'z-nas', path: 'z-nas', type: 'directory', children: [], incomplete: true });
|
||||
expect(first.truncated).toBe(true);
|
||||
expect(first.tree[0].children.map((node: { name: string }) => node.name)).toEqual(['needle.ts']);
|
||||
expect(deadReads).toBe(0);
|
||||
|
||||
const statCalls = () => vi.mocked(fs.stat).mock.calls.filter(([path]) => path === deadFolder).length;
|
||||
const stats = statCalls();
|
||||
const search = await deadline(get('?q=needle'));
|
||||
expect(search.matches.map((match: { path: string }) => match.path)).toEqual([join('a-fine', 'needle.ts')]);
|
||||
// A hit could be behind it, which is what the search's own `truncated` is for.
|
||||
expect(search.truncated).toBe(true);
|
||||
expect(statCalls()).toBe(stats);
|
||||
expect(deadReads).toBe(0);
|
||||
});
|
||||
|
||||
it('leaves a folder alone once the filesystem says it is gone: that is not an unfinished scan', async () => {
|
||||
vi.mocked(fs.stat).mockImplementation((async (path: string) => {
|
||||
if (path === deadFolder) throw Object.assign(new Error('gone'), { code: 'ENOENT' });
|
||||
return { size: 1, isDirectory: () => true };
|
||||
}) as never);
|
||||
|
||||
const data = await deadline(get(''));
|
||||
|
||||
const gone = data.tree.find((node: { name: string }) => node.name === 'z-nas');
|
||||
expect(gone).toEqual({ name: 'z-nas', path: 'z-nas', type: 'directory', children: [] });
|
||||
expect(data.truncated).toBe(false);
|
||||
expect(deadReads).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -19,7 +19,10 @@ import {
|
||||
readFileSync,
|
||||
symlinkSync,
|
||||
chmodSync,
|
||||
chownSync,
|
||||
statSync,
|
||||
lstatSync,
|
||||
readlinkSync,
|
||||
realpathSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
@@ -27,7 +30,7 @@ import {
|
||||
} from 'node:fs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
|
||||
import { MAX_EDITABLE_BYTES } from '../../src/config/file-editing.js';
|
||||
@@ -209,13 +212,6 @@ describe('file viewer edit mode (real fs)', () => {
|
||||
expect(res.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('rejects a .env file (allowlist first, sensitive-path as backstop)', async () => {
|
||||
writeFileSync(join(workDir, '.env'), 'SECRET=1');
|
||||
const res = await putFile('.env', { content: 'SECRET=2', baseHash: sha256('SECRET=1') });
|
||||
expect([400, 403]).toContain(res.statusCode);
|
||||
expect(readFileSync(join(workDir, '.env'), 'utf8')).toBe('SECRET=1');
|
||||
});
|
||||
|
||||
it('400s when the current file contains a NUL byte', async () => {
|
||||
writeFileSync(join(workDir, 'weird.txt'), Buffer.from([0x61, 0x00, 0x62]));
|
||||
const res = await putFile('weird.txt', { content: 'ab', baseHash: sha256(Buffer.from([0x61, 0x00, 0x62])) });
|
||||
@@ -324,6 +320,175 @@ describe('file viewer edit mode (real fs)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('dotenv files', () => {
|
||||
const original = 'TEST_VALUE=original\nTEST_LABEL=café';
|
||||
const updated = 'TEST_VALUE=updated\nTEST_LABEL=été';
|
||||
const editablePaths = ['.env', '.env.local', '.env.example', 'config.env', 'app/.env'];
|
||||
const forbiddenPaths = [
|
||||
'.ssh/.env',
|
||||
'.codeman/.env',
|
||||
'.codeman-dev/.env',
|
||||
// Spelled in capitals: the same login file on a case-insensitive filesystem.
|
||||
'.codeman/.ENV',
|
||||
'.CODEMAN/.env',
|
||||
'.npmrc',
|
||||
'credentials.json',
|
||||
];
|
||||
|
||||
const getPreview = (path: string) =>
|
||||
harness.app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${sessionId}/file-content?path=${encodeURIComponent(path)}`,
|
||||
});
|
||||
|
||||
describe.each(editablePaths)('%s', (path) => {
|
||||
beforeEach(() => {
|
||||
mkdirSync(dirname(join(workDir, path)), { recursive: true });
|
||||
writeFileSync(join(workDir, path), original);
|
||||
});
|
||||
|
||||
it('plain preview returns exact content and advertises editable:true', async () => {
|
||||
const res = await getPreview(path);
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.content).toBe(original);
|
||||
expect(body.data.editable).toBe(true);
|
||||
});
|
||||
|
||||
it('edit=1 returns full content and the SHA-256 of the file bytes', async () => {
|
||||
const res = await getEdit(path);
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(true);
|
||||
expect(body.data.content).toBe(original);
|
||||
expect(body.data.hash).toBe(sha256(Buffer.from(original, 'utf8')));
|
||||
expect(body.data.editable).toBe(true);
|
||||
expect(body.data.truncated).toBe(false);
|
||||
expect(body.data.totalLines).toBe(2);
|
||||
expect(body.data.eol).toBe('lf');
|
||||
});
|
||||
|
||||
it('PUT saves exact bytes and leaves no temp files', async () => {
|
||||
const directory = dirname(join(workDir, path));
|
||||
const before = readdirSync(directory).sort();
|
||||
const res = await putFile(path, { content: updated, baseHash: sha256(original) });
|
||||
expect.soft(res.statusCode).toBe(200);
|
||||
const body = res.json();
|
||||
expect.soft(body.success).toBe(true);
|
||||
expect.soft(body.data?.hash).toBe(sha256(updated));
|
||||
expect.soft(body.data?.eol).toBe('lf');
|
||||
expect.soft(body.data?.size).toBe(Buffer.byteLength(updated));
|
||||
expect.soft(readFileSync(join(workDir, path))).toEqual(Buffer.from(updated));
|
||||
expect(readdirSync(directory).sort()).toEqual(before);
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
['0600', 0o600],
|
||||
['0640', 0o640],
|
||||
])('preserves dotenv mode %s across a save', async (_label, mode) => {
|
||||
const path = join(workDir, '.env');
|
||||
writeFileSync(path, original);
|
||||
chmodSync(path, mode);
|
||||
const res = await putFile('.env', { content: updated, baseHash: sha256(original) });
|
||||
expect.soft(res.statusCode).toBe(200);
|
||||
expect.soft(res.json().success).toBe(true);
|
||||
expect.soft(readFileSync(path)).toEqual(Buffer.from(updated));
|
||||
expect(statSync(path).mode & 0o777).toBe(mode);
|
||||
});
|
||||
|
||||
// The save publishes a NEW file. Without help it takes this process's own group, so a
|
||||
// `.env` shared with a web server by group (you:www-data, 0640) came back you:you.
|
||||
const otherGroup = process.getgroups?.().find((gid) => gid !== process.getgid?.());
|
||||
it.skipIf(otherGroup === undefined)('keeps the group of a dotenv file across a save', async () => {
|
||||
const path = join(workDir, '.env');
|
||||
writeFileSync(path, original);
|
||||
chownSync(path, -1, otherGroup!);
|
||||
chmodSync(path, 0o640);
|
||||
const res = await putFile('.env', { content: updated, baseHash: sha256(original) });
|
||||
expect.soft(res.statusCode).toBe(200);
|
||||
expect.soft(readFileSync(path)).toEqual(Buffer.from(updated));
|
||||
expect.soft(statSync(path).mode & 0o777).toBe(0o640);
|
||||
expect(statSync(path).gid).toBe(otherGroup);
|
||||
});
|
||||
|
||||
it('rejects a stale dotenv baseHash with 409 and leaves the bytes unchanged', async () => {
|
||||
writeFileSync(join(workDir, '.env'), original);
|
||||
const res = await putFile('.env', { content: updated, baseHash: sha256('TEST_VALUE=older') });
|
||||
expect.soft(res.statusCode).toBe(409);
|
||||
expect.soft(res.json().success).toBe(false);
|
||||
expect.soft(res.json().errorCode).toBe('CONFLICT');
|
||||
expect(readFileSync(join(workDir, '.env'))).toEqual(Buffer.from(original));
|
||||
});
|
||||
|
||||
describe.each(forbiddenPaths)('protected %s', (path) => {
|
||||
beforeEach(() => {
|
||||
mkdirSync(dirname(join(workDir, path)), { recursive: true });
|
||||
writeFileSync(join(workDir, path), original);
|
||||
});
|
||||
|
||||
it('plain preview advertises editable:false', async () => {
|
||||
const res = await getPreview(path);
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().success).toBe(true);
|
||||
expect(res.json().data.editable).toBe(false);
|
||||
});
|
||||
|
||||
it('edit=1 refuses with 403', async () => {
|
||||
const res = await getEdit(path);
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().errorCode).toBe('FORBIDDEN');
|
||||
});
|
||||
|
||||
it('PUT refuses with FORBIDDEN and leaves the bytes unchanged', async () => {
|
||||
const res = await putFile(path, { content: updated, baseHash: sha256(original) });
|
||||
expect.soft(res.statusCode).toBe(403);
|
||||
expect.soft(res.json().success).toBe(false);
|
||||
expect.soft(res.json().errorCode).toBe('FORBIDDEN');
|
||||
expect(readFileSync(join(workDir, path))).toEqual(Buffer.from(original));
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a dotenv symlink to credentials.json with 403 and preserves its target', async () => {
|
||||
const target = join(workDir, 'credentials.json');
|
||||
writeFileSync(target, original);
|
||||
symlinkSync(target, join(workDir, '.env'));
|
||||
const res = await putFile('.env', { content: updated, baseHash: sha256(original) });
|
||||
expect.soft(res.statusCode).toBe(403);
|
||||
expect.soft(res.json().success).toBe(false);
|
||||
expect.soft(res.json().errorCode).toBe('FORBIDDEN');
|
||||
expect(readFileSync(target)).toEqual(Buffer.from(original));
|
||||
});
|
||||
|
||||
it('refuses a dotenv symlink outside the workspace with 404 and preserves its target', async () => {
|
||||
const target = join(outsideDir, 'outside.env');
|
||||
writeFileSync(target, original);
|
||||
symlinkSync(target, join(workDir, '.env'));
|
||||
const res = await putFile('.env', { content: updated, baseHash: sha256(original) });
|
||||
expect.soft(res.statusCode).toBe(404);
|
||||
expect.soft(res.json().success).toBe(false);
|
||||
expect(readFileSync(target)).toEqual(Buffer.from(original));
|
||||
});
|
||||
|
||||
it('writes through a dotenv symlink to real.env and preserves the symlink', async () => {
|
||||
const target = join(workDir, 'real.env');
|
||||
const link = join(workDir, '.env');
|
||||
writeFileSync(target, original);
|
||||
symlinkSync(target, link);
|
||||
const before = readdirSync(workDir).sort();
|
||||
const res = await putFile('.env', { content: updated, baseHash: sha256(original) });
|
||||
expect.soft(res.statusCode).toBe(200);
|
||||
expect.soft(res.json().success).toBe(true);
|
||||
expect.soft(readFileSync(target)).toEqual(Buffer.from(updated));
|
||||
expect.soft(readFileSync(link)).toEqual(Buffer.from(updated));
|
||||
expect.soft(lstatSync(link).isSymbolicLink()).toBe(true);
|
||||
expect.soft(readlinkSync(link)).toBe(target);
|
||||
expect(readdirSync(workDir).sort()).toEqual(before);
|
||||
});
|
||||
});
|
||||
|
||||
// ========== multi-user scoping ==========
|
||||
|
||||
describe('multi-user ownership', () => {
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* @fileoverview POST /api/filesystem/mkdir: the path picker's "New folder". Real filesystem under
|
||||
* test/setup.ts's temp HOME (a root the picker offers), so this proves what is on disk, not a mock.
|
||||
* Port: N/A (app.inject()).
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, writeFileSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
|
||||
import { LinkCaseSchema } from '../../src/web/schemas.js';
|
||||
import { isSandboxedHome, safeRmHomeTree } from '../mocks/index.js';
|
||||
|
||||
describe('POST /api/filesystem/mkdir', () => {
|
||||
let workDir = '';
|
||||
|
||||
beforeEach(() => {
|
||||
if (!isSandboxedHome()) throw new Error('filesystem-mkdir-routes.test.ts creates folders: run it via npm test');
|
||||
workDir = realpathSync(mkdtempSync(join(homedir(), 'picker-mkdir-')));
|
||||
});
|
||||
afterEach(() => {
|
||||
if (workDir) safeRmHomeTree(workDir);
|
||||
workDir = '';
|
||||
});
|
||||
|
||||
const mkdir = async (payload: Record<string, unknown>) => {
|
||||
const { app } = await createRouteTestHarness(registerFileRoutes);
|
||||
return app.inject({ method: 'POST', url: '/api/filesystem/mkdir', payload });
|
||||
};
|
||||
|
||||
it('creates one folder inside the folder being viewed and answers its path', async () => {
|
||||
const res = await mkdir({ path: workDir, name: 'fresh' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data).toEqual({ path: join(workDir, 'fresh') });
|
||||
expect(readdirSync(workDir)).toEqual(['fresh']);
|
||||
});
|
||||
|
||||
it.each(['Kay app', 'project_v2', 'v1.2', 'my-folder', 'Café 2026'])(
|
||||
'accepts %s, and Link Existing then accepts the folder it made',
|
||||
async (name) => {
|
||||
const res = await mkdir({ path: workDir, name });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(LinkCaseSchema.safeParse({ name: 'x', path: res.json().data.path }).success).toBe(true);
|
||||
}
|
||||
);
|
||||
|
||||
it('refuses the cases directory as the parent (400): a folder there is already a case', async () => {
|
||||
const casesDir = join(homedir(), 'codeman-cases');
|
||||
mkdirSync(casesDir, { recursive: true });
|
||||
try {
|
||||
const res = await mkdir({ path: casesDir, name: 'myproj' });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toContain('Pick a folder outside it');
|
||||
// Every picker offering New folder sees this, and Clone Repo opens here by default.
|
||||
expect(res.json().error).toContain('Add Case > Create New or Clone Repo (no custom folder)');
|
||||
expect(existsSync(join(casesDir, 'myproj'))).toBe(false);
|
||||
// A folder inside a case is fine.
|
||||
mkdirSync(join(casesDir, 'real-case'));
|
||||
expect((await mkdir({ path: join(casesDir, 'real-case'), name: 'sub' })).statusCode).toBe(200);
|
||||
} finally {
|
||||
safeRmHomeTree(casesDir);
|
||||
}
|
||||
});
|
||||
|
||||
it('answers 404 for a parent that is gone, the same answer browse gives', async () => {
|
||||
const res = await mkdir({ path: join(workDir, 'gone'), name: 'x' });
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
it('refuses a parent that is a file (400), like browse', async () => {
|
||||
writeFileSync(join(workDir, 'afile'), 'x');
|
||||
const res = await mkdir({ path: join(workDir, 'afile'), name: 'x' });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toBe('The folder to create in must be a directory');
|
||||
});
|
||||
|
||||
it('creates inside a hidden folder only when the picker is showing hidden entries', async () => {
|
||||
mkdirSync(join(workDir, '.hid'));
|
||||
const denied = await mkdir({ path: join(workDir, '.hid'), name: 'x' });
|
||||
expect(denied.statusCode).toBe(403);
|
||||
const ok = await mkdir({ path: join(workDir, '.hid'), name: 'x', showHidden: 'true' });
|
||||
expect(ok.statusCode).toBe(200);
|
||||
expect(existsSync(join(workDir, '.hid', 'x'))).toBe(true);
|
||||
// A dot name is still refused there.
|
||||
expect((await mkdir({ path: join(workDir, '.hid'), name: '.y', showHidden: 'true' })).statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('trims the name', async () => {
|
||||
const res = await mkdir({ path: workDir, name: ' spaced ' });
|
||||
expect(res.json().data.path).toBe(join(workDir, 'spaced'));
|
||||
});
|
||||
|
||||
it('refuses an existing folder (409) without touching it', async () => {
|
||||
mkdirSync(join(workDir, 'taken'));
|
||||
writeFileSync(join(workDir, 'taken', 'keep.txt'), 'mine');
|
||||
const res = await mkdir({ path: workDir, name: 'taken' });
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json().error).toContain('already exists');
|
||||
expect(readdirSync(join(workDir, 'taken'))).toEqual(['keep.txt']);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['a slash', 'a/b'],
|
||||
['a backslash', 'a\\b'],
|
||||
['a traversal', '..'],
|
||||
['a dot name', '.'],
|
||||
['a hidden name', '.secret'],
|
||||
['a lone tilde', '~'],
|
||||
['a leading tilde', '~tilde'],
|
||||
['an empty name', ' '],
|
||||
['an apostrophe', "Kay's app"],
|
||||
['parentheses', 'project (v2)'],
|
||||
['a plus', 'a+b'],
|
||||
['a comma', 'notes, 2026'],
|
||||
['a hash', 'c#'],
|
||||
['brackets', '[draft]'],
|
||||
['a double dot inside', 'v1..2'],
|
||||
['a tab', 'a\tb'],
|
||||
['an escape', 'a\x1b[31mb'],
|
||||
['a bell', 'a\x07b'],
|
||||
['a delete char', 'a\x7fb'],
|
||||
['a name over 255 bytes', 'é'.repeat(200)],
|
||||
])('refuses %s in the name (400) and creates nothing', async (_label, name) => {
|
||||
const res = await mkdir({ path: workDir, name });
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(readdirSync(workDir)).toEqual([]);
|
||||
});
|
||||
|
||||
it('refuses a parent that does not exist (404)', async () => {
|
||||
const res = await mkdir({ path: join(workDir, 'nope'), name: 'x' });
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(existsSync(join(workDir, 'nope'))).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses a parent outside the browse roots (403)', async () => {
|
||||
const res = await mkdir({ path: '/etc', name: 'x' });
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(existsSync('/etc/x')).toBe(false);
|
||||
});
|
||||
|
||||
it('refuses a relative or traversing parent (400)', async () => {
|
||||
expect((await mkdir({ path: 'relative', name: 'x' })).statusCode).toBe(400);
|
||||
expect((await mkdir({ path: `${workDir}/../x`, name: 'x' })).statusCode).toBe(400);
|
||||
});
|
||||
|
||||
describe('multi-user scoping', () => {
|
||||
let prevMultiUser: string | undefined;
|
||||
let prevSpaces: string | undefined;
|
||||
let spaces = '';
|
||||
|
||||
beforeEach(() => {
|
||||
prevMultiUser = process.env.CODEMAN_MULTIUSER;
|
||||
prevSpaces = process.env.CODEMAN_USER_SPACES_DIR;
|
||||
spaces = join(workDir, 'spaces');
|
||||
mkdirSync(join(spaces, 'alice'), { recursive: true });
|
||||
mkdirSync(join(spaces, 'bob'));
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
process.env.CODEMAN_USER_SPACES_DIR = spaces;
|
||||
});
|
||||
afterEach(() => {
|
||||
if (prevMultiUser === undefined) delete process.env.CODEMAN_MULTIUSER;
|
||||
else process.env.CODEMAN_MULTIUSER = prevMultiUser;
|
||||
if (prevSpaces === undefined) delete process.env.CODEMAN_USER_SPACES_DIR;
|
||||
else process.env.CODEMAN_USER_SPACES_DIR = prevSpaces;
|
||||
});
|
||||
|
||||
it("refuses a non-admin creating inside another user's space (403) and creates nothing", async () => {
|
||||
const { app } = await createRouteTestHarness(registerFileRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/filesystem/mkdir',
|
||||
payload: { path: join(spaces, 'alice'), name: 'x' },
|
||||
});
|
||||
expect(res.statusCode).toBe(403);
|
||||
expect(readdirSync(join(spaces, 'alice'))).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses a non-admin's own cases folder (400) but not the top of their space", async () => {
|
||||
const { app } = await createRouteTestHarness(registerFileRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
const own = join(spaces, 'bob', 'cases');
|
||||
mkdirSync(own, { recursive: true });
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/filesystem/mkdir',
|
||||
payload: { path: own, name: 'myproj' },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(existsSync(join(own, 'myproj'))).toBe(false);
|
||||
});
|
||||
|
||||
it('lets a non-admin create inside their own space', async () => {
|
||||
const { app } = await createRouteTestHarness(registerFileRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/filesystem/mkdir',
|
||||
payload: { path: join(spaces, 'bob'), name: 'mine' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(existsSync(join(spaces, 'bob', 'mine'))).toBe(true);
|
||||
});
|
||||
|
||||
it('404s a sessionId owned by another user, and adopts none of its folder', async () => {
|
||||
const scoped = await createRouteTestHarness(registerFileRoutes, { authUser: { username: 'bob', role: 'user' } });
|
||||
scoped.ctx._session.owner = 'alice';
|
||||
const res = await scoped.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/filesystem/mkdir',
|
||||
payload: { path: join(spaces, 'bob'), name: 'x', sessionId: scoped.ctx._sessionId },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(existsSync(join(spaces, 'bob', 'x'))).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* @fileoverview `POST /api/filesystem/mkdir` probes the folder bounded before the picker's
|
||||
* resolver runs `realpathSync` on it (#516): a mount that stopped answering is refused, and
|
||||
* the request never reaches a synchronous call that would freeze the server.
|
||||
*
|
||||
* The probe is mocked: a mount that never answers cannot be made here. Port: none (inject).
|
||||
*/
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../src/utils/bounded-path-probe.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/utils/bounded-path-probe.js')>();
|
||||
return { ...actual, probePathKind: vi.fn(actual.probePathKind) };
|
||||
});
|
||||
|
||||
import { probePathKind } from '../../src/utils/bounded-path-probe.js';
|
||||
import { registerFileRoutes } from '../../src/web/routes/file-routes.js';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
|
||||
describe('POST /api/filesystem/mkdir on an unresponsive mount', () => {
|
||||
afterEach(() => vi.mocked(probePathKind).mockClear());
|
||||
|
||||
it('refuses before the picker resolver touches the path', async () => {
|
||||
vi.mocked(probePathKind).mockResolvedValueOnce('unknown');
|
||||
const { app } = await createRouteTestHarness(registerFileRoutes);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/filesystem/mkdir',
|
||||
payload: { path: '/mnt/dead/projects', name: 'fresh' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(422);
|
||||
expect(res.json().errorCode).toBe('OPERATION_FAILED');
|
||||
expect(res.json().error).toMatch(/not responding|not checked/);
|
||||
expect(probePathKind).toHaveBeenCalledWith('/mnt/dead/projects', { pastCap: true });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,550 @@
|
||||
/**
|
||||
* @fileoverview The HTTP surface of foreign-tmux adoption, and the gates that
|
||||
* keep Codeman from driving a session it did not start.
|
||||
*
|
||||
* An adopted session wraps a process SOMEONE ELSE launched. Its `mode` is
|
||||
* whatever the probe saw (very often `claude`), so every refusal here has to
|
||||
* be its own `isAdopted` check and not a side effect of the external-CLI rule.
|
||||
* The two questions are different ("is this CLI one we drive?" vs "did we start
|
||||
* this process?"), and folding them into one means the day the first loosens,
|
||||
* Codeman silently starts sending `/clear` into someone's live conversation.
|
||||
*
|
||||
* Every refusal is paired with a session Codeman DID start, or a broken
|
||||
* endpoint would satisfy the refusal assertion just as well.
|
||||
*
|
||||
* Port: none (app.inject()).
|
||||
*/
|
||||
import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
|
||||
// The adopt route RE-RESOLVES the candidate rather than trusting the body, and
|
||||
// real discovery is disabled under VITEST, so the success path is unreachable
|
||||
// without standing in for it. Everything downstream of the lookup is real.
|
||||
const discoverForeignSessions = vi.fn();
|
||||
const invalidateForeignCache = vi.fn();
|
||||
vi.mock('../../src/foreign-tmux-discovery.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/foreign-tmux-discovery.js')>();
|
||||
return {
|
||||
...actual,
|
||||
discoverForeignSessions: (...a: unknown[]) => discoverForeignSessions(...(a as [])),
|
||||
invalidateForeignCache: () => invalidateForeignCache(),
|
||||
readAllDockerCases: async () => [],
|
||||
readAllRemoteHosts: async () => [],
|
||||
};
|
||||
});
|
||||
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
import { registerRespawnRoutes } from '../../src/web/routes/respawn-routes.js';
|
||||
import { registerRalphRoutes } from '../../src/web/routes/ralph-routes.js';
|
||||
import { registerMuxRoutes } from '../../src/web/routes/mux-routes.js';
|
||||
import { registerGitStatusRoutes } from '../../src/web/routes/git-status-routes.js';
|
||||
import { adoptTargetIdentity, foreignTargetKey } from '../../src/foreign-tmux.js';
|
||||
import type { SessionAdopt } from '../../src/types/session.js';
|
||||
|
||||
const SID = 'adopted-1';
|
||||
|
||||
// The stand-in defaults to "found nothing", which is what real discovery gives
|
||||
// under VITEST, so mocking the module does not change the tests that predate it.
|
||||
beforeEach(() => {
|
||||
discoverForeignSessions.mockReset();
|
||||
discoverForeignSessions.mockResolvedValue({ sessions: [], notes: [] });
|
||||
invalidateForeignCache.mockClear();
|
||||
});
|
||||
|
||||
describe('adopted sessions refuse every auto-op that drives the pane', () => {
|
||||
for (const route of ['auto-clear', 'auto-compact', 'auto-resume']) {
|
||||
it(`refuses POST /api/sessions/:id/${route}`, async () => {
|
||||
const h = await createRouteTestHarness(registerSessionRoutes, { sessionId: SID });
|
||||
(h.ctx._session as unknown as { isAdopted: boolean }).isAdopted = true;
|
||||
const res = await h.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${SID}/${route}`,
|
||||
payload: { enabled: true },
|
||||
});
|
||||
const body = res.json();
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toMatch(/adopted/i);
|
||||
await h.app.close();
|
||||
});
|
||||
|
||||
it(`still allows ${route} on a session Codeman started`, async () => {
|
||||
const h = await createRouteTestHarness(registerSessionRoutes, { sessionId: SID });
|
||||
const res = await h.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${SID}/${route}`,
|
||||
payload: { enabled: true },
|
||||
});
|
||||
expect(res.json().success).toBe(true);
|
||||
await h.app.close();
|
||||
});
|
||||
}
|
||||
|
||||
it('refuses a one-shot prompt, which would start a new local claude in /tmp', async () => {
|
||||
const h = await createRouteTestHarness(registerSessionRoutes, { sessionId: SID });
|
||||
(h.ctx._session as unknown as { isAdopted: boolean }).isAdopted = true;
|
||||
const res = await h.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${SID}/run`,
|
||||
payload: { prompt: 'hello' },
|
||||
});
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().error).toMatch(/adopted/i);
|
||||
expect(h.ctx._session.runPrompt).not.toHaveBeenCalled();
|
||||
await h.app.close();
|
||||
});
|
||||
|
||||
it('still runs a one-shot prompt on a session Codeman started', async () => {
|
||||
const h = await createRouteTestHarness(registerSessionRoutes, { sessionId: SID });
|
||||
await h.app.inject({ method: 'POST', url: `/api/sessions/${SID}/run`, payload: { prompt: 'hello' } });
|
||||
expect(h.ctx._session.runPrompt).toHaveBeenCalledWith('hello');
|
||||
await h.app.close();
|
||||
});
|
||||
|
||||
it('refuses respawn, for a harder reason: it kills and restarts the pane', async () => {
|
||||
const h = await createRouteTestHarness(registerRespawnRoutes, { sessionId: SID });
|
||||
(h.ctx._session as unknown as { isAdopted: boolean }).isAdopted = true;
|
||||
const res = await h.app.inject({ method: 'POST', url: `/api/sessions/${SID}/respawn/start`, payload: {} });
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().error).toMatch(/adopted/i);
|
||||
await h.app.close();
|
||||
});
|
||||
|
||||
it('refuses Ralph config', async () => {
|
||||
const h = await createRouteTestHarness(registerRalphRoutes, { sessionId: SID });
|
||||
(h.ctx._session as unknown as { isAdopted: boolean }).isAdopted = true;
|
||||
const res = await h.app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${SID}/ralph-config`,
|
||||
payload: { maxTodos: 10 },
|
||||
});
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().error).toMatch(/adopted/i);
|
||||
await h.app.close();
|
||||
});
|
||||
|
||||
// ⚠️ Neither of these is a mock-only concern: an adopted session's `workingDir` is the
|
||||
// neutral wrapper folder `/tmp`, so a live one wrote `/tmp/@ralph_prompt.md` on the host
|
||||
// and answered success, a predictable name in a folder anyone can write to.
|
||||
describe.each([
|
||||
['fix-plan/write', {}],
|
||||
['fix-plan/read', {}],
|
||||
['ralph-prompt/write', { content: 'prompt' }],
|
||||
])('POST %s', (route, payload) => {
|
||||
let dir: string;
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'adopted-ralph-'));
|
||||
writeFileSync(join(dir, '@fix_plan.md'), '- [ ] task\n');
|
||||
});
|
||||
afterEach(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
const post = async (isAdopted: boolean) => {
|
||||
const h = await createRouteTestHarness(registerRalphRoutes, { sessionId: SID });
|
||||
const ralphTracker = { todos: [], generateFixPlanMarkdown: () => '', importFixPlanMarkdown: () => 0 };
|
||||
Object.assign(h.ctx._session as object, { isAdopted, workingDir: dir, ralphTracker });
|
||||
const res = await h.app.inject({ method: 'POST', url: `/api/sessions/${SID}/${route}`, payload });
|
||||
await h.app.close();
|
||||
return res.json();
|
||||
};
|
||||
|
||||
it('refuses an adopted session and touches nothing', async () => {
|
||||
const before = readdirSync(dir);
|
||||
const body = await post(true);
|
||||
expect(body.success).toBe(false);
|
||||
expect(body.error).toMatch(/adopted/i);
|
||||
expect(readdirSync(dir)).toEqual(before);
|
||||
});
|
||||
|
||||
it('still answers for a session Codeman started', async () => {
|
||||
expect((await post(false)).success).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/mux/foreign', () => {
|
||||
let prev: string | undefined;
|
||||
beforeEach(() => {
|
||||
prev = process.env.CODEMAN_MULTIUSER;
|
||||
});
|
||||
afterEach(() => {
|
||||
if (prev === undefined) delete process.env.CODEMAN_MULTIUSER;
|
||||
else process.env.CODEMAN_MULTIUSER = prev;
|
||||
});
|
||||
|
||||
it('is admin-only in multi-user mode: it exposes every user’s processes and cwds', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerMuxRoutes, {
|
||||
authUser: { username: 'bob', role: 'user' },
|
||||
});
|
||||
const res = await app.inject({ method: 'GET', url: '/api/mux/foreign' });
|
||||
expect(res.statusCode).toBeGreaterThanOrEqual(400);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('answers an admin', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerMuxRoutes, {
|
||||
authUser: { username: 'root', role: 'admin' },
|
||||
});
|
||||
expect((await app.inject({ method: 'GET', url: '/api/mux/foreign' })).statusCode).toBe(200);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('answers in single-user mode, where the admin gate is a no-op', async () => {
|
||||
delete process.env.CODEMAN_MULTIUSER;
|
||||
const { app } = await createRouteTestHarness(registerMuxRoutes);
|
||||
const res = await app.inject({ method: 'GET', url: '/api/mux/foreign' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
// Real discovery is disabled under VITEST, so this pins the shape, not the
|
||||
// content. The body is bare here: the uniform envelope is applied by the
|
||||
// server's own hook, which a single-route harness does not install.
|
||||
expect(res.json()).toHaveProperty('sessions');
|
||||
expect(res.json()).toHaveProperty('canScanWide');
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/sessions/adopt', () => {
|
||||
let prev: string | undefined;
|
||||
beforeEach(() => {
|
||||
prev = process.env.CODEMAN_MULTIUSER;
|
||||
});
|
||||
afterEach(() => {
|
||||
if (prev === undefined) delete process.env.CODEMAN_MULTIUSER;
|
||||
else process.env.CODEMAN_MULTIUSER = prev;
|
||||
});
|
||||
|
||||
it('is admin-only in multi-user mode: adopting a shell is arbitrary host execution', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
const { app } = await createRouteTestHarness(registerSessionRoutes, {
|
||||
authUser: { username: 'bob', role: 'user' },
|
||||
});
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'x' } });
|
||||
expect(res.statusCode).toBeGreaterThanOrEqual(400);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('404s when the re-resolve no longer sees the target', async () => {
|
||||
// The browser hands back only an opaque id; the socket path and session name
|
||||
// are re-derived server-side, so a vanished target is simply absent from the
|
||||
// fresh list.
|
||||
const { app } = await createRouteTestHarness(registerSessionRoutes);
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'nope' } });
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().errorCode).toBe('NOT_FOUND');
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('rejects a body that tries to supply a socket path or session name', async () => {
|
||||
// The schema takes the opaque id and nothing else. That is why a path can
|
||||
// never reach the launch chain from the browser.
|
||||
const { app } = await createRouteTestHarness(registerSessionRoutes);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/adopt',
|
||||
payload: { id: 'x', socketPath: '/tmp/tmux-0/default', targetSession: 'work' },
|
||||
});
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().errorCode).toBe('INVALID_INPUT');
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
|
||||
/** The adoption record of a local wrapper, as the route writes it. */
|
||||
function localAdopt(socketPath: string, targetSession: string): SessionAdopt {
|
||||
return { location: 'local', socketPath, targetSession, viewSession: 'codeman-view-00000000' };
|
||||
}
|
||||
|
||||
describe('a successful adoption', () => {
|
||||
/** A candidate whose cwd is BOTH unsafe for SAFE_PATH_PATTERN and not on this host. */
|
||||
const CANDIDATE = {
|
||||
id: 'cand-1',
|
||||
location: 'local' as const,
|
||||
socketPath: '/tmp/tmux-0/default',
|
||||
sessionName: 'work',
|
||||
mode: 'claude' as const,
|
||||
workingDir: '/home/them/Program Files (x86)/c++',
|
||||
command: 'claude',
|
||||
panePid: 4242,
|
||||
paneCurrentCommand: 'node',
|
||||
createdAt: 1,
|
||||
windows: 1,
|
||||
attached: false,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
discoverForeignSessions.mockResolvedValue({ sessions: [CANDIDATE], notes: [] });
|
||||
});
|
||||
|
||||
it('gives the wrapper a neutral LOCAL workingDir, never the foreign pane\u2019s cwd', async () => {
|
||||
// That cwd carries `+`, spaces and parentheses, so using it would make
|
||||
// createSession throw and the tab would never start; and when the candidate
|
||||
// is a container or ssh pane it is not a path on this host at all, which is
|
||||
// what sent the boot hook sweep into someone else's repo.
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'cand-1' } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(ctx.addSession).toHaveBeenCalledTimes(1);
|
||||
const created = ctx.addSession.mock.calls[0][0] as unknown as {
|
||||
workingDir: string;
|
||||
adopt?: { paneCurrentPath?: string; targetSession?: string; viewSession?: string };
|
||||
};
|
||||
expect(created.workingDir).toBe('/tmp');
|
||||
expect(created.workingDir).not.toBe(CANDIDATE.workingDir);
|
||||
// The foreign cwd survives for display only.
|
||||
expect(created.adopt?.paneCurrentPath).toBe(CANDIDATE.workingDir);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('reuses the existing wrapper rather than making a second one for the same target', async () => {
|
||||
// Keyed on the target and not on our opaque candidate id: a wrapper restored
|
||||
// after a server restart does not carry that id.
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
ctx.sessions.set('wrapper-1', ctx._session);
|
||||
ctx._session.adopt = localAdopt(CANDIDATE.socketPath, CANDIDATE.sessionName);
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'cand-1' } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().alreadyAdopted).toBe(true);
|
||||
expect(ctx.addSession).not.toHaveBeenCalled();
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('sees a wrapper whose tab has not started yet, which has no mux record to find', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
const first = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'cand-1' } });
|
||||
expect(first.json().adopted).toBe(true);
|
||||
expect(ctx.mux.getSessions()).toEqual([]);
|
||||
const second = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'cand-1' } });
|
||||
expect(second.json().alreadyAdopted).toBe(true);
|
||||
expect(ctx.addSession).toHaveBeenCalledTimes(1);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('refuses a second adopt of a target whose wrapper is still being created', async () => {
|
||||
// Two devices on one row: both pass the live-session check, because the first
|
||||
// is parked on the layout lock and not yet in the map.
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
const add = ctx.addSession.getMockImplementation()!;
|
||||
let release!: () => void;
|
||||
const held = new Promise<void>((resolve) => (release = resolve));
|
||||
ctx.addSession.mockImplementationOnce(async (s: never) => {
|
||||
await held;
|
||||
return add(s);
|
||||
});
|
||||
const first = app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'cand-1' } });
|
||||
await vi.waitFor(() => expect(ctx.addSession).toHaveBeenCalledTimes(1));
|
||||
const second = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'cand-1' } });
|
||||
expect(second.json().success).toBe(false);
|
||||
expect(second.json().errorCode).toBe('SESSION_BUSY');
|
||||
release();
|
||||
expect((await first).json().adopted).toBe(true);
|
||||
expect(ctx.addSession).toHaveBeenCalledTimes(1);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('says "could not reach it" rather than "gone" when discovery left a note', async () => {
|
||||
// On a flaky link the session is alive and sitting right there; reporting
|
||||
// it as deleted is the wrong answer, not just an unhelpful one.
|
||||
discoverForeignSessions.mockResolvedValue({ sessions: [], notes: ['ssh box: connection timed out'] });
|
||||
const { app } = await createRouteTestHarness(registerSessionRoutes);
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'cand-1' } });
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().error).toMatch(/Could not reach it/);
|
||||
expect(res.json().error).toContain('connection timed out');
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('carries the adopt metadata that a restart needs to rebuild the command', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'cand-1' } });
|
||||
const created = ctx.addSession.mock.calls[0][0] as unknown as {
|
||||
adopt?: { socketPath?: string; targetSession?: string; viewSession?: string };
|
||||
isAdopted?: boolean;
|
||||
};
|
||||
expect(created.isAdopted).toBe(true);
|
||||
expect(created.adopt?.socketPath).toBe(CANDIDATE.socketPath);
|
||||
expect(created.adopt?.targetSession).toBe(CANDIDATE.sessionName);
|
||||
// Derived from the Codeman session id, so it is provably ours to kill.
|
||||
expect(created.adopt?.viewSession).toMatch(/^codeman-view-/);
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('same-named sessions in different locations', () => {
|
||||
// Containers commonly run tmux as root with default names, so `0` in two
|
||||
// containers is the same (socket, name) pair, and the same goes for this machine
|
||||
// and an ssh host with the same uid.
|
||||
const SHARED = {
|
||||
socketPath: '/tmp/tmux-0/default',
|
||||
sessionName: '0',
|
||||
mode: 'shell' as const,
|
||||
workingDir: '/workspace',
|
||||
command: 'bash',
|
||||
createdAt: 1,
|
||||
windows: 1,
|
||||
attached: false,
|
||||
};
|
||||
const IN_A = { ...SHARED, id: 'in-a', location: 'docker' as const, hostId: 'h1', containerName: 'box-a' };
|
||||
const IN_B = { ...SHARED, id: 'in-b', location: 'docker' as const, hostId: 'h1', containerName: 'box-b' };
|
||||
const OTHER_ENGINE = { ...SHARED, id: 'in-c', location: 'docker' as const, hostId: 'h2', containerName: 'box-a' };
|
||||
const ON_THIS_HOST = { ...SHARED, id: 'here', location: 'local' as const };
|
||||
|
||||
beforeEach(() => {
|
||||
discoverForeignSessions.mockResolvedValue({ sessions: [IN_A, IN_B, OTHER_ENGINE, ON_THIS_HOST], notes: [] });
|
||||
});
|
||||
|
||||
it('gives each location its own key, and a wrapper the key of its candidate', () => {
|
||||
const keys = [IN_A, IN_B, OTHER_ENGINE, ON_THIS_HOST].map(foreignTargetKey);
|
||||
expect(new Set(keys).size).toBe(4);
|
||||
expect(
|
||||
foreignTargetKey(
|
||||
adoptTargetIdentity({
|
||||
...localAdopt(SHARED.socketPath, SHARED.sessionName),
|
||||
location: 'docker',
|
||||
docker: { hostId: 'h1', label: 'one', engine: 'docker', containerName: 'box-b' },
|
||||
})
|
||||
)
|
||||
).toBe(foreignTargetKey(IN_B));
|
||||
});
|
||||
|
||||
it('adopting one never returns the tab of another', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
const a = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'in-a', docker: true } });
|
||||
const b = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'in-b', docker: true } });
|
||||
const local = await app.inject({ method: 'POST', url: '/api/sessions/adopt', payload: { id: 'here' } });
|
||||
for (const res of [a, b, local]) expect(res.json().adopted).toBe(true);
|
||||
expect(ctx.addSession).toHaveBeenCalledTimes(3);
|
||||
const ids = [a, b, local].map((res) => res.json().session.id);
|
||||
expect(new Set(ids).size).toBe(3);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('marks only the row that is really open as open', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerMuxRoutes);
|
||||
ctx.sessions.set('wrapper-b', {
|
||||
id: 'wrapper-b',
|
||||
adopt: {
|
||||
...localAdopt(SHARED.socketPath, SHARED.sessionName),
|
||||
location: 'docker',
|
||||
docker: { hostId: 'h1', label: 'one', engine: 'docker', containerName: 'box-b' },
|
||||
},
|
||||
} as never);
|
||||
const res = await app.inject({ method: 'GET', url: '/api/mux/foreign' });
|
||||
const adoptedBy = Object.fromEntries(
|
||||
(res.json().sessions as { id: string; adoptedBy?: string }[]).map((s) => [s.id, s.adoptedBy])
|
||||
);
|
||||
expect(adoptedBy).toEqual({ 'in-a': undefined, 'in-b': 'wrapper-b', 'in-c': undefined, here: undefined });
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('an adopted session has no workspace of ours', () => {
|
||||
// Its `workingDir` is the neutral `/tmp`, which local-looking code would take for
|
||||
// the session's folder: uploads landed there and the tab's close deleted them, and
|
||||
// a Git panel or fetch ran git on whatever sat there. Each refusal is paired with a
|
||||
// plain session, or a broken route would pass it too.
|
||||
const adopted = (s: { isAdopted: boolean; adopt?: SessionAdopt }) => {
|
||||
s.isAdopted = true;
|
||||
s.adopt = localAdopt('/tmp/tmux-1000/default', 'work');
|
||||
};
|
||||
|
||||
it('refuses a prompt upload before touching disk', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
adopted(ctx._session);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${ctx._sessionId}/paste-image`,
|
||||
headers: { 'x-codeman-csrf': '1' },
|
||||
});
|
||||
expect(res.statusCode).toBe(400);
|
||||
expect(res.json().error).toMatch(/adopted/);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('refuses the image watcher, and leaves it alone being switched off', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
adopted(ctx._session);
|
||||
const post = (enabled: boolean) =>
|
||||
app.inject({ method: 'POST', url: `/api/sessions/${ctx._sessionId}/image-watcher`, payload: { enabled } });
|
||||
expect((await post(true)).json().success).toBe(false);
|
||||
expect((await post(false)).json().success).toBe(true);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('refuses the per-session git fetch settings', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
adopted(ctx._session);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${ctx._sessionId}/git-fetch-settings`,
|
||||
payload: { enabled: true },
|
||||
});
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().error).toMatch(/adopted/);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('refuses a custom model, which restarts the CLI in the pane', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
adopted(ctx._session);
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${ctx._sessionId}/custom-model`,
|
||||
payload: { clear: true },
|
||||
});
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().error).toMatch(/adopted/);
|
||||
await app.close();
|
||||
});
|
||||
|
||||
it('answers unsupported on the git routes, running no git', async () => {
|
||||
const git = vi.fn(async () => ({ stdout: '', stderr: '' }));
|
||||
const { app, ctx } = await createRouteTestHarness((a, c) =>
|
||||
registerGitStatusRoutes(a, c, git as never, async () => [])
|
||||
);
|
||||
adopted(ctx._session);
|
||||
const status = await app.inject({ method: 'GET', url: `/api/sessions/${ctx._sessionId}/git-status` });
|
||||
expect(status.json()).toMatchObject({ success: true, data: { state: 'unsupported', reason: 'adopted' } });
|
||||
const fetch = await app.inject({ method: 'POST', url: `/api/sessions/${ctx._sessionId}/git-fetch` });
|
||||
expect(fetch.json()).toMatchObject({ success: true, data: { state: 'unsupported', reason: 'adopted' } });
|
||||
const diff = await app.inject({
|
||||
method: 'GET',
|
||||
url: `/api/sessions/${ctx._sessionId}/git-diff?repo=x&path=y&kind=z`,
|
||||
});
|
||||
expect(diff.statusCode).toBe(400);
|
||||
expect(git).not.toHaveBeenCalled();
|
||||
await app.close();
|
||||
});
|
||||
|
||||
describe('last-response', () => {
|
||||
let project: string;
|
||||
beforeEach(() => {
|
||||
project = join(process.env.HOME!, '.claude', 'projects', '-tmp');
|
||||
mkdirSync(project, { recursive: true });
|
||||
});
|
||||
afterEach(() => {
|
||||
rmSync(project, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('never pairs a transcript by the wrapper folder or the id we launched nothing with', async () => {
|
||||
const { app, ctx } = await createRouteTestHarness(registerSessionRoutes);
|
||||
(ctx._session as unknown as { mode: string }).mode = 'claude';
|
||||
writeFileSync(
|
||||
join(project, `${ctx._sessionId}.jsonl`),
|
||||
JSON.stringify({
|
||||
type: 'assistant',
|
||||
timestamp: '2026-07-21T00:00:01Z',
|
||||
message: { content: [{ type: 'text', text: 'an answer from another conversation' }] },
|
||||
})
|
||||
);
|
||||
const read = async () =>
|
||||
(await app.inject({ method: 'GET', url: `/api/sessions/${ctx._sessionId}/last-response` })).json();
|
||||
expect((await read()).text).toBe('an answer from another conversation');
|
||||
adopted(ctx._session);
|
||||
expect((await read()).text).toBe('');
|
||||
await app.close();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -9,8 +9,10 @@ import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { registerGitStatusRoutes } from '../../src/web/routes/git-status-routes.js';
|
||||
import { defaultDockerWorkspaces, registerGitStatusRoutes } from '../../src/web/routes/git-status-routes.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { clearGitStatusCache, runGit, type GitRunner } from '../../src/git-workspace-status.js';
|
||||
import { clearGitFetchLane, fetchWorkspaceOnce } from '../../src/git-fetch.js';
|
||||
|
||||
const ENV = {
|
||||
...process.env,
|
||||
@@ -29,14 +31,18 @@ let dir: string;
|
||||
let session: Record<string, unknown>;
|
||||
|
||||
async function setup(
|
||||
opts: { git?: GitRunner; authUser?: { username: string; role: 'admin' | 'user' }; dockerWorkspaces?: string[] } = {}
|
||||
opts: {
|
||||
git?: GitRunner;
|
||||
authUser?: { username: string; role: 'admin' | 'user' };
|
||||
/** A fixed list, a reader of the test's own, or `'real'` for the route's default (the data dir's file). */
|
||||
dockerWorkspaces?: string[] | (() => Promise<string[]>) | 'real';
|
||||
} = {}
|
||||
) {
|
||||
const h = await createRouteTestHarness(
|
||||
(app, ctx) => registerGitStatusRoutes(app, ctx, opts.git, async () => opts.dockerWorkspaces ?? []),
|
||||
{
|
||||
authUser: opts.authUser,
|
||||
}
|
||||
);
|
||||
const docker = opts.dockerWorkspaces;
|
||||
const reader = docker === 'real' ? undefined : typeof docker === 'function' ? docker : async () => docker ?? [];
|
||||
const h = await createRouteTestHarness((app, ctx) => registerGitStatusRoutes(app, ctx, opts.git, reader), {
|
||||
authUser: opts.authUser,
|
||||
});
|
||||
session = h.ctx._session as unknown as Record<string, unknown>;
|
||||
session.workingDir = dir;
|
||||
return h;
|
||||
@@ -44,6 +50,8 @@ async function setup(
|
||||
|
||||
beforeEach(() => {
|
||||
clearGitStatusCache();
|
||||
// The fetch lane is module state: a run left in it by the previous test would be joined by the next one.
|
||||
clearGitFetchLane();
|
||||
dir = mkdtempSync(join(tmpdir(), 'git-status-route-'));
|
||||
});
|
||||
afterEach(() => {
|
||||
@@ -353,6 +361,313 @@ describe('GET /api/sessions/:id/git-status limits', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/sessions/:id/git-fetch', () => {
|
||||
/** Records what each repository was asked to do, and lets real git answer the rest. */
|
||||
function recordingRunner() {
|
||||
const calls: Array<[string, string[]]> = [];
|
||||
const seenTimeouts: Array<number | undefined> = [];
|
||||
const runner: GitRunner = async (cwd, args, opts) => {
|
||||
calls.push([cwd, args]);
|
||||
seenTimeouts.push(opts?.timeoutMs);
|
||||
return execFileSyncGit(cwd, args);
|
||||
};
|
||||
return { calls, seenTimeouts, runner, fetches: () => calls.filter(([, args]) => args[0] === 'fetch') };
|
||||
}
|
||||
|
||||
it('runs one fetch per repository the window would show, in the session working directory', async () => {
|
||||
for (const name of ['api', 'web']) {
|
||||
mkdirSync(join(dir, name));
|
||||
git(join(dir, name), 'init', '-q', '-b', 'main');
|
||||
}
|
||||
const { calls, fetches, runner } = recordingRunner();
|
||||
const { app } = await setup({ git: runner });
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = res.json().data;
|
||||
expect(data.state).toBe('ok');
|
||||
expect(data.repos.map((r: { name: string; path: string }) => [r.name, r.path])).toEqual([
|
||||
['api', 'api'],
|
||||
['web', 'web'],
|
||||
]);
|
||||
expect(data.repos.every((r: { ok: boolean }) => r.ok)).toBe(true);
|
||||
// A bounded run does not promise which repository starts first, so compare the set.
|
||||
expect(fetches().sort()).toEqual([
|
||||
[join(dir, 'api'), ['fetch', '--quiet']],
|
||||
[join(dir, 'web'), ['fetch', '--quiet']],
|
||||
]);
|
||||
// Every repository git was asked to touch sits under the session folder, and under nothing else.
|
||||
for (const [cwd] of calls) expect(cwd.startsWith(dir)).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps a repository it could not fetch, with its reason, and says which ones it fetched', async () => {
|
||||
for (const name of ['ok', 'private']) {
|
||||
mkdirSync(join(dir, name));
|
||||
git(join(dir, name), 'init', '-q', '-b', 'main');
|
||||
}
|
||||
const { fetches, runner } = recordingRunner();
|
||||
const injected: GitRunner = async (cwd, args, opts) => {
|
||||
const recorded = runner(cwd, args, opts); // records the call before deciding what git would have said
|
||||
if (args[0] === 'fetch' && cwd === join(dir, 'private')) {
|
||||
throw Object.assign(new Error('Command failed'), {
|
||||
stderr: "fatal: could not read Username for 'https://github.com': terminal prompts disabled",
|
||||
});
|
||||
}
|
||||
return recorded;
|
||||
};
|
||||
const { app } = await setup({ git: injected });
|
||||
const data = (await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' })).json().data;
|
||||
const priv = data.repos.find((r: { name: string }) => r.name === 'private');
|
||||
expect(priv?.ok).toBe(false);
|
||||
expect(priv?.failure?.code).toBe('AUTH_REQUIRED');
|
||||
expect(data.repos.find((r: { name: string }) => r.name === 'ok')?.ok).toBe(true);
|
||||
// Both repositories are still in the list, so both were attempted: a failure does not cancel the run.
|
||||
expect(fetches()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('redacts credentials git may have echoed back before the failure reaches the client', async () => {
|
||||
git(dir, 'init', '-q', '-b', 'main');
|
||||
// Only the fetch is faked: the resolver still needs its own `rev-parse` to find the repository at all.
|
||||
const runner: GitRunner = async (cwd, args) => {
|
||||
if (args[0] === 'fetch') {
|
||||
throw Object.assign(new Error('Command failed'), {
|
||||
stderr: "fatal: unable to access 'https://bob:ghp_secret@github.com/x.git/'\u001b[31m",
|
||||
});
|
||||
}
|
||||
return execFileSyncGit(cwd, args);
|
||||
};
|
||||
const { app } = await setup({ git: runner });
|
||||
const data = (await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' })).json().data;
|
||||
expect(data.state).toBe('ok');
|
||||
expect(data.repos[0].failure.stderr).toBe("fatal: unable to access 'https://***:***@github.com/x.git/'[31m");
|
||||
});
|
||||
|
||||
it.each([
|
||||
['remote', { host: 'h', user: 'u' }],
|
||||
['docker', { container: 'c' }],
|
||||
])('does not run git for a %s session and says it is unsupported', async (kind, value) => {
|
||||
git(dir, 'init', '-q', '-b', 'main');
|
||||
const { calls, fetches, runner } = recordingRunner();
|
||||
const { app } = await setup({ git: runner });
|
||||
session[kind] = value;
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data).toMatchObject({ state: 'unsupported', reason: kind });
|
||||
expect(fetches()).toEqual([]);
|
||||
expect(calls).toEqual([]); // the resolver never ran either: the refusal comes before any git
|
||||
});
|
||||
|
||||
it('refuses a repository inside a Docker case workspace before any git runs', async () => {
|
||||
git(dir, 'init', '-q', '-b', 'main');
|
||||
const { calls, fetches, runner } = recordingRunner();
|
||||
const { app } = await setup({ git: runner, dockerWorkspaces: [realpathSync(dir)] });
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
expect(res.json().data).toMatchObject({ state: 'unsupported', reason: 'docker' });
|
||||
expect(fetches()).toEqual([]);
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
/**
|
||||
* docker-cases.json is rewritten in place (truncate, then write), so a read can land on an empty or
|
||||
* half-written file. Read as "no Docker workspaces", a fetch would run git, and with it the repository's
|
||||
* hooks, inside a folder a container can write to.
|
||||
*/
|
||||
it('fetches nothing when the Docker case list cannot be read, and answers a failed run', async () => {
|
||||
git(dir, 'init', '-q', '-b', 'main');
|
||||
const { calls, runner } = recordingRunner();
|
||||
const { app, ctx } = await setup({
|
||||
git: runner,
|
||||
dockerWorkspaces: async () => {
|
||||
throw new Error('docker-cases.json is not a valid JSON array');
|
||||
},
|
||||
});
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().data).toMatchObject({ state: 'error', repos: [] });
|
||||
expect(res.json().data.error).toMatch(/Docker case list/);
|
||||
expect(calls).toEqual([]); // not even the resolver's rev-parse
|
||||
expect(session.gitFetch).toMatchObject({ trigger: 'click', state: 'error', repos: 0, failed: 0 });
|
||||
expect(ctx.broadcast).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reads the real Docker case list strictly for a fetch, and leaves the status route as it was', async () => {
|
||||
git(dir, 'init', '-q', '-b', 'main');
|
||||
mkdirSync(getDataDir(), { recursive: true });
|
||||
const listPath = join(getDataDir(), 'docker-cases.json');
|
||||
try {
|
||||
writeFileSync(listPath, '[{"name":"c","hostWorkspacePath":"/x"');
|
||||
await expect(defaultDockerWorkspaces()).rejects.toThrow(/not a valid JSON array/);
|
||||
const { calls, fetches, runner } = recordingRunner();
|
||||
const { app } = await setup({ git: runner, dockerWorkspaces: 'real' });
|
||||
const fetched = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
expect(fetched.json().data.state).toBe('error');
|
||||
expect(calls).toEqual([]);
|
||||
// The read-only status route still reads an unreadable list as none, as it always has.
|
||||
const status = await app.inject({ method: 'GET', url: '/api/sessions/test-session-1/git-status' });
|
||||
expect(status.json().data.state).toBe('ok');
|
||||
expect(fetches()).toEqual([]);
|
||||
|
||||
// A readable list that names this folder refuses the fetch as a Docker workspace, so the strict
|
||||
// reader is the one the route really reads.
|
||||
writeFileSync(listPath, JSON.stringify([{ name: 'c', hostWorkspacePath: realpathSync(dir) }]));
|
||||
expect(await defaultDockerWorkspaces()).toEqual([realpathSync(dir)]);
|
||||
const refused = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
expect(refused.json().data).toMatchObject({ state: 'unsupported', reason: 'docker' });
|
||||
expect(fetches()).toEqual([]);
|
||||
} finally {
|
||||
rmSync(listPath, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('answers not-a-repo for a folder that is not a repository, running no fetch', async () => {
|
||||
const { fetches, runner } = recordingRunner();
|
||||
const { app } = await setup({ git: runner });
|
||||
const data = (await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' })).json().data;
|
||||
expect(data.state).toBe('not-a-repo');
|
||||
// The resolver looked once and found nothing, so nothing was fetched, and it never guessed a repository.
|
||||
expect(fetches()).toEqual([]);
|
||||
});
|
||||
|
||||
it("publishes what the click got as the session's own fetch state, naming the trigger the user asked for", async () => {
|
||||
git(dir, 'init', '-q', '-b', 'main');
|
||||
const { runner } = recordingRunner();
|
||||
const { app, ctx } = await setup({ git: runner });
|
||||
const res = await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
// The response body is one tab's copy of the run; the state is what every other tab open on the same
|
||||
// folder sees, and a number the user did not ask for has to read differently from one they did.
|
||||
expect(session.gitFetch).toMatchObject({ trigger: 'click', state: 'ok', repos: 1, failed: 0 });
|
||||
expect(ctx.persistSessionState).toHaveBeenCalled();
|
||||
expect(ctx.broadcast).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('joins a run already going for the same folder instead of starting a second git process in the same clone', async () => {
|
||||
git(dir, 'init', '-q', '-b', 'main');
|
||||
let releaseRun = () => {};
|
||||
const held = new Promise<void>((resolve) => (releaseRun = resolve));
|
||||
let running = () => {};
|
||||
const runStarted = new Promise<void>((resolve) => (running = resolve));
|
||||
const fetches: string[] = [];
|
||||
const runner: GitRunner = async (cwd, args) => {
|
||||
if (args[0] === 'fetch') {
|
||||
fetches.push(cwd);
|
||||
running();
|
||||
await held;
|
||||
}
|
||||
return execFileSyncGit(cwd, args);
|
||||
};
|
||||
const { app } = await setup({ git: runner });
|
||||
|
||||
const first = app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
await runStarted; // the run is going, and still going
|
||||
// A click from another tab open on the same clone. Two fetches there would collide on git's ref lock, so
|
||||
// this one joins the run already going rather than starting its own.
|
||||
const second = app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
// Assert the join BEFORE releasing the run: the lane entry goes away when the run finishes, so releasing
|
||||
// first would let the run complete before this request reached the lane, and it would then be entitled to
|
||||
// start its own fetch: a test that passes for the wrong reason. One tick of the loop is enough for both
|
||||
// handlers to reach the lane while the run is still held open.
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
expect(fetches).toHaveLength(1); // one run, and the second request is waiting on it, not working
|
||||
|
||||
releaseRun();
|
||||
const a = (await first).json().data;
|
||||
const b = (await second).json().data;
|
||||
expect(b).toEqual(a); // both tabs get the same run's answer, not a partial one
|
||||
});
|
||||
|
||||
it('publishes the trigger of the run the click joined, because a click that fetched nothing cannot report itself as the fetch', async () => {
|
||||
git(dir, 'init', '-q', '-b', 'main');
|
||||
let releaseRun = () => {};
|
||||
const held = new Promise<void>((resolve) => (releaseRun = resolve));
|
||||
let running = () => {};
|
||||
const runStarted = new Promise<void>((resolve) => (running = resolve));
|
||||
const fetches: string[] = [];
|
||||
const runner: GitRunner = async (cwd, args) => {
|
||||
if (args[0] === 'fetch') {
|
||||
fetches.push(cwd);
|
||||
running();
|
||||
await held;
|
||||
}
|
||||
return execFileSyncGit(cwd, args);
|
||||
};
|
||||
const { app, ctx } = await setup({ git: runner });
|
||||
|
||||
// The interval tick got to this clone first. The click joins it, so the row the other tabs see has to name
|
||||
// the interval: the user clicked, but nothing this click did was a fetch. The request is left open, not
|
||||
// awaited: awaiting it here would wait on the run this test is holding, and the test would wait on itself.
|
||||
const intervalRun = fetchWorkspaceOnce(dir, { git: runner }, 'interval');
|
||||
await runStarted;
|
||||
const res = app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' });
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
releaseRun();
|
||||
const run = await intervalRun;
|
||||
const body = (await res).json().data;
|
||||
expect(body).toEqual(run.report); // the run it joined, not a partial answer of its own
|
||||
// Asserted after the run, so this can only pass if the click reached the lane and joined: a click that had
|
||||
// started its own fetch would make this two, and would have nothing to call the interval.
|
||||
expect(fetches).toHaveLength(1);
|
||||
expect(session.gitFetch).toMatchObject({ trigger: 'interval', state: 'ok', repos: 1, failed: 0 });
|
||||
expect(ctx.broadcast).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('404s an unknown session, running no fetch', async () => {
|
||||
const { calls, fetches, runner } = recordingRunner();
|
||||
const { app } = await setup({ git: runner });
|
||||
expect((await app.inject({ method: 'POST', url: '/api/sessions/nope/git-fetch' })).statusCode).toBe(404);
|
||||
expect(fetches()).toEqual([]);
|
||||
expect(calls).toEqual([]);
|
||||
});
|
||||
|
||||
it('multi-user: another user’s session is not found, and no fetch runs', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
git(dir, 'init', '-q', '-b', 'main');
|
||||
const { fetches, runner } = recordingRunner();
|
||||
const { app } = await setup({ git: runner, authUser: { username: 'bob', role: 'user' } });
|
||||
session.owner = 'alice';
|
||||
expect((await app.inject({ method: 'POST', url: '/api/sessions/test-session-1/git-fetch' })).statusCode).toBe(404);
|
||||
expect(fetches()).toEqual([]);
|
||||
});
|
||||
|
||||
it('honours maxRepos and timeout (seconds) for a fetch too, clamped, and reports the limit it used', async () => {
|
||||
for (const n of ['a', 'b', 'c']) {
|
||||
mkdirSync(join(dir, n));
|
||||
git(join(dir, n), 'init', '-q', '-b', 'main');
|
||||
}
|
||||
const { seenTimeouts, fetches, runner } = recordingRunner();
|
||||
const { app } = await setup({ git: runner });
|
||||
const post = async (query: string) => {
|
||||
const res = await app.inject({ method: 'POST', url: `/api/sessions/test-session-1/git-fetch${query}` });
|
||||
expect(res.statusCode).toBe(200);
|
||||
return res.json().data as { repoLimit: number; repos: Array<{ name: string }> };
|
||||
};
|
||||
const fetchCount = () => fetches().length;
|
||||
const ran = async (query: string, expected: number) => {
|
||||
const before = fetchCount();
|
||||
const data = await post(query);
|
||||
expect(fetchCount() - before).toBe(expected);
|
||||
return data;
|
||||
};
|
||||
|
||||
const limited = await ran('?maxRepos=2&timeout=7', 2);
|
||||
expect(limited.repos.map((r) => r.name)).toEqual(['a', 'b']);
|
||||
expect(limited).toMatchObject({ reposTruncated: true, repoLimit: 2 }); // the window has to say three were found
|
||||
expect(new Set(seenTimeouts)).toEqual(new Set([7000]));
|
||||
|
||||
const wild = await ran('?maxRepos=9999&timeout=1', 3);
|
||||
expect(wild.repoLimit).toBe(50); // clamped to MAX_REPOS_LIMIT, so one request cannot scan the whole disk
|
||||
expect(seenTimeouts.at(-1)).toBe(5000);
|
||||
|
||||
const junk = await ran('?maxRepos=abc&timeout=xyz', 3);
|
||||
expect(junk.repoLimit).toBe(12);
|
||||
expect(seenTimeouts.at(-1)).toBe(30_000);
|
||||
|
||||
// A repeated key reaches the route as an array: it means "default", never a 500.
|
||||
await ran('?timeout=5&timeout=6', 3);
|
||||
expect(seenTimeouts.at(-1)).toBe(30_000);
|
||||
});
|
||||
});
|
||||
|
||||
function execFileSyncGit(cwd: string, args: string[]): Promise<string> {
|
||||
return Promise.resolve(execFileSync('git', ['--no-optional-locks', ...args], { cwd, env: ENV, encoding: 'utf8' }));
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
|
||||
import { approvalInbox } from '../../src/web/approval-inbox.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { ApiErrorCode, httpStatusForErrorCode } from '../../src/types.js';
|
||||
import { registerHookEventRoutes } from '../../src/web/routes/hook-event-routes.js';
|
||||
@@ -98,6 +99,103 @@ describe('hook-event-routes', () => {
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* The prompt-cache keep-warm's own turn (prompt-cache-keepwarm.ts) ends with the same stop
|
||||
* hook and idle prompt as a real one. While the session marks the turn as its keep-alive,
|
||||
* both open pre-acknowledged: the broadcast says why, and nothing is pushed.
|
||||
*/
|
||||
it('opens the stop and idle prompt of a keep-alive turn pre-acknowledged and pushes nothing', async () => {
|
||||
harness.ctx._session.keepAliveTurnActive = true;
|
||||
for (const event of ['stop', 'idle_prompt']) {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/hook-event',
|
||||
payload: { event, sessionId: harness.ctx._sessionId, data: null },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(harness.ctx.broadcast).toHaveBeenCalledWith(
|
||||
`hook:${event}`,
|
||||
expect.objectContaining({ sessionId: harness.ctx._sessionId, acknowledgedReason: 'cache keep-alive' })
|
||||
);
|
||||
}
|
||||
expect(harness.ctx.sendPushNotifications).not.toHaveBeenCalled();
|
||||
// The inbox item is what a reload seeds tab alerts from, so it must open acknowledged too.
|
||||
const item = approvalInbox.getForSession(harness.ctx._sessionId);
|
||||
approvalInbox.resolveForSession(harness.ctx._sessionId, 'dismissed');
|
||||
expect(item?.acknowledgedReason).toBe('cache keep-alive');
|
||||
// acknowledgedAt is what approvals-ui.js reads to skip the alert on a reload.
|
||||
expect(item?.acknowledgedAt).toBe(item?.createdAt);
|
||||
});
|
||||
|
||||
/**
|
||||
* Only a human spends an idle alert (CLAUDE.md, Approvals Inbox). A keep-alive turn that
|
||||
* starts while an idle item is pending must leave that item exactly as it found it: its stop
|
||||
* does not resolve it, and its idle prompt does not replace it, so an unseen alert stays
|
||||
* unseen (and pushes nothing a second time) and one a person looked at keeps saying so.
|
||||
*/
|
||||
it.each([
|
||||
{ seen: false, label: 'an unseen' },
|
||||
{ seen: true, label: 'a seen' },
|
||||
])('leaves $label idle item pending through a keep-alive turn', async ({ seen }) => {
|
||||
const sessionId = harness.ctx._sessionId;
|
||||
const hook = (event: string) =>
|
||||
harness.app.inject({ method: 'POST', url: '/api/hook-event', payload: { event, sessionId, data: null } });
|
||||
await hook('idle_prompt');
|
||||
const before = approvalInbox.getForSession(sessionId);
|
||||
expect(before?.acknowledgedAt).toBeUndefined();
|
||||
if (seen) approvalInbox.acknowledge(sessionId);
|
||||
const acknowledgedAt = before?.acknowledgedAt;
|
||||
harness.ctx.sendPushNotifications.mockClear();
|
||||
harness.ctx.broadcast.mockClear();
|
||||
|
||||
harness.ctx._session.keepAliveTurnActive = true;
|
||||
await hook('stop');
|
||||
await hook('idle_prompt');
|
||||
|
||||
const after = approvalInbox.getForSession(sessionId);
|
||||
approvalInbox.resolveForSession(sessionId, 'dismissed');
|
||||
expect(after?.id).toBe(before?.id);
|
||||
expect(after?.acknowledgedAt).toBe(acknowledgedAt);
|
||||
expect(after?.acknowledgedReason).toBeUndefined();
|
||||
expect(harness.ctx.sendPushNotifications).not.toHaveBeenCalled();
|
||||
// The page's _onHookStop and _onHookIdlePrompt return on the reason, leaving the tab alert.
|
||||
for (const event of ['stop', 'idle_prompt']) {
|
||||
expect(harness.ctx.broadcast).toHaveBeenCalledWith(
|
||||
`hook:${event}`,
|
||||
expect.objectContaining({ acknowledgedReason: 'cache keep-alive' })
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it("a keep-alive turn's idle prompt ends the keep-alive window, its stop does not", async () => {
|
||||
const sessionId = harness.ctx._sessionId;
|
||||
const hook = (event: string) =>
|
||||
harness.app.inject({ method: 'POST', url: '/api/hook-event', payload: { event, sessionId, data: null } });
|
||||
harness.ctx._session.keepAliveTurnActive = true;
|
||||
await hook('stop');
|
||||
expect(harness.ctx._session.keepAliveTurnActive).toBe(true);
|
||||
await hook('idle_prompt');
|
||||
approvalInbox.resolveForSession(sessionId, 'dismissed');
|
||||
expect(harness.ctx._session.keepAliveTurnActive).toBe(false);
|
||||
});
|
||||
|
||||
it("a keep-alive turn's stop still resolves a pending permission dialog", async () => {
|
||||
const sessionId = harness.ctx._sessionId;
|
||||
await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/hook-event',
|
||||
payload: { event: 'permission_prompt', sessionId, data: null },
|
||||
});
|
||||
expect(approvalInbox.getForSession(sessionId)?.kind).toBe('permission');
|
||||
harness.ctx._session.keepAliveTurnActive = true;
|
||||
await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/hook-event',
|
||||
payload: { event: 'stop', sessionId, data: null },
|
||||
});
|
||||
expect(approvalInbox.getForSession(sessionId)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('sends push notifications for hook events', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
@@ -144,6 +242,27 @@ describe('hook-event-routes', () => {
|
||||
expect(harness.ctx.persistSessionState).toHaveBeenCalledWith(session);
|
||||
});
|
||||
|
||||
/**
|
||||
* The hook's prompt text is what tells a person typing in an attached tmux client apart
|
||||
* from the prompt-cache keep-alive (Session.markPromptSubmitted ends the keep-alive window
|
||||
* for anything but the nudge), so the route must hand it over, and nothing else.
|
||||
*/
|
||||
it("hands the prompt_submitted hook's prompt text to the session", async () => {
|
||||
const session = harness.ctx._session;
|
||||
for (const data of [
|
||||
{ session_id: 'conv-1', prompt: 'fix the login bug' },
|
||||
{ session_id: 'conv-1', prompt: 42 },
|
||||
{ session_id: 'conv-1' },
|
||||
]) {
|
||||
await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/hook-event',
|
||||
payload: { event: 'prompt_submitted', sessionId: harness.ctx._sessionId, data },
|
||||
});
|
||||
}
|
||||
expect(session.submittedPrompts).toEqual(['fix the login bug', undefined, undefined]);
|
||||
});
|
||||
|
||||
it('records a /clear successor in the chain and persists it, without duplicating a repeat', async () => {
|
||||
const session = harness.ctx._session;
|
||||
const submit = async (conversationId: string) =>
|
||||
@@ -308,6 +427,36 @@ describe('hook-event-routes', () => {
|
||||
expect(mockTracker.recordHookEvent).toHaveBeenCalledWith('stop', expect.any(Object));
|
||||
});
|
||||
|
||||
/**
|
||||
* The run summary files every `stop` as a warning, and the Away digest lists warnings under
|
||||
* Needs Attention, so a keep-alive turn's hooks would add a row there (and to the session's
|
||||
* Summary timeline) for every nudge. They are Codeman's own turn, not the agent's.
|
||||
*/
|
||||
it("keeps a keep-alive turn's stop and idle prompt out of the run summary", async () => {
|
||||
const sessionId = harness.ctx._sessionId;
|
||||
const mockTracker = { recordHookEvent: vi.fn() };
|
||||
harness.ctx.runSummaryTrackers.set(sessionId, mockTracker as never);
|
||||
harness.ctx._session.keepAliveTurnActive = true;
|
||||
for (const event of ['stop', 'idle_prompt']) {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/hook-event',
|
||||
payload: { event, sessionId, data: null },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
}
|
||||
approvalInbox.resolveForSession(sessionId, 'dismissed');
|
||||
expect(mockTracker.recordHookEvent).not.toHaveBeenCalled();
|
||||
|
||||
// The next real turn is recorded as before.
|
||||
await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/hook-event',
|
||||
payload: { event: 'stop', sessionId, data: null },
|
||||
});
|
||||
expect(mockTracker.recordHookEvent).toHaveBeenCalledWith('stop', expect.any(Object));
|
||||
});
|
||||
|
||||
it('starts transcript watcher when transcript_path is provided', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
|
||||
@@ -34,6 +34,9 @@ describe('html-view routes', () => {
|
||||
writeFileSync(join(root, 'outside.txt'), 'outside');
|
||||
symlinkSync(join(root, 'outside.txt'), join(workspace, 'escape.txt'));
|
||||
|
||||
mkdirSync(join(root, 'sibling-feature'));
|
||||
writeFileSync(join(root, 'sibling-feature', 'report.html'), '<p>feature</p>');
|
||||
|
||||
harness = await createRouteTestHarness(registerHtmlViewRoutes);
|
||||
sid = harness.ctx._sessionId as string;
|
||||
(harness.ctx.sessions.get(sid) as { workingDir: string }).workingDir = workspace;
|
||||
@@ -270,6 +273,64 @@ describe('html-view routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('in a worktree outside the workspace (#765 follow-up)', () => {
|
||||
let sibling: string;
|
||||
const saved = {
|
||||
confine: process.env.CODEMAN_ATTACHMENT_CONFINE,
|
||||
blocked: process.env.CODEMAN_ATTACHMENT_BLOCKED_PATHS,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
sibling = realpathSync(join(root, 'sibling-feature'));
|
||||
Object.assign(harness.ctx.sessions.get(sid) as object, {
|
||||
liveWorktree: { name: 'sibling-feature', path: sibling, outside: true },
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const [key, value] of [
|
||||
['CODEMAN_ATTACHMENT_CONFINE', saved.confine],
|
||||
['CODEMAN_ATTACHMENT_BLOCKED_PATHS', saved.blocked],
|
||||
] as const) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
it('renders a page from the worktree, minted as outside the workspace', async () => {
|
||||
const res = await open(join(sibling, 'report.html'));
|
||||
expect(res.statusCode).toBe(200);
|
||||
const url = JSON.parse(res.body).data.url as string;
|
||||
const page = await harness.app.inject({ method: 'GET', url });
|
||||
expect(page.statusCode).toBe(200);
|
||||
expect(page.body).toBe('<p>feature</p>');
|
||||
// Minted as outside the workspace, so the serve route's per-request confinement check covers it.
|
||||
expect(htmlViewCapabilities.resolve(capabilityFromHtmlViewPath(url) as string)?.outsideWorkspace).toBe(true);
|
||||
});
|
||||
|
||||
it('answers to the attachment guard: confinement on, or a blocked tree', async () => {
|
||||
const res = await open(join(sibling, 'report.html'));
|
||||
const url = JSON.parse(res.body).data.url as string;
|
||||
|
||||
process.env.CODEMAN_ATTACHMENT_CONFINE = '1';
|
||||
expect((await open(join(sibling, 'report.html'))).statusCode).toBe(403);
|
||||
// A page minted before confinement was switched on stops serving too.
|
||||
expect((await harness.app.inject({ method: 'GET', url })).statusCode).toBe(404);
|
||||
delete process.env.CODEMAN_ATTACHMENT_CONFINE;
|
||||
|
||||
process.env.CODEMAN_ATTACHMENT_BLOCKED_PATHS = sibling;
|
||||
expect((await open(join(sibling, 'report.html'))).statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it('leaves a path outside both roots as it was', async () => {
|
||||
mkdirSync(join(root, 'reports'));
|
||||
writeFileSync(join(root, 'reports', 'report.html'), '<p>report</p>');
|
||||
expect((await open(join(root, 'reports', 'report.html'))).statusCode).toBe(200);
|
||||
process.env.CODEMAN_ATTACHMENT_CONFINE = '1';
|
||||
expect((await open(join(root, 'reports', 'report.html'))).statusCode).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses an HTML file inside a hidden directory, in or out of the workspace', async () => {
|
||||
mkdirSync(join(workspace, '.cache'));
|
||||
writeFileSync(join(workspace, '.cache', 'r.html'), '<p>r</p>');
|
||||
|
||||
@@ -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]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,309 @@
|
||||
/**
|
||||
* @fileoverview The launch guard of the endpoint the local model install manages, at the two
|
||||
* routes that put a session onto a custom model endpoint: they ask the install service before
|
||||
* anything is written.
|
||||
*
|
||||
* - `POST /api/sessions/:id/custom-model` (a running session switches to the endpoint), and
|
||||
* - `POST /api/quick-start` with `customModel` (a session is created on it)
|
||||
*
|
||||
* call `LocalModelService.launchRefusalMessage(endpointId, modelId)` once the endpoint is
|
||||
* found and before anything is written, restarted or created. A sentence back is the answer
|
||||
* (`OPERATION_FAILED`); `undefined` lets the launch go on exactly as before. That is how a
|
||||
* model whose digest is no longer the one stored at install time is not launched, and how
|
||||
* nothing is launched against a port our runtime is not on.
|
||||
*
|
||||
* Every OTHER way a new agent process comes to be on the endpoint (the attach that finds no
|
||||
* pane, the respawn of a dead pane, a restart in place, the rebuild after a reboot) is
|
||||
* covered below the routes, by `Session`'s launch guard: test/local-model-session-launch-guard.test.ts.
|
||||
*
|
||||
* The service is replaced by a fake for most cases, and is the REAL one (over the real state
|
||||
* file, with no runtime running) for the cases that pin the default wiring.
|
||||
*
|
||||
* Port: N/A (app.inject, no real port needed)
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { rmSync, writeFileSync } from 'node:fs';
|
||||
import { rm } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { createMockRouteContext, safeRmHomeTree, type MockRouteContext } from '../mocks/index.js';
|
||||
import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
import { dataPath, getDataDir } from '../../src/config/instance.js';
|
||||
import { CASES_DIR } from '../../src/web/route-helpers.js';
|
||||
import { Session } from '../../src/session.js';
|
||||
import { writeCustomModelHosts, type CustomModelHost } from '../../src/custom-model-hosts.js';
|
||||
import { webviewFetch } from '../../src/web/webview-egress.js';
|
||||
import type { LocalModelService } from '../../src/local-model/install-job.js';
|
||||
|
||||
vi.mock('../../src/web/webview-egress.js', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../src/web/webview-egress.js')>(
|
||||
'../../src/web/webview-egress.js'
|
||||
);
|
||||
return { ...actual, webviewFetch: vi.fn() };
|
||||
});
|
||||
const fetchMock = vi.mocked(webviewFetch);
|
||||
|
||||
// See test/routes/quick-start-custom-model.test.ts: the CLI availability gate runs before the
|
||||
// code under test and would refuse every launch on a machine without the binary.
|
||||
vi.mock('../../src/utils/cli-launcher.js', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../src/utils/cli-launcher.js')>(
|
||||
'../../src/utils/cli-launcher.js'
|
||||
);
|
||||
return { ...actual, resolveCliLaunchError: vi.fn().mockResolvedValue(null) };
|
||||
});
|
||||
|
||||
/** The service the session routes get: a fake by default, the real one where a test says so. */
|
||||
const guard = vi.hoisted(() => ({
|
||||
launchRefusalMessage: vi.fn<(endpointId: string, modelId: string) => Promise<string | undefined>>(),
|
||||
real: undefined as LocalModelService | undefined,
|
||||
}));
|
||||
vi.mock('../../src/local-model/install-job.js', async () => {
|
||||
const actual = await vi.importActual<typeof import('../../src/local-model/install-job.js')>(
|
||||
'../../src/local-model/install-job.js'
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
getLocalModelService: () => guard.real ?? { launchRefusalMessage: guard.launchRefusalMessage },
|
||||
};
|
||||
});
|
||||
|
||||
const MANAGED: CustomModelHost = {
|
||||
id: 'local-ollama',
|
||||
label: 'This Mac',
|
||||
baseUrl: 'http://127.0.0.1:11435',
|
||||
authStyle: 'bearer',
|
||||
models: ['qwen3.6:35b-a3b'],
|
||||
defaultModelId: 'qwen3.6:35b-a3b',
|
||||
defaultContextLength: 131072,
|
||||
};
|
||||
|
||||
const OTHER: CustomModelHost = { id: 'ep1', label: 'llama.cpp box', baseUrl: 'http://192.168.1.50:8080', apiKey: 'k' };
|
||||
|
||||
const CHANGED = 'The model on this Mac changed since it was installed. Remove it and install it again.';
|
||||
const STATE = () => dataPath('local-model.json');
|
||||
|
||||
/** The state file of an installed model whose connection is the managed record. */
|
||||
function writeInstalledState(): void {
|
||||
writeFileSync(
|
||||
STATE(),
|
||||
JSON.stringify({
|
||||
schema: 1,
|
||||
state: 'installed',
|
||||
model: { id: 'qwen3.6:35b-a3b', label: 'Qwen3.6 35B-A3B', context: 131072, digest: 'abc123' },
|
||||
cli: { id: 'opencode', label: 'OpenCode' },
|
||||
runtime: { version: '0.40.15', port: 11435, enabled: true },
|
||||
connection: { endpointId: 'local-ollama', flagWasEnabled: false },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function realService(): Promise<LocalModelService> {
|
||||
const actual = await vi.importActual<typeof import('../../src/local-model/install-job.js')>(
|
||||
'../../src/local-model/install-job.js'
|
||||
);
|
||||
// The real service with its real state file. No runtime was ever started by it.
|
||||
return actual.createLocalModelService();
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
guard.launchRefusalMessage.mockReset();
|
||||
guard.launchRefusalMessage.mockResolvedValue(undefined);
|
||||
guard.real = undefined;
|
||||
fetchMock.mockReset();
|
||||
fetchMock.mockResolvedValue(new Response('not found', { status: 404 }));
|
||||
await writeCustomModelHosts(getDataDir(), [MANAGED, OTHER]);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
rmSync(STATE(), { force: true });
|
||||
await rm(join(getDataDir(), 'custom-model-hosts.json'), { force: true });
|
||||
await rm(join(getDataDir(), 'custom-model-configs'), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('POST /api/sessions/:id/custom-model on the managed endpoint', () => {
|
||||
async function setup() {
|
||||
const harness = await createRouteTestHarness(registerSessionRoutes);
|
||||
const session = harness.ctx.sessions.get('test-session-1')!;
|
||||
session.mode = 'claude';
|
||||
return { ...harness, session };
|
||||
}
|
||||
|
||||
const apply = (app: FastifyInstance, payload: Record<string, unknown>) =>
|
||||
app.inject({ method: 'POST', url: '/api/sessions/test-session-1/custom-model', payload });
|
||||
|
||||
it('asks the install service with the endpoint and the model, before anything is applied', async () => {
|
||||
const { app, session } = await setup();
|
||||
const res = await apply(app, { endpointId: 'local-ollama', modelId: 'qwen3.6:35b-a3b' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(guard.launchRefusalMessage).toHaveBeenCalledTimes(1);
|
||||
expect(guard.launchRefusalMessage).toHaveBeenCalledWith('local-ollama', 'qwen3.6:35b-a3b');
|
||||
// No refusal: the model is applied and the CLI restarted, as for any endpoint.
|
||||
expect(session.setCustomModel).toHaveBeenCalledTimes(1);
|
||||
expect(session.restartCli).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('a changed model refuses the switch in one plain sentence, and nothing is written or restarted', async () => {
|
||||
const { app, session } = await setup();
|
||||
guard.launchRefusalMessage.mockResolvedValue(CHANGED);
|
||||
const res = await apply(app, { endpointId: 'local-ollama', modelId: 'qwen3.6:35b-a3b' });
|
||||
expect(res.json()).toEqual({ success: false, error: CHANGED, errorCode: 'OPERATION_FAILED' });
|
||||
expect(session.setCustomModel).not.toHaveBeenCalled();
|
||||
expect(session.restartCli).not.toHaveBeenCalled();
|
||||
// The runtime was not even asked what it has loaded.
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('every other endpoint is asked about too, and the service lets it through', async () => {
|
||||
const { app, session } = await setup();
|
||||
const res = await apply(app, { endpointId: 'ep1', modelId: 'qwen3' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(guard.launchRefusalMessage).toHaveBeenCalledWith('ep1', 'qwen3');
|
||||
expect(session.setCustomModel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('clearing a selection is never refused: it is the way OFF the endpoint', async () => {
|
||||
const { app, session } = await setup();
|
||||
guard.launchRefusalMessage.mockResolvedValue(CHANGED);
|
||||
session.setCustomModel.mockReturnValue({ previousConfigDir: undefined });
|
||||
const res = await apply(app, { clear: true });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(guard.launchRefusalMessage).not.toHaveBeenCalled();
|
||||
expect(session.setCustomModel).toHaveBeenCalledWith(undefined);
|
||||
});
|
||||
|
||||
it('an endpoint that does not exist is still a 404 of its own, asked about nothing', async () => {
|
||||
const { app } = await setup();
|
||||
const res = await apply(app, { endpointId: 'nope', modelId: 'x' });
|
||||
expect(res.json()).toMatchObject({ success: false, errorCode: 'NOT_FOUND' });
|
||||
expect(guard.launchRefusalMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('with the real install service', () => {
|
||||
it('an installed model whose runtime is not running is not switched to', async () => {
|
||||
writeInstalledState();
|
||||
guard.real = await realService();
|
||||
const { app, session } = await setup();
|
||||
const res = await apply(app, { endpointId: 'local-ollama', modelId: 'qwen3.6:35b-a3b' });
|
||||
expect(res.json()).toEqual({
|
||||
success: false,
|
||||
error: 'The model on this Mac is not running. Start it first.',
|
||||
errorCode: 'OPERATION_FAILED',
|
||||
});
|
||||
expect(session.setCustomModel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a record with the reserved id that nobody installed is an endpoint like any other', async () => {
|
||||
// No state file: this feature wrote nothing, so there is nothing of ours to guard.
|
||||
guard.real = await realService();
|
||||
const { app, session } = await setup();
|
||||
const res = await apply(app, { endpointId: 'local-ollama', modelId: 'qwen3.6:35b-a3b' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(session.setCustomModel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('any other endpoint is untouched by an installed model', async () => {
|
||||
writeInstalledState();
|
||||
guard.real = await realService();
|
||||
const { app, session } = await setup();
|
||||
const res = await apply(app, { endpointId: 'ep1', modelId: 'qwen3' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(session.setCustomModel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/quick-start with customModel on the managed endpoint', () => {
|
||||
let app: FastifyInstance;
|
||||
let ctx: MockRouteContext;
|
||||
|
||||
const quickStart = (payload: Record<string, unknown>) =>
|
||||
app.inject({ method: 'POST', url: '/api/quick-start', payload });
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.spyOn(Session.prototype, 'startInteractive').mockResolvedValue(undefined);
|
||||
vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined);
|
||||
vi.spyOn(Session.prototype, 'restartCli').mockResolvedValue(true);
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
ctx = createMockRouteContext();
|
||||
registerSessionRoutes(app, ctx);
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
vi.restoreAllMocks();
|
||||
safeRmHomeTree(CASES_DIR);
|
||||
});
|
||||
|
||||
it('asks the install service, and with no refusal the session starts on the local model', async () => {
|
||||
const before = ctx.sessions.size;
|
||||
const res = await quickStart({
|
||||
caseName: 'lm-ok',
|
||||
mode: 'claude',
|
||||
customModel: { endpointId: 'local-ollama', modelId: 'qwen3.6:35b-a3b' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().sessionId).toBeTruthy();
|
||||
expect(guard.launchRefusalMessage).toHaveBeenCalledWith('local-ollama', 'qwen3.6:35b-a3b');
|
||||
expect(ctx.sessions.size).toBe(before + 1);
|
||||
const session = ctx.sessions.get(res.json().sessionId) as unknown as Session;
|
||||
expect(session.customModel).toMatchObject({ endpointId: 'local-ollama', modelId: 'qwen3.6:35b-a3b' });
|
||||
});
|
||||
|
||||
it('a changed model refuses the launch in one plain sentence, and no session is created', async () => {
|
||||
guard.launchRefusalMessage.mockResolvedValue(CHANGED);
|
||||
const before = ctx.sessions.size;
|
||||
const res = await quickStart({
|
||||
caseName: 'lm-changed',
|
||||
mode: 'claude',
|
||||
customModel: { endpointId: 'local-ollama', modelId: 'qwen3.6:35b-a3b' },
|
||||
});
|
||||
expect(res.json()).toEqual({ success: false, error: CHANGED, errorCode: 'OPERATION_FAILED' });
|
||||
expect(ctx.sessions.size).toBe(before);
|
||||
expect(Session.prototype.startInteractive).not.toHaveBeenCalled();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a launch without a custom model never asks', async () => {
|
||||
const res = await quickStart({ caseName: 'lm-plain', mode: 'claude' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(guard.launchRefusalMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('with the real install service', () => {
|
||||
it('an installed model whose runtime is not running is not launched', async () => {
|
||||
writeInstalledState();
|
||||
guard.real = await realService();
|
||||
const before = ctx.sessions.size;
|
||||
const res = await quickStart({
|
||||
caseName: 'lm-stopped',
|
||||
mode: 'claude',
|
||||
customModel: { endpointId: 'local-ollama', modelId: 'qwen3.6:35b-a3b' },
|
||||
});
|
||||
expect(res.json()).toEqual({
|
||||
success: false,
|
||||
error: 'The model on this Mac is not running. Start it first.',
|
||||
errorCode: 'OPERATION_FAILED',
|
||||
});
|
||||
expect(ctx.sessions.size).toBe(before);
|
||||
});
|
||||
|
||||
it('a launch on any other endpoint goes on as before', async () => {
|
||||
writeInstalledState();
|
||||
guard.real = await realService();
|
||||
const res = await quickStart({
|
||||
caseName: 'lm-other',
|
||||
mode: 'claude',
|
||||
customModel: { endpointId: 'ep1', modelId: 'qwen3' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().sessionId).toBeTruthy();
|
||||
expect(res.json().success).not.toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* @fileoverview The omp approval hook module on BOTH session create paths.
|
||||
*
|
||||
* `POST /api/quick-start` is how the Run button, the agent skill's `spawn_worker` and
|
||||
* `codeman agent spawn` start omp, so installing only from `POST /api/sessions` left the
|
||||
* usual omp launch silent. These tests pin, on disk:
|
||||
* - both paths write `.claude/hooks/pre/codeman-approval.ts` into a local workspace;
|
||||
* - neither writes Claude's `.claude/settings.local.json` hook block for omp (only
|
||||
* claude reads it) or, for a Docker case, a CLAUDE.md;
|
||||
* - `workspaceHooksEnabled: false` writes nothing;
|
||||
* - a create refused by the launch pre-flight leaves nothing behind.
|
||||
*
|
||||
* The launch pre-flight is mocked so the result does not depend on whether omp is
|
||||
* installed on the machine running the suite. Uses app.inject(), no port.
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { mkdtemp, rm, mkdir, writeFile } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createMockRouteContext, safeRmHomeTree } from '../mocks/index.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
import { OMP_APPROVAL_HOOK_DIR, OMP_APPROVAL_HOOK_FILE } from '../../src/hooks-config.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { CASES_DIR } from '../../src/web/route-helpers.js';
|
||||
import { Session } from '../../src/session.js';
|
||||
|
||||
const launch = vi.hoisted(() => ({ error: null as string | null }));
|
||||
vi.mock('../../src/utils/cli-launcher.js', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../../src/utils/cli-launcher.js')>()),
|
||||
resolveCliLaunchError: vi.fn(async () => launch.error),
|
||||
}));
|
||||
|
||||
const hookFileIn = (dir: string) => join(dir, OMP_APPROVAL_HOOK_DIR, OMP_APPROVAL_HOOK_FILE);
|
||||
const claudeSettingsIn = (dir: string) => join(dir, '.claude', 'settings.local.json');
|
||||
|
||||
/**
|
||||
* A create that SUCCEEDED. The status alone cannot say so: `createErrorResponse()`
|
||||
* envelopes come back as 200 here (no preSerialization hook), so an early refusal would
|
||||
* make every "wrote nothing" assertion below pass vacuously. A success body is the raw
|
||||
* payload (no envelope), so the proof is a real session id in it.
|
||||
*/
|
||||
function expectCreated(res: { statusCode: number; body: string }) {
|
||||
expect(res.statusCode).toBe(200);
|
||||
const body = JSON.parse(res.body) as { success?: boolean; session?: { id?: string }; sessionId?: string };
|
||||
expect(body.success, res.body).not.toBe(false);
|
||||
expect(body.session?.id ?? body.sessionId, res.body).toBeTruthy();
|
||||
}
|
||||
|
||||
describe('omp approval hook on the create paths', () => {
|
||||
let app: FastifyInstance;
|
||||
|
||||
const useApp = async (workspaceHooksEnabled = true) => {
|
||||
await app?.close();
|
||||
app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
registerSessionRoutes(app, createMockRouteContext({ workspaceHooksEnabled }));
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
launch.error = null;
|
||||
vi.spyOn(Session.prototype, 'startInteractive').mockResolvedValue(undefined);
|
||||
vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined);
|
||||
await useApp();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close();
|
||||
vi.restoreAllMocks();
|
||||
await rm(join(getDataDir(), 'docker-hosts.json'), { force: true });
|
||||
await rm(join(getDataDir(), 'docker-cases.json'), { force: true });
|
||||
// CASES_DIR sits under the (redirected) test HOME; safeRmHomeTree refuses anything else.
|
||||
safeRmHomeTree(CASES_DIR);
|
||||
});
|
||||
|
||||
describe('POST /api/sessions', () => {
|
||||
let workingDir: string;
|
||||
const createSession = (payload: Record<string, unknown>) =>
|
||||
app.inject({ method: 'POST', url: '/api/sessions', payload });
|
||||
|
||||
beforeEach(async () => {
|
||||
workingDir = await mkdtemp(join(tmpdir(), 'codeman-omp-create-'));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(workingDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('installs the module, and no Claude hook block', async () => {
|
||||
expectCreated(await createSession({ name: 'omp-create', mode: 'omp', workingDir }));
|
||||
expect(existsSync(hookFileIn(workingDir))).toBe(true);
|
||||
expect(existsSync(claudeSettingsIn(workingDir))).toBe(false);
|
||||
});
|
||||
|
||||
it('writes nothing when workspaceHooksEnabled is off', async () => {
|
||||
await useApp(false);
|
||||
expectCreated(await createSession({ name: 'omp-off', mode: 'omp', workingDir }));
|
||||
expect(existsSync(join(workingDir, '.claude'))).toBe(false);
|
||||
});
|
||||
|
||||
it('leaves nothing behind when the launch pre-flight refuses the create', async () => {
|
||||
launch.error = 'omp: command not found';
|
||||
const res = await createSession({ name: 'omp-missing', mode: 'omp', workingDir });
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(existsSync(join(workingDir, '.claude'))).toBe(false);
|
||||
});
|
||||
|
||||
it('gives claude no module', async () => {
|
||||
expectCreated(await createSession({ name: 'claude-create', mode: 'claude', workingDir }));
|
||||
expect(existsSync(hookFileIn(workingDir))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('POST /api/quick-start', () => {
|
||||
const quickStart = (payload: Record<string, unknown>) =>
|
||||
app.inject({ method: 'POST', url: '/api/quick-start', payload });
|
||||
|
||||
it('installs the module into an EXISTING case, and no Claude hook block', async () => {
|
||||
const casePath = join(CASES_DIR, 'ompexisting');
|
||||
await mkdir(casePath, { recursive: true });
|
||||
expectCreated(await quickStart({ caseName: 'ompexisting', mode: 'omp' }));
|
||||
expect(existsSync(hookFileIn(casePath))).toBe(true);
|
||||
expect(existsSync(claudeSettingsIn(casePath))).toBe(false);
|
||||
});
|
||||
|
||||
it('installs the module into a case it scaffolds, and no Claude hook block', async () => {
|
||||
expectCreated(await quickStart({ caseName: 'ompnew', mode: 'omp' }));
|
||||
const casePath = join(CASES_DIR, 'ompnew');
|
||||
expect(existsSync(hookFileIn(casePath))).toBe(true);
|
||||
expect(existsSync(claudeSettingsIn(casePath))).toBe(false);
|
||||
});
|
||||
|
||||
it('writes nothing into an existing case when workspaceHooksEnabled is off', async () => {
|
||||
await useApp(false);
|
||||
const casePath = join(CASES_DIR, 'ompoff');
|
||||
await mkdir(casePath, { recursive: true });
|
||||
expectCreated(await quickStart({ caseName: 'ompoff', mode: 'omp' }));
|
||||
expect(existsSync(join(casePath, '.claude'))).toBe(false);
|
||||
});
|
||||
|
||||
it('leaves nothing behind when the launch pre-flight refuses', async () => {
|
||||
launch.error = 'omp: command not found';
|
||||
const casePath = join(CASES_DIR, 'ompmissing');
|
||||
await mkdir(casePath, { recursive: true });
|
||||
const res = await quickStart({ caseName: 'ompmissing', mode: 'omp' });
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(existsSync(join(casePath, '.claude'))).toBe(false);
|
||||
});
|
||||
|
||||
it('writes neither the module nor a Claude block (or CLAUDE.md) into a Docker case', async () => {
|
||||
const ws = await mkdtemp(join(tmpdir(), 'codeman-docker-omp-'));
|
||||
try {
|
||||
await mkdir(getDataDir(), { recursive: true });
|
||||
await writeFile(
|
||||
join(getDataDir(), 'docker-hosts.json'),
|
||||
JSON.stringify([{ id: 'd1', label: 'box', image: 'codeman/agent:base' }])
|
||||
);
|
||||
await writeFile(
|
||||
join(getDataDir(), 'docker-cases.json'),
|
||||
JSON.stringify([{ name: 'dockomp', type: 'docker', hostId: 'd1', hostWorkspacePath: ws }])
|
||||
);
|
||||
expectCreated(await quickStart({ caseName: 'dockomp', mode: 'omp' }));
|
||||
expect(existsSync(hookFileIn(ws))).toBe(false);
|
||||
expect(existsSync(claudeSettingsIn(ws))).toBe(false);
|
||||
expect(existsSync(join(ws, 'CLAUDE.md'))).toBe(false);
|
||||
} finally {
|
||||
await rm(ws, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -21,7 +21,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { rm, readFile } from 'node:fs/promises';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { existsSync, readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { createMockRouteContext, safeRmHomeTree, type MockRouteContext } from '../mocks/index.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
@@ -92,6 +92,35 @@ describe('POST /api/quick-start: customModel (one-shot custom-model launch)', ()
|
||||
safeRmHomeTree(CASES_DIR);
|
||||
});
|
||||
|
||||
it("learns the caller's own value under an injected key, so a clear can put it back", async () => {
|
||||
const own = join(getDataDir(), 'client-claude');
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-own-home',
|
||||
mode: 'claude',
|
||||
envOverrides: { CLAUDE_CONFIG_DIR: own },
|
||||
customModel: { endpointId: 'ep1', modelId: 'qwen3' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const { sessionId } = res.json();
|
||||
const session = ctx.sessions.get(sessionId) as unknown as Session;
|
||||
const isolatedDir = customModelConfigDir(sessionId);
|
||||
// It launches on the isolated directory, with the caller's value set aside rather
|
||||
// than recorded as the injected one.
|
||||
expect(session.envOverrideValue('CLAUDE_CONFIG_DIR')).toBe(isolatedDir);
|
||||
expect(session.getCustomModelForPersist()?.ownEnv).toEqual({ CLAUDE_CONFIG_DIR: own });
|
||||
|
||||
const clear = await app.inject({
|
||||
method: 'POST',
|
||||
url: `/api/sessions/${sessionId}/custom-model`,
|
||||
payload: { clear: true },
|
||||
});
|
||||
expect(clear.statusCode).toBe(200);
|
||||
expect(session.customModel).toBeUndefined();
|
||||
expect(session.envOverrideValue('CLAUDE_CONFIG_DIR')).toBe(own);
|
||||
expect(existsSync(isolatedDir)).toBe(false);
|
||||
});
|
||||
|
||||
it('launches a claude session already pointed at the endpoint — no restart at all', async () => {
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-claude',
|
||||
@@ -122,6 +151,9 @@ describe('POST /api/quick-start: customModel (one-shot custom-model launch)', ()
|
||||
const { sessionId } = res.json();
|
||||
const session = ctx.sessions.get(sessionId) as unknown as Session;
|
||||
expect(session.customModel?.endpointId).toBe('ep1');
|
||||
// #750, pinned the same way as the pi/grok/omp one-shot paths below: the FIRST
|
||||
// launch already carries the selected id, not just the file on disk.
|
||||
expect(session.getCustomModelForPersist()?.launchModel).toBe('qwen3');
|
||||
expect(restartSpy).not.toHaveBeenCalled();
|
||||
|
||||
const configDir = customModelConfigDir(sessionId);
|
||||
@@ -172,6 +204,34 @@ describe('POST /api/quick-start: customModel (one-shot custom-model launch)', ()
|
||||
expect(restartSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves the caller's own model in the stored config, which is what a later clear falls back to", async () => {
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-pi-own-model',
|
||||
mode: 'pi',
|
||||
piConfig: { model: 'anthropic/claude-x' },
|
||||
customModel: { endpointId: 'ep1', modelId: 'qwen3' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const { sessionId } = res.json();
|
||||
const session = ctx.sessions.get(sessionId) as unknown as Session;
|
||||
expect(session.getCustomModelForPersist()?.launchModel).toBe('custom/qwen3');
|
||||
expect(session.toState().piConfig?.model).toBe('anthropic/claude-x');
|
||||
});
|
||||
|
||||
it('stores no model at all for a caller that chose none', async () => {
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-codex-no-model',
|
||||
mode: 'codex',
|
||||
customModel: { endpointId: 'ep1', modelId: 'qwen3' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
const session = ctx.sessions.get(res.json().sessionId) as unknown as Session;
|
||||
expect(session.getCustomModelForPersist()?.launchModel).toBe('qwen3');
|
||||
expect(session.toState().codexConfig?.model).toBeUndefined();
|
||||
});
|
||||
|
||||
it('404s for an unknown endpoint id', async () => {
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-ghost',
|
||||
@@ -192,7 +252,9 @@ describe('POST /api/quick-start: customModel (one-shot custom-model launch)', ()
|
||||
expect(res.json().errorCode).toBe('OPERATION_FAILED');
|
||||
});
|
||||
|
||||
it('refuses a model id the CLI cannot carry on its command line, cleaning up any written config dir', async () => {
|
||||
it('refuses a model id the CLI cannot carry on its command line, before writing anything', async () => {
|
||||
const dirs = join(getDataDir(), 'custom-model-configs');
|
||||
const before = existsSync(dirs) ? readdirSync(dirs).length : 0;
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-badmodel',
|
||||
mode: 'pi',
|
||||
@@ -200,6 +262,7 @@ describe('POST /api/quick-start: customModel (one-shot custom-model launch)', ()
|
||||
});
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().errorCode).toBe('INVALID_INPUT');
|
||||
expect(existsSync(dirs) ? readdirSync(dirs).length : 0).toBe(before);
|
||||
});
|
||||
|
||||
it('refuses customModel for a remote case', async () => {
|
||||
@@ -226,6 +289,21 @@ describe('POST /api/quick-start: customModel (one-shot custom-model launch)', ()
|
||||
});
|
||||
}
|
||||
|
||||
it('refuses a model id the CLI cannot launch before asking anyone to evict a model', async () => {
|
||||
const other = ctx.sessions.get('test-session-1')!;
|
||||
(other as unknown as { customModel: unknown }).customModel = { endpointId: 'ep1', modelId: 'llama3' };
|
||||
mockRunning([{ model: 'llama3', state: 'ready' }]);
|
||||
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-badmodel-swap',
|
||||
mode: 'codex',
|
||||
customModel: { endpointId: 'ep1', modelId: 'org/model@q4_k_m' },
|
||||
});
|
||||
|
||||
expect(res.json().requiresConfirmation).toBeUndefined();
|
||||
expect(res.json().errorCode).toBe('INVALID_INPUT');
|
||||
});
|
||||
|
||||
it('asks for confirmation instead of launching when another live session is using the currently loaded model', async () => {
|
||||
const other = ctx.sessions.get('test-session-1')!;
|
||||
(other as unknown as { customModel: unknown }).customModel = { endpointId: 'ep1', modelId: 'llama3' };
|
||||
@@ -316,6 +394,47 @@ describe('POST /api/quick-start: customModel (one-shot custom-model launch)', ()
|
||||
expect(ctx.sessions.size).toBe(2);
|
||||
});
|
||||
|
||||
describe('parallel slots share the context (the quick-start path has its own slot branch)', () => {
|
||||
const slotEndpoint = (contextLength: number, slots: number): CustomModelHost => ({
|
||||
id: 'ep-slots',
|
||||
label: 'multi-slot box',
|
||||
baseUrl: 'http://192.168.1.52:8080',
|
||||
apiKey: 'k',
|
||||
modelContextLengths: { m: contextLength },
|
||||
modelSlotCounts: { m: slots },
|
||||
});
|
||||
|
||||
it('warns when the context divided across the slots is below the floor, and reports the slot count', async () => {
|
||||
await writeCustomModelHosts(getDataDir(), [ENDPOINT, slotEndpoint(131072, 4)]); // ~33k per slot
|
||||
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-slots-warn',
|
||||
mode: 'claude',
|
||||
customModel: { endpointId: 'ep-slots', modelId: 'm' },
|
||||
});
|
||||
|
||||
const body = res.json();
|
||||
expect(body.requiresContextWarning).toBe(true);
|
||||
expect(body.contextLength).toBe(131072);
|
||||
expect(body.slotCount).toBe(4);
|
||||
expect(ctx.sessions.size).toBe(1); // nothing was created
|
||||
});
|
||||
|
||||
it('launches when every slot can hold the floor', async () => {
|
||||
await writeCustomModelHosts(getDataDir(), [ENDPOINT, slotEndpoint(262144, 4)]); // 65,536 per slot
|
||||
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-slots-ok',
|
||||
mode: 'claude',
|
||||
customModel: { endpointId: 'ep-slots', modelId: 'm' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().requiresContextWarning).toBeUndefined();
|
||||
expect(ctx.sessions.size).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
it('does not warn when nothing about context was discovered', async () => {
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-no-ctx-data',
|
||||
@@ -326,6 +445,50 @@ describe('POST /api/quick-start: customModel (one-shot custom-model launch)', ()
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().requiresContextWarning).toBeUndefined();
|
||||
});
|
||||
|
||||
it('warns using the endpoint defaultContextLength when discovery recorded no per-model figure', async () => {
|
||||
const endpoint: CustomModelHost = {
|
||||
id: 'ep-default',
|
||||
label: 'silent gateway',
|
||||
baseUrl: 'http://192.168.1.53:8080',
|
||||
apiKey: 'k',
|
||||
defaultContextLength: 16384,
|
||||
};
|
||||
await writeCustomModelHosts(getDataDir(), [ENDPOINT, endpoint]);
|
||||
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-default-ctx',
|
||||
mode: 'claude',
|
||||
customModel: { endpointId: 'ep-default', modelId: 'some-unknown-model' },
|
||||
});
|
||||
|
||||
const body = res.json();
|
||||
expect(body.requiresContextWarning).toBe(true);
|
||||
expect(body.contextLength).toBe(16384);
|
||||
expect(ctx.sessions.size).toBe(1); // nothing was created
|
||||
});
|
||||
|
||||
it('a discovered per-model figure wins over the endpoint defaultContextLength', async () => {
|
||||
const endpoint: CustomModelHost = {
|
||||
id: 'ep-precedence',
|
||||
label: 'mixed box',
|
||||
baseUrl: 'http://192.168.1.54:8080',
|
||||
apiKey: 'k',
|
||||
modelContextLengths: { m: 131072 },
|
||||
defaultContextLength: 16384,
|
||||
};
|
||||
await writeCustomModelHosts(getDataDir(), [ENDPOINT, endpoint]);
|
||||
|
||||
const res = await quickStart({
|
||||
caseName: 'cm-precedence',
|
||||
mode: 'claude',
|
||||
customModel: { endpointId: 'ep-precedence', modelId: 'm' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().requiresContextWarning).toBeUndefined();
|
||||
expect(ctx.sessions.size).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('triggering the actual llama-swap load (not just watching for it)', () => {
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* @fileoverview Ralph file routes for a REMOTE (SSH) session.
|
||||
*
|
||||
* A remote session's `workingDir` is a path on the remote host. `fix-plan/read`
|
||||
* used to read `@fix_plan.md` with local `fs`, and `fix-plan/write` and
|
||||
* `ralph-prompt/write` wrote their files with it, so with a same-named local folder
|
||||
* (an sshfs mount, a shared home layout) they read and wrote the LOCAL twin. Now:
|
||||
* - `fix-plan/read` reads the file on the remote host through `src/remote-files.ts`
|
||||
* (the File Viewer's ssh path), and a missing remote file is the same 404 as a
|
||||
* missing local one;
|
||||
* - both writes are refused (remote writes are out of scope, like the File Viewer's
|
||||
* remote edit).
|
||||
*
|
||||
* The workspace path EXISTS locally here, holding a different `@fix_plan.md`, so a
|
||||
* route that fell back to local `fs` would visibly import or overwrite the wrong file.
|
||||
* The ssh layer is mocked (no connection is opened); the pure builders and
|
||||
* `RemoteFileAccessError` stay real.
|
||||
*
|
||||
* Port: N/A (app.inject doesn't open ports)
|
||||
*/
|
||||
|
||||
import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { createRouteTestHarness, type RouteTestHarness } from './_route-test-utils.js';
|
||||
import { safeRmHomeTree } from '../mocks/test-helpers.js';
|
||||
import { registerRalphRoutes } from '../../src/web/routes/ralph-routes.js';
|
||||
import type { RemoteProbe } from '../../src/remote-files.js';
|
||||
import type { SessionRemote } from '../../src/types/session.js';
|
||||
|
||||
vi.mock('../../src/remote-files.js', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('../../src/remote-files.js')>();
|
||||
return { ...actual, remoteProbePaths: vi.fn(), remoteReadFile: vi.fn() };
|
||||
});
|
||||
|
||||
import { remoteProbePaths, remoteReadFile, RemoteFileAccessError } from '../../src/remote-files.js';
|
||||
|
||||
const mockedProbePaths = vi.mocked(remoteProbePaths);
|
||||
const mockedReadFile = vi.mocked(remoteReadFile);
|
||||
|
||||
// The local twin of the remote workspace: same absolute path, different file.
|
||||
const TWIN = join(homedir(), '.codeman-test-ralph-remote-twin');
|
||||
const LOCAL_PLAN = '# Fix Plan\n\n- [ ] LOCAL task\n';
|
||||
const REMOTE_PLAN = '# Fix Plan\n\n- [ ] REMOTE task\n';
|
||||
const remote: SessionRemote = {
|
||||
hostId: 'host-1',
|
||||
label: 'testhost',
|
||||
host: '192.0.2.10',
|
||||
username: 'j',
|
||||
remotePath: TWIN,
|
||||
};
|
||||
|
||||
function fileProbe(size = REMOTE_PLAN.length): RemoteProbe {
|
||||
return { realPath: join(TWIN, '@fix_plan.md'), kind: 'file', size, mtimeMs: 1_700_000_000_000 };
|
||||
}
|
||||
|
||||
const rootProbe: RemoteProbe = { realPath: TWIN, kind: 'directory', size: 0, mtimeMs: 0 };
|
||||
|
||||
describe('ralph file routes for a remote (SSH) session', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let importFixPlanMarkdown: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeAll(() => {
|
||||
mkdirSync(TWIN, { recursive: true });
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
safeRmHomeTree(TWIN);
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
writeFileSync(join(TWIN, '@fix_plan.md'), LOCAL_PLAN);
|
||||
harness = await createRouteTestHarness(registerRalphRoutes);
|
||||
importFixPlanMarkdown = vi.fn(() => 1);
|
||||
const session = harness.ctx._session as unknown as Record<string, unknown>;
|
||||
session.workingDir = TWIN;
|
||||
session.remote = { ...remote };
|
||||
session.ralphTracker = {
|
||||
generateFixPlanMarkdown: vi.fn(() => '# Fix Plan\n\n- [ ] generated\n'),
|
||||
importFixPlanMarkdown,
|
||||
todos: [],
|
||||
};
|
||||
mockedProbePaths.mockResolvedValue([fileProbe(), rootProbe]);
|
||||
mockedReadFile.mockResolvedValue(Buffer.from(REMOTE_PLAN));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const post = (route: string, payload?: unknown) =>
|
||||
harness.app.inject({ method: 'POST', url: `/api/sessions/${harness.ctx._sessionId}/${route}`, payload });
|
||||
|
||||
describe('POST fix-plan/read', () => {
|
||||
it('imports the file from the remote host, not the local twin', async () => {
|
||||
const res = await post('fix-plan/read');
|
||||
expect(JSON.parse(res.body)).toMatchObject({ success: true, data: { importedCount: 1 } });
|
||||
expect(mockedProbePaths).toHaveBeenCalledWith(remote, [join(TWIN, '@fix_plan.md'), TWIN]);
|
||||
expect(mockedReadFile).toHaveBeenCalledWith(remote, join(TWIN, '@fix_plan.md'), expect.any(Number));
|
||||
expect(importFixPlanMarkdown).toHaveBeenCalledWith(REMOTE_PLAN);
|
||||
expect(harness.ctx.persistSessionState).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('answers the same not-found as a local read when the remote file is missing', async () => {
|
||||
mockedProbePaths.mockResolvedValue([null, rootProbe]);
|
||||
const res = await post('fix-plan/read');
|
||||
expect(JSON.parse(res.body)).toMatchObject({ success: false, errorCode: 'NOT_FOUND' });
|
||||
expect(mockedReadFile).not.toHaveBeenCalled();
|
||||
expect(importFixPlanMarkdown).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('treats a @fix_plan.md that resolves outside the workspace as missing', async () => {
|
||||
// e.g. a symlink to ~/.ssh/id_rsa on the remote host: the File Viewer's confinement applies.
|
||||
mockedProbePaths.mockResolvedValue([{ ...fileProbe(), realPath: '/home/j/.ssh/id_rsa' }, rootProbe]);
|
||||
const res = await post('fix-plan/read');
|
||||
expect(JSON.parse(res.body)).toMatchObject({ success: false, errorCode: 'NOT_FOUND' });
|
||||
expect(mockedReadFile).not.toHaveBeenCalled();
|
||||
expect(importFixPlanMarkdown).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a remote path that is not a regular file, or one over the cap, without reading it', async () => {
|
||||
for (const probe of [
|
||||
{ ...fileProbe(), kind: 'directory' as const },
|
||||
{ ...fileProbe(), kind: 'other' as const },
|
||||
fileProbe(64 * 1024 * 1024),
|
||||
]) {
|
||||
mockedProbePaths.mockResolvedValue([probe, rootProbe]);
|
||||
const res = await post('fix-plan/read');
|
||||
expect(JSON.parse(res.body)).toMatchObject({ success: false, errorCode: 'OPERATION_FAILED' });
|
||||
}
|
||||
expect(mockedReadFile).not.toHaveBeenCalled();
|
||||
expect(importFixPlanMarkdown).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports an unreachable host as a failed read, never a local fallback', async () => {
|
||||
mockedProbePaths.mockRejectedValue(new RemoteFileAccessError('remote host testhost unreachable: timeout'));
|
||||
const res = await post('fix-plan/read');
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body).toMatchObject({ success: false, errorCode: 'OPERATION_FAILED' });
|
||||
expect(body.error).toContain('unreachable');
|
||||
expect(body.error).not.toContain('RemoteFileAccessError');
|
||||
expect(importFixPlanMarkdown).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('writes', () => {
|
||||
it('refuses fix-plan/write and leaves the local twin alone', async () => {
|
||||
const res = await post('fix-plan/write');
|
||||
expect(JSON.parse(res.body)).toMatchObject({ success: false, errorCode: 'INVALID_INPUT' });
|
||||
expect(readFileSync(join(TWIN, '@fix_plan.md'), 'utf-8')).toBe(LOCAL_PLAN);
|
||||
});
|
||||
|
||||
it('refuses ralph-prompt/write and creates nothing locally', async () => {
|
||||
const res = await post('ralph-prompt/write', { content: 'do the thing' });
|
||||
expect(JSON.parse(res.body)).toMatchObject({ success: false, errorCode: 'INVALID_INPUT' });
|
||||
expect(existsSync(join(TWIN, '@ralph_prompt.md'))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a local session is unchanged', () => {
|
||||
beforeEach(() => {
|
||||
delete (harness.ctx._session as unknown as Record<string, unknown>).remote;
|
||||
});
|
||||
|
||||
it('reads the local file without touching ssh', async () => {
|
||||
const res = await post('fix-plan/read');
|
||||
expect(JSON.parse(res.body)).toMatchObject({ success: true });
|
||||
expect(importFixPlanMarkdown).toHaveBeenCalledWith(LOCAL_PLAN);
|
||||
expect(mockedProbePaths).not.toHaveBeenCalled();
|
||||
expect(mockedReadFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('writes the local files', async () => {
|
||||
expect(JSON.parse((await post('fix-plan/write')).body)).toMatchObject({ success: true });
|
||||
expect(readFileSync(join(TWIN, '@fix_plan.md'), 'utf-8')).toContain('generated');
|
||||
expect(JSON.parse((await post('ralph-prompt/write', { content: 'do the thing' })).body)).toMatchObject({
|
||||
success: true,
|
||||
});
|
||||
expect(readFileSync(join(TWIN, '@ralph_prompt.md'), 'utf-8')).toBe('do the thing');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -476,6 +476,8 @@ describe('ralph-routes', () => {
|
||||
payload: { taskDescription: 'test task', completionPhrase: 'DONE', caseName: 'registration-order' },
|
||||
});
|
||||
await vi.waitFor(() => expect(harness.ctx.addSession).toHaveBeenCalledTimes(1));
|
||||
// The case rides the registration, so the session lands in the case's default session group.
|
||||
expect(harness.ctx.addSession).toHaveBeenCalledWith(expect.anything(), { caseName: 'registration-order' });
|
||||
expect(harness.ctx.persistSessionState).not.toHaveBeenCalled();
|
||||
expect(harness.ctx.setupSessionListeners).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { createRouteTestHarness } from './_route-test-utils.js';
|
||||
import { createMockSession } from '../mocks/index.js';
|
||||
import { getDataDir } from '../../src/config/instance.js';
|
||||
import { writeCustomModelHosts, type CustomModelHost } from '../../src/custom-model-hosts.js';
|
||||
import { existsSync, readFileSync, statSync } from 'node:fs';
|
||||
import { existsSync, readFileSync, readlinkSync, rmSync, statSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { webviewFetch } from '../../src/web/webview-egress.js';
|
||||
|
||||
@@ -97,6 +97,27 @@ describe('POST /api/sessions/:id/custom-model', () => {
|
||||
expect(trustFile.customApiKeyResponses.approved).toEqual(['k']);
|
||||
});
|
||||
|
||||
it("links a switch from the session's own home, never the injected one the map now holds", async () => {
|
||||
const { app, ctx } = await setup();
|
||||
const session = ctx.sessions.get('test-session-1')!;
|
||||
session.mode = 'deepseek';
|
||||
const isolatedDir = join(getDataDir(), 'custom-model-configs', 'test-session-1');
|
||||
const ownHome = join(getDataDir(), 'own-dsh-home');
|
||||
session.envOverrideValue.mockImplementation(() => isolatedDir);
|
||||
session.ownEnvValue.mockImplementation((key: string) => (key === 'DSH_HOME' ? ownHome : undefined));
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-session-1/custom-model',
|
||||
payload: { endpointId: 'ep1', modelId: 'qwen3' },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(readlinkSync(join(isolatedDir, 'sessions'))).toBe(join(ownHome, 'sessions'));
|
||||
rmSync(isolatedDir, { recursive: true, force: true });
|
||||
rmSync(ownHome, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('clears back to the native default', async () => {
|
||||
const { app, ctx } = await setup();
|
||||
const session = ctx.sessions.get('test-session-1')!;
|
||||
@@ -203,6 +224,10 @@ describe('POST /api/sessions/:id/custom-model', () => {
|
||||
const { app, ctx } = await setup();
|
||||
const session = ctx.sessions.get('test-session-1')!;
|
||||
session.mode = 'pi';
|
||||
// Start from no dir at all (a sibling test's successful pi apply may have left one),
|
||||
// so the existsSync below says something about THIS request.
|
||||
const dir = join(getDataDir(), 'custom-model-configs', 'test-session-1');
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
@@ -214,8 +239,45 @@ describe('POST /api/sessions/:id/custom-model', () => {
|
||||
expect(res.json().errorCode).toBe('INVALID_INPUT');
|
||||
expect(session.setCustomModel).not.toHaveBeenCalled();
|
||||
expect(session.restartCli).not.toHaveBeenCalled();
|
||||
// The config dir written before the check is cleaned up again.
|
||||
expect(existsSync(join(getDataDir(), 'custom-model-configs', 'test-session-1'))).toBe(false);
|
||||
// The pattern check runs on the pure build BEFORE any write, so a refused id leaves
|
||||
// no directory behind at all, nothing to clean up.
|
||||
expect(existsSync(dir)).toBe(false);
|
||||
});
|
||||
|
||||
it('codex: a refused forced launch id never touches the live config dir the session runs on as CODEX_HOME', async () => {
|
||||
const { app, ctx } = await setup();
|
||||
const session = ctx.sessions.get('test-session-1')!;
|
||||
session.mode = 'codex';
|
||||
|
||||
// First apply succeeds: the session now runs codex on qwen3:32b, whose config.toml
|
||||
// lives in the per-session dir the running CLI itself uses as CODEX_HOME.
|
||||
const ok = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-session-1/custom-model',
|
||||
payload: { endpointId: 'ep1', modelId: 'qwen3:32b' },
|
||||
});
|
||||
expect(ok.statusCode).toBe(200);
|
||||
const dir = join(getDataDir(), 'custom-model-configs', 'test-session-1');
|
||||
const written = join(dir, 'config.toml');
|
||||
expect(existsSync(written)).toBe(true);
|
||||
|
||||
// `@` is outside codex's `model-plain-colon` pattern. The pattern check now runs on
|
||||
// the pure build BEFORE any write, so the refusal must leave the dir, and the file
|
||||
// the live CLI reads, exactly as they were, rather than replacing and deleting the
|
||||
// CODEX_HOME of a session that stays on qwen3:32b.
|
||||
const before = readFileSync(written, 'utf8');
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-session-1/custom-model',
|
||||
payload: { endpointId: 'ep1', modelId: 'org/model@q4_k_m' },
|
||||
});
|
||||
|
||||
expect(res.json().success).toBe(false);
|
||||
expect(res.json().errorCode).toBe('INVALID_INPUT');
|
||||
expect(session.setCustomModel).toHaveBeenCalledTimes(1);
|
||||
expect(session.restartCli).toHaveBeenCalledTimes(1);
|
||||
expect(existsSync(dir)).toBe(true);
|
||||
expect(readFileSync(written, 'utf8')).toBe(before);
|
||||
});
|
||||
|
||||
it('clear removes the previous config dir the session reports', async () => {
|
||||
@@ -298,6 +360,28 @@ describe('POST /api/sessions/:id/custom-model', () => {
|
||||
expect(session.restartCli).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a model id the CLI cannot launch before asking anyone to evict a model', async () => {
|
||||
const { app, ctx } = await setup();
|
||||
const session = ctx.sessions.get('test-session-1')!;
|
||||
session.mode = 'codex';
|
||||
const other = createMockSession('other-session');
|
||||
other.name = 'w2-otherbox';
|
||||
other.customModel = { endpointId: 'ep1', modelId: 'llama3' };
|
||||
ctx.sessions.set('other-session', other);
|
||||
mockRunning([{ model: 'llama3', state: 'ready' }]);
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-session-1/custom-model',
|
||||
payload: { endpointId: 'ep1', modelId: 'org/model@q4_k_m' },
|
||||
});
|
||||
|
||||
// Agreeing to the swap first would only lead to this same 400.
|
||||
expect(res.json().requiresConfirmation).toBeUndefined();
|
||||
expect(res.json().errorCode).toBe('INVALID_INPUT');
|
||||
expect(session.setCustomModel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe('multi-user: the confirm dialog must not name a session the caller cannot access', () => {
|
||||
const saved: Record<string, string | undefined> = {};
|
||||
|
||||
@@ -449,6 +533,130 @@ describe('POST /api/sessions/:id/custom-model', () => {
|
||||
expect(session.restartCli).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('the endpoint defaultContextLength stands in when discovery recorded no per-model figure', async () => {
|
||||
const { app, ctx } = await setup();
|
||||
// A gateway that states nothing per model: only the user's default is known.
|
||||
const endpoint: CustomModelHost = {
|
||||
id: 'ep-default',
|
||||
label: 'silent gateway',
|
||||
baseUrl: 'http://192.168.1.53:8080',
|
||||
apiKey: 'k',
|
||||
defaultContextLength: 16384,
|
||||
};
|
||||
await writeCustomModelHosts(getDataDir(), [CLAUDE_ENDPOINT, endpoint]);
|
||||
const session = ctx.sessions.get('test-session-1')!;
|
||||
session.mode = 'claude';
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-session-1/custom-model',
|
||||
payload: { endpointId: 'ep-default', modelId: 'some-unknown-model' },
|
||||
});
|
||||
|
||||
const body = res.json();
|
||||
expect(body.requiresContextWarning).toBe(true);
|
||||
expect(body.contextLength).toBe(16384);
|
||||
expect(session.setCustomModel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('a discovered per-model figure wins over the endpoint defaultContextLength', async () => {
|
||||
const { app, ctx } = await setup();
|
||||
// The default is small enough to warn on; the discovered figure for THIS model is
|
||||
// not, so the fallback must not leak into the per-model path.
|
||||
const endpoint: CustomModelHost = {
|
||||
id: 'ep-precedence',
|
||||
label: 'mixed box',
|
||||
baseUrl: 'http://192.168.1.54:8080',
|
||||
apiKey: 'k',
|
||||
modelContextLengths: { 'qwen3.8-27b-ud-q4_k_xl': 131072 },
|
||||
defaultContextLength: 16384,
|
||||
};
|
||||
await writeCustomModelHosts(getDataDir(), [CLAUDE_ENDPOINT, endpoint]);
|
||||
const session = ctx.sessions.get('test-session-1')!;
|
||||
session.mode = 'claude';
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-session-1/custom-model',
|
||||
payload: { endpointId: 'ep-precedence', modelId: 'qwen3.8-27b-ud-q4_k_xl' },
|
||||
});
|
||||
|
||||
expect(res.json().requiresContextWarning).toBeUndefined();
|
||||
expect(session.setCustomModel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// llama-server splits its context across --parallel slots, and Claude Code sends several
|
||||
// requests at once, so a context that clears the floor as a whole can still fail per slot.
|
||||
describe('parallel slots share the context', () => {
|
||||
const slotEndpoint = (contextLength: number, slots?: number): CustomModelHost => ({
|
||||
id: 'ep-slots',
|
||||
label: 'multi-slot box',
|
||||
baseUrl: 'http://192.168.1.52:8080',
|
||||
apiKey: 'k',
|
||||
modelContextLengths: { m: contextLength },
|
||||
...(slots === undefined ? {} : { modelSlotCounts: { m: slots } }),
|
||||
});
|
||||
|
||||
async function apply(endpoint: CustomModelHost) {
|
||||
const { app, ctx } = await setup();
|
||||
await writeCustomModelHosts(getDataDir(), [CLAUDE_ENDPOINT, endpoint]);
|
||||
const session = ctx.sessions.get('test-session-1')!;
|
||||
session.mode = 'claude';
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-session-1/custom-model',
|
||||
payload: { endpointId: endpoint.id, modelId: 'm' },
|
||||
});
|
||||
return { body: res.json(), session };
|
||||
}
|
||||
|
||||
it('warns when the context divided across the slots is below the floor, and reports the slot count', async () => {
|
||||
// the measured case: ~131k shared by 4 slots is ~33k each, under the 40k a request needs
|
||||
const { body, session } = await apply(slotEndpoint(131072, 4));
|
||||
|
||||
expect(body.requiresContextWarning).toBe(true);
|
||||
expect(body.contextLength).toBe(131072);
|
||||
expect(body.slotCount).toBe(4);
|
||||
expect(session.setCustomModel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('divides the discovered context across the slots even when it clears the floor as a whole', async () => {
|
||||
// 65,536 over 4 slots is 16,384 each: nothing the server reports can widen this pool
|
||||
const { body } = await apply(slotEndpoint(65536, 4));
|
||||
|
||||
expect(body.requiresContextWarning).toBe(true);
|
||||
expect(body.contextLength).toBe(65536);
|
||||
expect(body.slotCount).toBe(4);
|
||||
});
|
||||
|
||||
it('does not warn once every slot can hold the floor', async () => {
|
||||
const { body, session } = await apply(slotEndpoint(262144, 4)); // 65,536 each
|
||||
|
||||
expect(body.requiresContextWarning).toBeUndefined();
|
||||
expect(session.setCustomModel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not warn for a single slot with the same context that failed across four', async () => {
|
||||
const { body, session } = await apply(slotEndpoint(131072, 1));
|
||||
|
||||
expect(body.requiresContextWarning).toBeUndefined();
|
||||
expect(session.setCustomModel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('an unknown slot count is treated as one slot, never guessed', async () => {
|
||||
const { body } = await apply(slotEndpoint(131072));
|
||||
|
||||
expect(body.requiresContextWarning).toBeUndefined();
|
||||
});
|
||||
|
||||
it('omits slotCount from the warning when the context is too small on its own with a single slot', async () => {
|
||||
const { body } = await apply(slotEndpoint(16384, 1));
|
||||
|
||||
expect(body.requiresContextWarning).toBe(true);
|
||||
expect(body.slotCount).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
it('applies once confirmed, skipping the context check the second time', async () => {
|
||||
const { app, ctx } = await setup();
|
||||
await writeCustomModelHosts(getDataDir(), [CLAUDE_ENDPOINT, SMALL_CTX_ENDPOINT]);
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
@@ -131,6 +131,35 @@ describe('PUT /api/sessions/:id/name', () => {
|
||||
expect(transcriptRows()).toHaveLength(before + 1);
|
||||
});
|
||||
|
||||
it("finds the transcript in the session's relocated Claude config folder when no hook has named it (#701)", async () => {
|
||||
// Before the first hook after a restart the watcher has no path, and the scan used to
|
||||
// look under ~/.claude alone, so a session on another account kept its old /resume title.
|
||||
const configDir = join(transcriptDir, 'claude-clients', 'acme');
|
||||
const projectDir = join(configDir, 'projects', '-tmp');
|
||||
mkdirSync(projectDir, { recursive: true });
|
||||
const relocatedPath = join(projectDir, `${session.id}.jsonl`);
|
||||
writeFileSync(relocatedPath, `${JSON.stringify({ type: 'user', message: { role: 'user', content: 'hi' } })}\n`);
|
||||
const hookPath = harness.ctx.getTranscriptPath;
|
||||
(harness.ctx as Record<string, unknown>).getTranscriptPath = () => null;
|
||||
Object.defineProperty(session, 'claudeConfigDir', { configurable: true, value: () => configDir });
|
||||
try {
|
||||
const res = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: `/api/sessions/${session.id}/name`,
|
||||
payload: { name: 'client work' },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const rows = readFileSync(relocatedPath, 'utf8')
|
||||
.split('\n')
|
||||
.filter(Boolean)
|
||||
.map((line) => JSON.parse(line) as Record<string, unknown>);
|
||||
expect(rows.at(-1)).toEqual({ type: 'custom-title', customTitle: 'client work', sessionId: session.id });
|
||||
} finally {
|
||||
delete (session as unknown as Record<string, unknown>).claudeConfigDir;
|
||||
(harness.ctx as Record<string, unknown>).getTranscriptPath = hookPath;
|
||||
}
|
||||
});
|
||||
|
||||
it('writes no title row for a docker session, whose transcript lives in the container', async () => {
|
||||
const before = transcriptRows().length;
|
||||
Object.defineProperty(session, 'docker', { configurable: true, get: () => ({ caseName: 'c' }) });
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
* @fileoverview Agent-skill injection on POST /api/sessions (docs/agent-control-plan.md §2).
|
||||
*
|
||||
* The quick-start half of this is covered end-to-end in test/quick-start.test.ts;
|
||||
* the plain create path had NO coverage, because the shared mock context hardcoded
|
||||
* `getAgentSkillEnabled` to false and nothing could flip it. This exercises the real
|
||||
* the plain create path had NO coverage, because the shared mock context once hardcoded
|
||||
* `getAgentSkillEnabled` to false and nothing could flip it (it now defaults to true,
|
||||
* the shipped default since 1.50.0, and takes an override). This exercises the real
|
||||
* `applyAgentSkill` against a temp working dir, so it asserts bytes on disk rather
|
||||
* than a spy call.
|
||||
*
|
||||
@@ -81,6 +82,27 @@ describe('POST /api/sessions agent-skill injection', () => {
|
||||
// remove what this create wrote.
|
||||
expect(skillMd).toContain(MARKER_PREFIX);
|
||||
expect(existsSync(join(skillDir(), 'reference', 'endpoints.md'))).toBe(true);
|
||||
// The copy ignores itself, so the default leaves the user's `git status` clean.
|
||||
expect(await readFile(join(skillDir(), '.gitignore'), 'utf-8')).toBe('*\n');
|
||||
});
|
||||
|
||||
it('injects with the shared mock context left at its default (the shipped default is ON)', async () => {
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
const ctx = createMockRouteContext();
|
||||
registerSessionRoutes(app, ctx);
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
harness = { app, ctx };
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions',
|
||||
payload: { name: 'skill-default', mode: 'claude', workingDir },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(existsSync(join(skillDir(), 'SKILL.md'))).toBe(true);
|
||||
});
|
||||
|
||||
it('leaves the working dir untouched when the gate is OFF', async () => {
|
||||
|
||||
@@ -598,3 +598,141 @@ describe('GET /api/sessions/:id/last-response (claude conversation pinning)', ()
|
||||
expect(near.adoptClaudeSessionId).toHaveBeenCalledWith('fresh-conversation');
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /api/sessions/:id/last-response (relocated Claude config folder, #701)', () => {
|
||||
let harness: LocalHarness;
|
||||
let testHome: string;
|
||||
let relocated: string;
|
||||
let previousHome: string | undefined;
|
||||
let previousConfigDir: string | undefined;
|
||||
const WORKDIR = '/workspace';
|
||||
const NOW = 1_770_000_000_000;
|
||||
|
||||
beforeEach(async () => {
|
||||
testHome = mkdtempSync(join(tmpdir(), 'codeman-claude-relocated-'));
|
||||
relocated = join(testHome, 'claude-clients', 'acme');
|
||||
previousHome = process.env.HOME;
|
||||
previousConfigDir = process.env.CLAUDE_CONFIG_DIR;
|
||||
process.env.HOME = testHome;
|
||||
delete process.env.CLAUDE_CONFIG_DIR;
|
||||
harness = await createEnvelopeHarness();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (previousHome === undefined) delete process.env.HOME;
|
||||
else process.env.HOME = previousHome;
|
||||
if (previousConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
|
||||
else process.env.CLAUDE_CONFIG_DIR = previousConfigDir;
|
||||
rmSync(testHome, { recursive: true, force: true });
|
||||
await harness.app.close();
|
||||
});
|
||||
|
||||
/** A one-answer transcript under `<configDir>/projects`, stamped at `mtimeMs`. */
|
||||
function writeTranscript(configDir: string, conversationId: string, text: string, mtimeMs = NOW - 60_000): void {
|
||||
const projectDir = join(configDir, 'projects', '-workspace');
|
||||
mkdirSync(projectDir, { recursive: true });
|
||||
const path = join(projectDir, `${conversationId}.jsonl`);
|
||||
writeFileSync(
|
||||
path,
|
||||
JSON.stringify({
|
||||
type: 'assistant',
|
||||
timestamp: new Date(mtimeMs).toISOString(),
|
||||
message: { content: [{ type: 'text', text }] },
|
||||
})
|
||||
);
|
||||
utimesSync(path, mtimeMs / 1000, mtimeMs / 1000);
|
||||
}
|
||||
|
||||
function writeHistory(configDir: string, sessionId: string, timestamp: number): void {
|
||||
mkdirSync(configDir, { recursive: true });
|
||||
writeFileSync(
|
||||
join(configDir, 'history.jsonl'),
|
||||
JSON.stringify({ display: 'prompt', project: WORKDIR, sessionId, timestamp })
|
||||
);
|
||||
}
|
||||
|
||||
/** Replaces the pre-seeded mock session with a Claude pane in WORKDIR. */
|
||||
function addPane(conversationId: string, opts: { configDir?: string; lastSubmitAt?: number; docker?: boolean } = {}) {
|
||||
const base = harness.ctx._session;
|
||||
const pane = Object.create(Object.getPrototypeOf(base)) as typeof base & {
|
||||
claudeSessionId: string;
|
||||
lastSubmitAt: number;
|
||||
claudeSessionIdIsFirstHand: boolean;
|
||||
claudeConfigDirOverride: string | undefined;
|
||||
adoptClaudeSessionId: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
Object.assign(pane, base, {
|
||||
id: 'pane-1',
|
||||
mode: 'claude',
|
||||
workingDir: WORKDIR,
|
||||
docker: opts.docker ? { containerName: 'codeman-case-acme' } : undefined,
|
||||
});
|
||||
pane.claudeSessionId = conversationId;
|
||||
pane.lastSubmitAt = opts.lastSubmitAt ?? 0;
|
||||
pane.claudeSessionIdIsFirstHand = false;
|
||||
pane.claudeConfigDirOverride = opts.configDir;
|
||||
pane.adoptClaudeSessionId = vi.fn((newId: string) => {
|
||||
pane.claudeSessionId = newId;
|
||||
});
|
||||
harness.ctx.sessions.set(pane.id, pane);
|
||||
return pane;
|
||||
}
|
||||
|
||||
async function getLastResponse(query = '') {
|
||||
const response = await harness.app.inject({ method: 'GET', url: `/api/sessions/pane-1/last-response${query}` });
|
||||
return JSON.parse(response.body).data as { text: string; messages?: unknown[] };
|
||||
}
|
||||
|
||||
it("reads the answer from the session's own config folder", async () => {
|
||||
addPane('conversation-a', { configDir: relocated });
|
||||
writeTranscript(relocated, 'conversation-a', 'the answer in the relocated folder');
|
||||
|
||||
expect((await getLastResponse()).text).toBe('the answer in the relocated folder');
|
||||
expect((await getLastResponse('?context=full')).messages).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("reads the server's own CLAUDE_CONFIG_DIR for a session without an override", async () => {
|
||||
process.env.CLAUDE_CONFIG_DIR = relocated;
|
||||
addPane('conversation-a');
|
||||
writeTranscript(relocated, 'conversation-a', 'the answer in the server folder');
|
||||
|
||||
expect((await getLastResponse()).text).toBe('the answer in the server folder');
|
||||
});
|
||||
|
||||
it('never shows a conversation of the same id from ~/.claude instead', async () => {
|
||||
const home = join(testHome, '.claude');
|
||||
writeTranscript(home, 'conversation-a', 'an answer from another account');
|
||||
|
||||
// The relocated folder has conversations, but not this one.
|
||||
addPane('conversation-a', { configDir: relocated });
|
||||
writeTranscript(relocated, 'another-conversation', 'not this pane');
|
||||
expect(await getLastResponse('?context=turn')).toEqual({ text: '', timestamp: '', messages: [] });
|
||||
|
||||
// And a relocated folder that is not there at all.
|
||||
addPane('conversation-a', { configDir: join(testHome, 'not-created-yet') });
|
||||
expect(await getLastResponse()).toEqual({ text: '', timestamp: '' });
|
||||
});
|
||||
|
||||
it("follows /clear through the relocated folder's history, not the one under ~/.claude", async () => {
|
||||
const pane = addPane('before-clear', { configDir: relocated, lastSubmitAt: NOW });
|
||||
writeTranscript(relocated, 'before-clear', 'answer before clear', NOW - 60_000);
|
||||
writeTranscript(relocated, 'after-clear', 'answer after clear', NOW + 500);
|
||||
writeHistory(relocated, 'after-clear', NOW + 120);
|
||||
// The default account typed in the same folder at the same moment.
|
||||
const home = join(testHome, '.claude');
|
||||
writeTranscript(home, 'default-account', 'an answer from the default account', NOW + 500);
|
||||
writeHistory(home, 'default-account', NOW + 100);
|
||||
|
||||
expect((await getLastResponse()).text).toBe('answer after clear');
|
||||
expect(pane.adoptClaudeSessionId).toHaveBeenCalledWith('after-clear');
|
||||
});
|
||||
|
||||
it("keeps a Docker session off its override, which names a folder inside the container", async () => {
|
||||
const home = join(testHome, '.claude');
|
||||
writeTranscript(home, 'conversation-a', 'what the host folder holds');
|
||||
writeTranscript(relocated, 'conversation-a', 'a host folder that only shares the path');
|
||||
addPane('conversation-a', { configDir: relocated, docker: true });
|
||||
|
||||
expect((await getLastResponse()).text).toBe('what the host folder holds');
|
||||
});
|
||||
});
|
||||
@@ -89,6 +89,32 @@ describe('Codex launch defaults', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('fills Allow network access into every local codex launch, and an explicit value wins', async () => {
|
||||
await writeFile(SETTINGS_PATH, JSON.stringify({ codexNetworkAccess: true }));
|
||||
expect(await resolveCodexDefaults(undefined)).toEqual({ networkAccess: true });
|
||||
expect(buildCodexCommand(await resolveCodexDefaults(undefined))).toBe(
|
||||
'codex --config sandbox_workspace_write.network_access=true'
|
||||
);
|
||||
// The browser sends a codexConfig without the field, so the default still applies.
|
||||
expect(await resolveCodexDefaults({ dangerouslyBypassApprovals: false })).toEqual({
|
||||
dangerouslyBypassApprovals: false,
|
||||
networkAccess: true,
|
||||
});
|
||||
expect(await resolveCodexDefaults({ networkAccess: false })).toEqual({ networkAccess: false });
|
||||
// Off (and a malformed value) fills nothing, so the launch stays byte-identical.
|
||||
for (const value of [false, 'yes']) {
|
||||
await writeFile(SETTINGS_PATH, JSON.stringify({ codexNetworkAccess: value }));
|
||||
expect(await resolveCodexDefaults(undefined)).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
for (const url of ['/api/sessions', '/api/quick-start']) {
|
||||
it(`records Allow network access on a codex session created at ${url}`, async () => {
|
||||
await writeFile(SETTINGS_PATH, JSON.stringify({ codexNetworkAccess: true }));
|
||||
expect(await createdConfig(url)).toMatchObject({ networkAccess: true });
|
||||
});
|
||||
}
|
||||
|
||||
it('keeps defaults out of custom endpoint launches', async () => {
|
||||
const config = { model: 'local-model', animations: false };
|
||||
expect(await resolveCodexDefaults(config, true)).toBe(config);
|
||||
@@ -100,6 +126,7 @@ describe('Codex launch defaults', () => {
|
||||
expect(getCli('codex')!.capabilities.launchDefaults).toEqual({
|
||||
model: 'codexModel',
|
||||
reasoningEffort: 'codexReasoningEffort',
|
||||
networkAccess: 'codexNetworkAccess',
|
||||
});
|
||||
for (const entry of STOCK_CLIS) {
|
||||
if ((entry.id as string) === 'codex') continue;
|
||||
|
||||
@@ -14,9 +14,11 @@
|
||||
* block without it lost the "You" badge on prompts
|
||||
* - a pane that has produced no output reports hasContext: false rather than 404ing
|
||||
* - Claude mode still takes the Claude path (regression guard)
|
||||
* - copilot (a repainting full-screen TUI) is read off the pane SCREEN via
|
||||
* capturePaneText, and falls back to the buffer only when there is no screen
|
||||
*/
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { createMockRouteContext, createMockSession, type MockRouteContext } from '../mocks/index.js';
|
||||
@@ -154,6 +156,83 @@ describe('GET /api/sessions/:id/last-response — external CLI panes', () => {
|
||||
expect(body.data.hasContext).toBe(false);
|
||||
});
|
||||
|
||||
describe('copilot reads the pane screen, not the stream', () => {
|
||||
const rule = '─'.repeat(80);
|
||||
const screenOf = (answer: string) =>
|
||||
[
|
||||
' ❯ what changed 11:30',
|
||||
` ● ${answer}`,
|
||||
' /tmp/work Session: 0 AIC used',
|
||||
rule,
|
||||
'❯',
|
||||
rule,
|
||||
' ← open sidebar · Interactive · Manual Approval · / commands · ? help',
|
||||
].join('\n');
|
||||
|
||||
function stubCapture(result: string | null) {
|
||||
const capturePaneText = vi.fn((_muxName: string) => result);
|
||||
(harness.ctx.mux as unknown as { capturePaneText: typeof capturePaneText }).capturePaneText = capturePaneText;
|
||||
return capturePaneText;
|
||||
}
|
||||
|
||||
it('segments the captured screen of the session pane', async () => {
|
||||
session.mode = 'copilot';
|
||||
// What the stream looks like for a repainting TUI once escapes are stripped: rows fused
|
||||
// together, so a reader of the buffer would return this run of text.
|
||||
session.terminalBuffer = 'STREAM-ONLY fused rows that are not the answer';
|
||||
const capture = stubCapture(screenOf('The screen answer.'));
|
||||
|
||||
const { res, body } = await lastResponse();
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(capture).toHaveBeenCalledWith(session.muxName);
|
||||
expect(body.data.text).toBe('The screen answer.');
|
||||
expect(body.data.text).not.toContain('STREAM-ONLY');
|
||||
expect(body.data.hasContext).toBe(true);
|
||||
});
|
||||
|
||||
it('falls back to the buffer when the pane has no screen to capture', async () => {
|
||||
session.mode = 'copilot';
|
||||
session.terminalBuffer = screenOf('The buffer answer.');
|
||||
const capture = stubCapture(null);
|
||||
|
||||
const { res, body } = await lastResponse();
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(capture).toHaveBeenCalledWith(session.muxName);
|
||||
expect(body.data.text).toBe('The buffer answer.');
|
||||
});
|
||||
|
||||
it('never captures the screen for a mode that streams lines', async () => {
|
||||
session.mode = 'opencode';
|
||||
session.terminalBuffer = PANE;
|
||||
const capture = stubCapture(screenOf('must not be read'));
|
||||
|
||||
const { body } = await lastResponse();
|
||||
|
||||
expect(capture).not.toHaveBeenCalled();
|
||||
expect(body.data.text).toContain('Documented the helper in docs/retry.md');
|
||||
});
|
||||
});
|
||||
|
||||
it('answers jcode with an honest empty, never a segmented pane', async () => {
|
||||
// jcode is a repainting alternate-screen TUI: segmenting its stream served the
|
||||
// welcome banner as "the answer" (measured on a live pane), and the Claude scan
|
||||
// below the external branch could adopt a Claude conversation from the same folder.
|
||||
// It has no transcript reader yet, so "nothing said yet" is the only honest reply.
|
||||
session.mode = 'jcode';
|
||||
session.terminalBuffer = PANE;
|
||||
|
||||
const { res, body } = await lastResponse();
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(body.data.text).toBe('');
|
||||
expect(body.data.messages).toBeUndefined();
|
||||
|
||||
const full = await lastResponse(true);
|
||||
expect(full.body.data.text).toBe('');
|
||||
expect(full.body.data.messages).toEqual([]);
|
||||
});
|
||||
|
||||
it('leaves Claude mode on the Claude transcript path', async () => {
|
||||
// Regression guard: a claude pane must NOT be segmented off its terminal
|
||||
// buffer, or a real transcript would be shadowed by scraped pane text.
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* `POST /api/sessions/:id/git-fetch-settings` (session-routes.ts): the per-case half of the fetch interval
|
||||
* (src/git-fetch-scheduler.ts): the case's own switch and its own interval. `null` on either half clears
|
||||
* that half so the app-wide setting applies again, and a body that names one row leaves the other as it was,
|
||||
* because the Session Options rows save on their own. Refused for remote and Docker cases, the same rule the
|
||||
* Git panel and the scheduler use. app.inject(), no port.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
|
||||
interface Harness {
|
||||
app: FastifyInstance;
|
||||
ctx: MockRouteContext;
|
||||
}
|
||||
|
||||
async function createHarness(): Promise<Harness> {
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
const ctx = createMockRouteContext();
|
||||
registerSessionRoutes(app, ctx);
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
return { app, ctx };
|
||||
}
|
||||
|
||||
describe('POST /api/sessions/:id/git-fetch-settings', () => {
|
||||
let harness: Harness;
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createHarness();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
});
|
||||
|
||||
const post = (payload: unknown) =>
|
||||
harness.app.inject({ method: 'POST', url: `/api/sessions/${harness.ctx._sessionId}/git-fetch-settings`, payload });
|
||||
|
||||
it('stores the case’s own choice, persists and broadcasts it', async () => {
|
||||
const res = await post({ enabled: true, intervalSeconds: 120 });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).data.gitFetchSettings).toEqual({ enabled: true, intervalSeconds: 120 });
|
||||
expect(harness.ctx._session.gitFetchEnabled).toBe(true);
|
||||
expect(harness.ctx._session.gitFetchIntervalSeconds).toBe(120);
|
||||
expect(harness.ctx.persistSessionState).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('answers `null` for a case that follows the app, which is what the Session Options row shows', async () => {
|
||||
const data = JSON.parse((await post({})).body).data.gitFetchSettings;
|
||||
expect(data).toEqual({ enabled: null, intervalSeconds: null });
|
||||
});
|
||||
|
||||
it('clears the override on null so the app-wide setting applies again', async () => {
|
||||
await post({ enabled: true, intervalSeconds: 120 });
|
||||
const res = await post({ enabled: null, intervalSeconds: null });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(harness.ctx._session.gitFetchEnabled).toBeUndefined();
|
||||
expect(harness.ctx._session.gitFetchIntervalSeconds).toBeUndefined();
|
||||
expect(JSON.parse(res.body).data.gitFetchSettings).toEqual({ enabled: null, intervalSeconds: null });
|
||||
});
|
||||
|
||||
it('leaves the other half as it was when only one row was saved', async () => {
|
||||
await post({ enabled: true });
|
||||
expect(harness.ctx._session.gitFetchIntervalSeconds).toBeUndefined(); // still following the app on that half
|
||||
const res = await post({ intervalSeconds: 90 });
|
||||
expect(JSON.parse(res.body).data.gitFetchSettings).toEqual({ enabled: true, intervalSeconds: 90 });
|
||||
});
|
||||
|
||||
it('rejects an interval outside the schema bounds, storing nothing, because that is what the scheduler acts on', async () => {
|
||||
// `null` is NOT on this list: it is the schema's way of clearing the override, tested above.
|
||||
for (const raw of [29, 3601, 12.5, '120', true]) {
|
||||
const res = await post({ enabled: true, intervalSeconds: raw });
|
||||
expect(res.statusCode, String(raw)).toBe(400);
|
||||
}
|
||||
expect(harness.ctx._session.gitFetchEnabled).toBeUndefined();
|
||||
expect(harness.ctx.persistSessionState).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['remote', { host: 'h', user: 'u' }],
|
||||
['docker', { container: 'c' }],
|
||||
])('refuses a %s case, storing nothing', async (kind, value) => {
|
||||
(harness.ctx._session as unknown as Record<string, unknown>)[kind] = value;
|
||||
const res = await post({ enabled: true, intervalSeconds: 120 });
|
||||
expect(JSON.parse(res.body)).toMatchObject({ success: false, errorCode: 'INVALID_INPUT' });
|
||||
expect(harness.ctx._session.gitFetchEnabled).toBeUndefined();
|
||||
expect(harness.ctx.persistSessionState).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('404s an unknown session, storing nothing', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/nope/git-fetch-settings',
|
||||
payload: { enabled: true },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
expect(harness.ctx.persistSessionState).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* `POST /api/sessions/:id/keep-warm` (session-routes.ts): the per-session opt-in for the
|
||||
* prompt-cache keep-warm. Stores the choice, persists and broadcasts the session, asks the
|
||||
* scheduler to re-evaluate, clears the choice on `null`, and refuses a CLI with no cache
|
||||
* telemetry. app.inject(), no port.
|
||||
*/
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import { createMockRouteContext, type MockRouteContext } from '../mocks/index.js';
|
||||
import { installRouteErrorHandler } from '../../src/web/route-error-handler.js';
|
||||
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
|
||||
|
||||
interface Harness {
|
||||
app: FastifyInstance;
|
||||
ctx: MockRouteContext;
|
||||
}
|
||||
|
||||
async function createHarness(): Promise<Harness> {
|
||||
const app = Fastify({ logger: false });
|
||||
await app.register(fastifyCookie);
|
||||
const ctx = createMockRouteContext();
|
||||
registerSessionRoutes(app, ctx);
|
||||
installRouteErrorHandler(app);
|
||||
await app.ready();
|
||||
return { app, ctx };
|
||||
}
|
||||
|
||||
describe('POST /api/sessions/:id/keep-warm', () => {
|
||||
let harness: Harness;
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createHarness();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
});
|
||||
|
||||
const post = (payload: unknown) =>
|
||||
harness.app.inject({ method: 'POST', url: `/api/sessions/${harness.ctx._sessionId}/keep-warm`, payload });
|
||||
|
||||
it('stores the choice, persists, broadcasts and re-evaluates', async () => {
|
||||
const res = await post({ enabled: true });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(JSON.parse(res.body).data.keepWarm).toMatchObject({ enabled: true });
|
||||
expect(harness.ctx._session.keepWarmEnabled).toBe(true);
|
||||
expect(harness.ctx.persistSessionState).toHaveBeenCalled();
|
||||
expect(harness.ctx.keepWarm.schedule).toHaveBeenCalledWith(harness.ctx._sessionId);
|
||||
// The re-evaluation runs first, so the broadcast state and the response carry the new status.
|
||||
expect(harness.ctx.keepWarm.schedule.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
harness.ctx.persistSessionState.mock.invocationCallOrder[0]
|
||||
);
|
||||
});
|
||||
|
||||
it('clears the choice on null so the app-wide default applies again', async () => {
|
||||
await post({ enabled: false });
|
||||
const res = await post({ enabled: null });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(harness.ctx._session.keepWarmEnabled).toBeUndefined();
|
||||
expect(JSON.parse(res.body).data.keepWarm.enabled).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects a body without enabled', async () => {
|
||||
expect((await post({})).statusCode).toBe(400);
|
||||
});
|
||||
|
||||
it('refuses a CLI that reports no cache telemetry', async () => {
|
||||
harness.ctx._session.mode = 'shell';
|
||||
const res = await post({ enabled: true });
|
||||
// This harness has no envelope hook, so the refusal shows in the body, not the status.
|
||||
expect(JSON.parse(res.body)).toMatchObject({ success: false, errorCode: 'INVALID_INPUT' });
|
||||
expect(harness.ctx._session.keepWarmEnabled).toBeUndefined();
|
||||
expect(harness.ctx.keepWarm.schedule).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -104,7 +104,9 @@ describe('create routes: tabGroupId', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const data = body(res.body);
|
||||
expect(ctx.addSession.mock.calls[0][1]).toEqual({ tabGroupId: 'g1' });
|
||||
// quick-start always names its case too, for the case's default group (the
|
||||
// explicit group still wins inside TabLayoutService).
|
||||
expect(ctx.addSession.mock.calls[0][1]).toEqual({ caseName: 'tabgroupcase', tabGroupId: 'g1' });
|
||||
expect(data.tabLayout.groups[0].refs).toEqual([{ kind: 'session', id: data.sessionId }]);
|
||||
|
||||
const plain = await app.inject({
|
||||
|
||||
@@ -17,7 +17,7 @@ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import fastifyMultipart from '@fastify/multipart';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { dirname, extname, join } from 'node:path';
|
||||
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { registryFilePath, reloadCliRegistry } from '../../src/config/cli-registry/registry.js';
|
||||
import fs, { mkdtemp, rm, mkdir, writeFile, readFile, readdir, symlink } from 'node:fs/promises';
|
||||
@@ -25,7 +25,8 @@ import { tmpdir } from 'node:os';
|
||||
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 { GuardedInputBusyError, 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() }));
|
||||
@@ -264,6 +265,33 @@ describe('session-routes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('answers 409 CONFLICT, without an error log, when a guarded submit cannot hold the key', async () => {
|
||||
execFile.mockReset();
|
||||
const session = harness.ctx._session as unknown as {
|
||||
performAuxiliaryInput: (op: () => Promise<void>) => Promise<void>;
|
||||
};
|
||||
const original = session.performAuxiliaryInput;
|
||||
session.performAuxiliaryInput = async () => {
|
||||
throw new GuardedInputBusyError();
|
||||
};
|
||||
const errors = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
try {
|
||||
const res = await harness.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/sessions/test-session-1/send-key',
|
||||
payload: { key: 'S-Enter' },
|
||||
});
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toMatchObject({ success: false, errorCode: 'CONFLICT' });
|
||||
expect(res.json().error).toMatch(/guarded submit is in progress.*nothing was written/);
|
||||
expect(errors).not.toHaveBeenCalled();
|
||||
expect(execFile).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
errors.mockRestore();
|
||||
session.performAuxiliaryInput = original;
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects keys outside the hex allowlist without invoking tmux', async () => {
|
||||
execFile.mockReset();
|
||||
const res = await harness.app.inject({
|
||||
@@ -858,12 +886,39 @@ describe('session-routes', () => {
|
||||
for (const [name, bytes] of [
|
||||
['fake.pdf', png], // PNG bytes under a PDF name
|
||||
['fake.docx', pdf], // a PDF under an OOXML name
|
||||
['binary.txt', Buffer.from('hello\u0000world')], // a NUL byte is never text
|
||||
['latin1.csv', Buffer.from([0x61, 0x2c, 0xe9, 0x0a])], // not UTF-8
|
||||
] as const) {
|
||||
const res = await upload(name, 'application/octet-stream', bytes);
|
||||
expect(res.statusCode, name).toBe(415);
|
||||
expect(JSON.parse(res.body).error, name).toMatch(/do not match declared type/);
|
||||
expect(JSON.parse(res.body).error, name).toBe(`File bytes do not match declared type ${extname(name)}`);
|
||||
}
|
||||
expect(await readdir(workDir)).toEqual([]);
|
||||
await rm(workDir, { recursive: true });
|
||||
});
|
||||
|
||||
it('refuses non-UTF-8 text by naming the encoding, UTF-16 when a BOM says so', async () => {
|
||||
const workDir = await mkdtemp(join(tmpdir(), 'codeman-doc-'));
|
||||
harness.ctx._session.workingDir = workDir;
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
const notUtf8 = (ext: string) => `This ${ext} file is not UTF-8 text; save it as UTF-8 and attach it again`;
|
||||
const utf16 = (ext: string) => `This ${ext} file is UTF-16 text, not UTF-8; save it as UTF-8 and attach it again`;
|
||||
try {
|
||||
for (const [name, bytes, error, reason] of [
|
||||
// Excel "Unicode Text" / Notepad "Unicode": UTF-16LE with its BOM.
|
||||
['export.txt', Buffer.from('\ufeffa\tb\n', 'utf16le'), utf16('.txt'), 'utf16-bom'],
|
||||
['export.csv', Buffer.from([0xfe, 0xff, 0x00, 0x61, 0x00, 0x0a]), utf16('.csv'), 'utf16-bom'], // UTF-16BE
|
||||
['binary.txt', Buffer.from('hello\u0000world'), notUtf8('.txt'), 'nul-byte'], // NUL, no BOM
|
||||
['latin1.csv', Buffer.from('a,René\n', 'latin1'), notUtf8('.csv'), 'not-utf8'], // Excel's default CSV
|
||||
] as const) {
|
||||
warn.mockClear();
|
||||
const res = await upload(name, 'application/octet-stream', bytes);
|
||||
expect(res.statusCode, name).toBe(415);
|
||||
expect(JSON.parse(res.body).error, name).toBe(error);
|
||||
expect(String(warn.mock.calls[0]?.[0]), name).toMatch(
|
||||
new RegExp(`declaredExt=\\S+ size=\\d+ reason=${reason}$`)
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
warn.mockRestore();
|
||||
}
|
||||
expect(await readdir(workDir)).toEqual([]);
|
||||
await rm(workDir, { recursive: true });
|
||||
@@ -956,6 +1011,27 @@ describe('session-routes', () => {
|
||||
// with no broadcast, so other open tabs kept showing the retired row until
|
||||
// their next unrelated fetch.
|
||||
expect(harness.ctx.broadcast).toHaveBeenCalledWith('session:deleted', { id: 'ghost-session' });
|
||||
// Its stored edit history (diffs can hold secrets) goes with the record.
|
||||
expect(harness.ctx.forgetEditHistory).toHaveBeenCalledWith('ghost-session');
|
||||
});
|
||||
|
||||
it('keeps the edit history of a pinned persisted-only session whose record is only demoted', async () => {
|
||||
vi.mocked(harness.ctx.store.getSession).mockReturnValueOnce({ id: 'pinned-ghost', owner: undefined } as never);
|
||||
vi.mocked(harness.ctx.store.demoteOrRemoveSession).mockReturnValueOnce('preserved');
|
||||
const res = await harness.app.inject({ method: 'DELETE', url: '/api/sessions/pinned-ghost' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(harness.ctx.forgetEditHistory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
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 () => {
|
||||
@@ -1158,6 +1234,93 @@ describe('session-routes', () => {
|
||||
expect(session.writeBuffer).toEqual(['prompt', '\r']);
|
||||
});
|
||||
|
||||
it('refuses tagged input with 409 and gives the seq back while a guarded submit holds the input lease', async () => {
|
||||
const url = `/api/sessions/${harness.ctx._sessionId}/input`;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const session = harness.ctx.sessions.get(harness.ctx._sessionId) as any;
|
||||
session.writeBuffer.length = 0;
|
||||
const post = (payload: unknown) => harness.app.inject({ method: 'POST', url, payload });
|
||||
session.guardedInputHeld = true;
|
||||
for (const payload of [
|
||||
{ input: 'tagged', seq: 7, clientId: 'cid-guard' },
|
||||
{ input: 'prompt\r', useMux: true, seq: 1, clientId: 'cid-guard-mux' },
|
||||
]) {
|
||||
const refused = await post(payload);
|
||||
expect(refused.statusCode, JSON.stringify(payload)).toBe(409);
|
||||
expect(refused.json()).toMatchObject({ success: false, errorCode: 'CONFLICT' });
|
||||
expect(refused.json().error).toMatch(/guarded submit is in progress.*nothing was written/);
|
||||
}
|
||||
expect(session.writeBuffer).toEqual([]);
|
||||
expect(session.heldGuardedInput).toEqual([]);
|
||||
// Once the lease is released the browser's retry of the same seq is applied, not
|
||||
// rejected as a duplicate.
|
||||
session.releaseGuardedLease();
|
||||
expect((await post({ input: 'tagged', seq: 7, clientId: 'cid-guard' })).statusCode).toBe(200);
|
||||
expect(session.writeBuffer).toEqual(['tagged']);
|
||||
});
|
||||
|
||||
it('holds an untagged raw POST during a guarded submit and writes it once the lease is released', async () => {
|
||||
// The phone accessory keys and the Stop button's Ctrl+C are untagged, fire-and-forget
|
||||
// POSTs that never read the answer, so a 409 here silently lost the tap.
|
||||
const url = `/api/sessions/${harness.ctx._sessionId}/input`;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const session = harness.ctx.sessions.get(harness.ctx._sessionId) as any;
|
||||
session.writeBuffer.length = 0;
|
||||
session.guardedInputHeld = true;
|
||||
try {
|
||||
for (const input of ['\x03', '\x1b[A']) {
|
||||
const res = await harness.app.inject({ method: 'POST', url, payload: { input } });
|
||||
expect(res.statusCode, JSON.stringify(input)).toBe(200);
|
||||
expect(res.json()).toMatchObject({ success: true });
|
||||
}
|
||||
expect(session.writeBuffer).toEqual([]);
|
||||
session.releaseGuardedLease();
|
||||
expect(session.writeBuffer).toEqual(['\x03', '\x1b[A']);
|
||||
} finally {
|
||||
session.releaseGuardedLease();
|
||||
}
|
||||
});
|
||||
|
||||
it('lets untagged mux input wait its own turn behind the lease instead of refusing it', async () => {
|
||||
const url = `/api/sessions/${harness.ctx._sessionId}/input`;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const session = harness.ctx.sessions.get(harness.ctx._sessionId) as any;
|
||||
session.writeBuffer.length = 0;
|
||||
const post = (payload: unknown) => harness.app.inject({ method: 'POST', url, payload });
|
||||
session.guardedInputHeld = true;
|
||||
try {
|
||||
// Fire-and-forget `useMux`: answered at once, written in its turn.
|
||||
expect((await post({ input: 'x', useMux: true })).statusCode).toBe(200);
|
||||
// A plain prompt's mux write is awaited, so it answers once written.
|
||||
const prompt = post({ input: 'prompt\r' });
|
||||
await vi.waitFor(() => expect(session.heldGuardedInput).toHaveLength(2));
|
||||
expect(session.writeBuffer).toEqual([]);
|
||||
session.releaseGuardedLease();
|
||||
expect((await prompt).statusCode).toBe(200);
|
||||
expect(session.writeBuffer).toEqual(['x', 'prompt\r']);
|
||||
} finally {
|
||||
session.releaseGuardedLease();
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses an untagged raw POST with 409 only when the hold queue is full', async () => {
|
||||
const url = `/api/sessions/${harness.ctx._sessionId}/input`;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const session = harness.ctx.sessions.get(harness.ctx._sessionId) as any;
|
||||
session.writeBuffer.length = 0;
|
||||
session.guardedInputHeld = true;
|
||||
session.holdForGuardedLease = () => 'full';
|
||||
try {
|
||||
const res = await harness.app.inject({ method: 'POST', url, payload: { input: '\x03' } });
|
||||
expect(res.statusCode).toBe(409);
|
||||
expect(res.json()).toMatchObject({ success: false, errorCode: 'CONFLICT' });
|
||||
expect(session.writeBuffer).toEqual([]);
|
||||
} finally {
|
||||
delete session.holdForGuardedLease;
|
||||
session.releaseGuardedLease();
|
||||
}
|
||||
});
|
||||
|
||||
it('always applies untagged input (curl/legacy, no dedup)', async () => {
|
||||
const url = `/api/sessions/${harness.ctx._sessionId}/input`;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
@@ -2586,6 +2749,26 @@ describe('session-routes', () => {
|
||||
expect(row.workingDir).not.toBe(home);
|
||||
});
|
||||
|
||||
it("resumes a renamed case's conversation in the new folder, not the stale cwd in the transcript", async () => {
|
||||
const home = process.env.HOME as string;
|
||||
const realDir = join(home, 'renamed-case');
|
||||
await mkdir(realDir, { recursive: true });
|
||||
|
||||
const projectKey = realDir.replace(/[^a-zA-Z0-9]/g, '-');
|
||||
const projDir = join(home, '.claude', 'projects', projectKey);
|
||||
await mkdir(projDir, { recursive: true });
|
||||
|
||||
const sessionId = '33333333-3333-3333-3333-333333333333';
|
||||
const line =
|
||||
JSON.stringify({ type: 'user', cwd: join(home, 'old-case-name'), message: { role: 'user', content: 'hi' } }) +
|
||||
'\n';
|
||||
await writeFile(join(projDir, `${sessionId}.jsonl`), line + '#'.repeat(4200 - line.length));
|
||||
|
||||
const res = await harness.app.inject({ method: 'GET', url: `/api/history/sessions?projectKey=${projectKey}` });
|
||||
const row = JSON.parse(res.body).data.sessions.find((s: { sessionId: string }) => s.sessionId === sessionId);
|
||||
expect(row.workingDir).toBe(realDir);
|
||||
});
|
||||
|
||||
it('prefers the dotdir over a same-named non-dot sibling, and never emits a "//" path', async () => {
|
||||
// A doubled dash also lets the decoder read the empty split segment as a
|
||||
// directory NAME. `isDir(current + '/' + '')` stats `current + '/'`, which
|
||||
|
||||
@@ -52,6 +52,35 @@ describe('POST /api/status-telemetry', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('context report (auto-compact and auto-clear)', () => {
|
||||
const noted = () => h.ctx._session.noteContextReport as ReturnType<typeof vi.fn>;
|
||||
const context = (cw: Record<string, unknown>) => ({ sessionId: SID, data: { context_window: cw } });
|
||||
|
||||
it('hands the context size and the window to the session', async () => {
|
||||
const res = await post(context({ total_input_tokens: 562411, context_window_size: 1000000 }));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(noted()).toHaveBeenCalledWith({ tokens: 562411, windowSize: 1000000 });
|
||||
});
|
||||
|
||||
it('accepts a null window and passes the tokens on without one', async () => {
|
||||
const res = await post(context({ total_input_tokens: 5, context_window_size: null }));
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(noted()).toHaveBeenCalledWith({ tokens: 5, windowSize: undefined });
|
||||
});
|
||||
|
||||
it('keeps the last report when a render carries no context size', async () => {
|
||||
await post(context({ used_percentage: 10 }));
|
||||
await post({ sessionId: SID, data: {} });
|
||||
expect(noted()).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('takes no report from a CLI without a statusline exporter', async () => {
|
||||
h.ctx._session.mode = 'shell';
|
||||
await post(context({ total_input_tokens: 562411 }));
|
||||
expect(noted()).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it('does not broadcast for an unknown session; returns an EMPTY footer, never a brand word', async () => {
|
||||
const res = await post({ sessionId: 'does-not-exist', data: REAL });
|
||||
expect(res.statusCode).toBe(200);
|
||||
|
||||
@@ -54,6 +54,11 @@ vi.mock('node:fs/promises', () => ({
|
||||
default: {
|
||||
readFile: vi.fn(async () => JSON.stringify(STORED)),
|
||||
writeFile: vi.fn(async () => undefined),
|
||||
// settings.json is written to a temp file and renamed over the real one (settings-writer.ts).
|
||||
realpath: vi.fn(async (p: string) => p),
|
||||
mkdir: vi.fn(async () => undefined),
|
||||
rename: vi.fn(async () => undefined),
|
||||
rm: vi.fn(async () => undefined),
|
||||
},
|
||||
}));
|
||||
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
*
|
||||
* PR #361 once made it reconcile `showPlanUsageLimits` on first read: if the
|
||||
* key was absent, the route persisted `true`. But readJsonConfig() answers
|
||||
* `{}` for ANY read failure (parse error, EACCES, EMFILE, a read landing inside
|
||||
* PUT's non-atomic write), not only ENOENT, and every page load calls this
|
||||
* `{}` for ANY read failure (parse error, EACCES, EMFILE, and at the time a read
|
||||
* landing inside PUT's non-atomic write), not only ENOENT, and every page load calls this
|
||||
* route, so one unlucky read replaced the whole settings file with a one-key
|
||||
* file. The default now lives in the readers instead: an absent key means ON
|
||||
* to readPlanUsageTelemetryEnabled() (pinned in test/hooks-config.test.ts) and
|
||||
|
||||
@@ -47,18 +47,34 @@ const { EXISTING_SETTINGS, subagentWatcher, imageWatcher, workflowRunWatcher } =
|
||||
};
|
||||
};
|
||||
return {
|
||||
// Persisted settings.json for these tests: two watchers ON, subagent tracking OFF.
|
||||
EXISTING_SETTINGS: { subagentTrackingEnabled: false, imageWatcherEnabled: true, showUltracodeAgents: true },
|
||||
// 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),
|
||||
workflowRunWatcher: makeWatcher(true),
|
||||
};
|
||||
});
|
||||
|
||||
// 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)),
|
||||
writeFile: vi.fn(async () => undefined),
|
||||
// settings.json is written to a temp file and renamed over the real one (settings-writer.ts).
|
||||
realpath: vi.fn(async (p: string) => p),
|
||||
mkdir: vi.fn(async () => undefined),
|
||||
rename: vi.fn(async () => undefined),
|
||||
rm: vi.fn(async () => undefined),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -70,6 +86,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;
|
||||
@@ -81,6 +98,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 () => {
|
||||
@@ -143,4 +161,43 @@ describe('PUT /api/settings — partial body must not reset service toggles', ()
|
||||
// showUltracodeAgents is still true in settings.json, so it stays up.
|
||||
expect(workflowRunWatcher.stop).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
/**
|
||||
* The browser sends both keep-warm keys on every App Settings save, so testing for the keys in
|
||||
* the body re-read the settings and re-evaluated every session on each save of anything.
|
||||
*/
|
||||
it('re-evaluates the prompt-cache keep-warm only when its default or cap changes', async () => {
|
||||
const put = (payload: Record<string, unknown>) =>
|
||||
harness.app.inject({ method: 'PUT', url: '/api/settings', payload });
|
||||
|
||||
expect((await put({ promptCacheKeepWarm: false, promptCacheKeepWarmMaxHours: 2 })).statusCode).toBe(200);
|
||||
expect(harness.ctx.keepWarm.rescheduleAll).not.toHaveBeenCalled();
|
||||
|
||||
expect((await put({ promptCacheKeepWarm: false, promptCacheKeepWarmMaxHours: 3 })).statusCode).toBe(200);
|
||||
expect(harness.ctx.keepWarm.rescheduleAll).toHaveBeenCalledTimes(1);
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,25 +1,21 @@
|
||||
/**
|
||||
* @fileoverview COD-55 — tunnel password guard.
|
||||
*
|
||||
* Enabling the Cloudflare tunnel publishes the whole app (full terminal control =
|
||||
* effectively RCE) to a public *.trycloudflare.com URL. When no CODEMAN_PASSWORD
|
||||
* is set, requests through that URL are unauthenticated. These tests assert the
|
||||
* PUT /api/settings tunnel-enable path REFUSES to start the tunnel unless a
|
||||
* password is set OR the unauthenticated-network opt-in is acknowledged.
|
||||
*
|
||||
* Uses app.inject() — no real HTTP ports needed. Port: N/A.
|
||||
* @fileoverview Issue #706 keeps LAN acknowledgement separate from public tunnel consent. A login, tunnel-specific env opt-in, launch flag or per-request acknowledgement permits enabling. Early refusals persist nothing; late race refusals save unrelated settings without enabling the tunnel. Status reports login configuration independently of exposure opt-ins.
|
||||
*/
|
||||
|
||||
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';
|
||||
|
||||
// Settings are written to disk via fs/promises — stub so the guard test never
|
||||
// Settings are written to disk via fs/promises; stub so the guard test never
|
||||
// touches the real settings.json, and so we can assert "not persisted on refusal".
|
||||
vi.mock('node:fs/promises', () => ({
|
||||
default: {
|
||||
readFile: vi.fn(async () => '{}'),
|
||||
writeFile: vi.fn(async () => undefined),
|
||||
// settings.json is written to a temp file and renamed over the real one (settings-writer.ts).
|
||||
realpath: vi.fn(async (p: string) => p),
|
||||
mkdir: vi.fn(async () => undefined),
|
||||
rename: vi.fn(async () => undefined),
|
||||
rm: vi.fn(async () => undefined),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -34,129 +30,331 @@ vi.mock('node:fs', async (importOriginal) => {
|
||||
});
|
||||
|
||||
import fs from 'node:fs/promises';
|
||||
import { SETTINGS_PATH } from '../../src/web/route-helpers.js';
|
||||
const mockedWriteFile = vi.mocked(fs.writeFile);
|
||||
const mockedRename = vi.mocked(fs.rename);
|
||||
|
||||
/** Build a tunnelManager stub the route's ctx can use. */
|
||||
function makeTunnelManager(running = false) {
|
||||
/**
|
||||
* settings.json writes as [path, contents]. The writer (settings-writer.ts) writes each one to a
|
||||
* temp file and renames it over settings.json, so a write counts once its rename lands. Every
|
||||
* writeFile must be such a temp file and every one must be renamed into place: a direct write to
|
||||
* settings.json, or any other write that was never renamed, fails here rather than going unseen.
|
||||
*/
|
||||
function settingsWrites(): [string, string][] {
|
||||
const writes = mockedWriteFile.mock.calls.map(([path, contents]) => [String(path), String(contents)]);
|
||||
const renames = mockedRename.mock.calls.map(([from, to]) => [String(from), String(to)]);
|
||||
const isTemp = (path: string) => path.startsWith(`${SETTINGS_PATH}.`) && path.endsWith('.tmp');
|
||||
const notRenamed = writes.filter(([path]) => !isTemp(path) || !renames.some(([from]) => from === path));
|
||||
expect(
|
||||
notRenamed.map(([path]) => path),
|
||||
'writes that were not a temp file renamed into place'
|
||||
).toEqual([]);
|
||||
expect(renames.length, 'one rename per write').toBe(writes.length);
|
||||
return renames.map(([from, to]) => {
|
||||
const write = writes.find(([path]) => path === from);
|
||||
expect(write, `rename of ${from}, which was never written`).toBeDefined();
|
||||
return [to, String(write?.[1])];
|
||||
});
|
||||
}
|
||||
|
||||
const STATUS = { running: false, url: null };
|
||||
|
||||
function makeTunnelManager() {
|
||||
return {
|
||||
start: vi.fn(),
|
||||
stop: vi.fn(),
|
||||
isRunning: vi.fn(() => running),
|
||||
isRunning: vi.fn(() => false),
|
||||
getUrl: vi.fn(() => null),
|
||||
getStatus: vi.fn(() => ({ running })),
|
||||
getStatus: vi.fn(() => ({ ...STATUS })),
|
||||
};
|
||||
}
|
||||
|
||||
describe('COD-55 tunnel password guard (PUT /api/settings tunnelEnabled)', () => {
|
||||
describe('tunnel authentication policy', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let tunnel: ReturnType<typeof makeTunnelManager>;
|
||||
const savedPassword = process.env.CODEMAN_PASSWORD;
|
||||
const savedOptIn = process.env.CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK;
|
||||
const envKeys = [
|
||||
'CODEMAN_PASSWORD',
|
||||
'CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK',
|
||||
'CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL',
|
||||
'CODEMAN_MULTIUSER',
|
||||
] as const;
|
||||
let savedEnv: (string | undefined)[];
|
||||
|
||||
beforeEach(async () => {
|
||||
harness = await createRouteTestHarness(registerSystemRoutes);
|
||||
savedEnv = envKeys.map((key) => process.env[key]);
|
||||
for (const key of envKeys) delete process.env[key];
|
||||
harness = await createRouteTestHarness(registerSystemRoutes, {
|
||||
authUser: { username: 'root', role: 'admin' },
|
||||
});
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(fs.readFile).mockResolvedValue('{}');
|
||||
mockedWriteFile.mockResolvedValue(undefined);
|
||||
tunnel = makeTunnelManager(false);
|
||||
// tunnelManager is null in the default mock ctx — inject our spy.
|
||||
tunnel = makeTunnelManager();
|
||||
(harness.ctx as unknown as { tunnelManager: unknown }).tunnelManager = tunnel;
|
||||
delete process.env.CODEMAN_PASSWORD;
|
||||
delete process.env.CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK;
|
||||
(harness.ctx as unknown as { allowUnauthenticatedTunnel: boolean }).allowUnauthenticatedTunnel = false;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await harness.app.close();
|
||||
if (savedPassword === undefined) delete process.env.CODEMAN_PASSWORD;
|
||||
else process.env.CODEMAN_PASSWORD = savedPassword;
|
||||
if (savedOptIn === undefined) delete process.env.CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK;
|
||||
else process.env.CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK = savedOptIn;
|
||||
try {
|
||||
await harness?.app.close();
|
||||
} finally {
|
||||
envKeys.forEach((key, i) => {
|
||||
if (savedEnv[i] === undefined) delete process.env[key];
|
||||
else process.env[key] = savedEnv[i];
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('REFUSES tunnel-enable with no password and no opt-in (4xx, start not called)', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/settings',
|
||||
payload: { tunnelEnabled: true },
|
||||
});
|
||||
const put = (payload: Record<string, boolean> = { tunnelEnabled: true }) =>
|
||||
harness.app.inject({ method: 'PUT', url: '/api/settings', payload });
|
||||
|
||||
expect(res.statusCode).toBeGreaterThanOrEqual(400);
|
||||
expect(res.statusCode).toBeLessThan(500);
|
||||
const body = JSON.parse(res.body);
|
||||
expect(body.success).toBe(false);
|
||||
// Message should tell the user how to fix it.
|
||||
expect(body.error).toMatch(/CODEMAN_PASSWORD|CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK/);
|
||||
// The tunnel must NOT have been started.
|
||||
expect(tunnel.start).not.toHaveBeenCalled();
|
||||
// And tunnelEnabled:true must NOT have been persisted.
|
||||
expect(mockedWriteFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ALLOWS tunnel-enable when CODEMAN_PASSWORD is set (start called, 200)', async () => {
|
||||
process.env.CODEMAN_PASSWORD = 'hunter2';
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/settings',
|
||||
payload: { tunnelEnabled: true },
|
||||
function expectRefused(res: Awaited<ReturnType<typeof put>>) {
|
||||
expect.soft(res.statusCode).toBe(403);
|
||||
expect.soft(res.json()).toEqual({
|
||||
success: false,
|
||||
errorCode: 'OPERATION_FAILED',
|
||||
error: expect.any(String),
|
||||
});
|
||||
expect.soft(tunnel.start.mock.calls).toEqual([]);
|
||||
expect.soft(mockedWriteFile.mock.calls).toEqual([]);
|
||||
}
|
||||
|
||||
function expectEnabled(res: Awaited<ReturnType<typeof put>>) {
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(tunnel.start).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
expect(tunnel.start.mock.calls).toEqual([[harness.ctx.port, harness.ctx.https]]);
|
||||
expect(tunnel.stop.mock.calls).toEqual([]);
|
||||
expect(settingsWrites()).toEqual([[SETTINGS_PATH, JSON.stringify({ tunnelEnabled: true }, null, 2)]]);
|
||||
}
|
||||
|
||||
it('ALLOWS tunnel-enable with the unauthenticated-network opt-in acknowledged (start called, 200)', async () => {
|
||||
it('refuses the incident: network acknowledgement does not authorize a public tunnel', async () => {
|
||||
process.env.CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK = '1';
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/settings',
|
||||
payload: { tunnelEnabled: true },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(tunnel.start).toHaveBeenCalledTimes(1);
|
||||
const res = await put();
|
||||
expectRefused(res);
|
||||
expect.soft(res.json().error).toContain('CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL');
|
||||
expect.soft(res.json().error).toContain('CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK');
|
||||
expect.soft(res.json().error).toMatch(/no longer/i);
|
||||
});
|
||||
|
||||
it('ALLOWS tunnel-enable with per-request acknowledgeUnauthTunnel:true (start called, 200, flag not persisted)', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/settings',
|
||||
payload: { tunnelEnabled: true, acknowledgeUnauthTunnel: true },
|
||||
});
|
||||
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(tunnel.start).toHaveBeenCalledTimes(1);
|
||||
// The action flag must NOT be persisted to settings.json.
|
||||
expect(mockedWriteFile).toHaveBeenCalled();
|
||||
const persisted = JSON.parse(mockedWriteFile.mock.calls[0][1] as string);
|
||||
expect(persisted.acknowledgeUnauthTunnel).toBeUndefined();
|
||||
expect(persisted.tunnelEnabled).toBe(true);
|
||||
it('refuses without credentials or acknowledgement and names the tunnel opt-in', async () => {
|
||||
const res = await put();
|
||||
expectRefused(res);
|
||||
expect(res.json().error).toContain('CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL');
|
||||
});
|
||||
|
||||
it('still REFUSES when acknowledgeUnauthTunnel is false (4xx, start not called)', async () => {
|
||||
const res = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/settings',
|
||||
payload: { tunnelEnabled: true, acknowledgeUnauthTunnel: false },
|
||||
});
|
||||
it.each(['1', 'true', 'yes', 'on', ' TRUE '])(
|
||||
'allows tunnel env value %j without an acknowledgement',
|
||||
async (value) => {
|
||||
process.env.CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL = value;
|
||||
expectEnabled(await put());
|
||||
}
|
||||
);
|
||||
|
||||
expect(res.statusCode).toBeGreaterThanOrEqual(400);
|
||||
expect(res.statusCode).toBeLessThan(500);
|
||||
expect(tunnel.start).not.toHaveBeenCalled();
|
||||
expect(mockedWriteFile).not.toHaveBeenCalled();
|
||||
it('allows the route context flag without an env opt-in or acknowledgement', async () => {
|
||||
(harness.ctx as unknown as { allowUnauthenticatedTunnel: boolean }).allowUnauthenticatedTunnel = true;
|
||||
expectEnabled(await put());
|
||||
});
|
||||
|
||||
it('does not guard tunnel-disable (tunnelEnabled:false always allowed)', async () => {
|
||||
tunnel = makeTunnelManager(true);
|
||||
(harness.ctx as unknown as { tunnelManager: unknown }).tunnelManager = tunnel;
|
||||
it('allows acknowledgement alone and persists only tunnelEnabled', async () => {
|
||||
expectEnabled(await put({ tunnelEnabled: true, acknowledgeUnauthTunnel: true }));
|
||||
});
|
||||
|
||||
const res = await harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/settings',
|
||||
payload: { tunnelEnabled: false },
|
||||
});
|
||||
it('refuses a false acknowledgement', async () => {
|
||||
expectRefused(await put({ tunnelEnabled: true, acknowledgeUnauthTunnel: false }));
|
||||
});
|
||||
|
||||
it('allows a configured password without acknowledgement', async () => {
|
||||
process.env.CODEMAN_PASSWORD = 'test-password';
|
||||
expectEnabled(await put());
|
||||
});
|
||||
|
||||
it('allows a multi-user admin without acknowledgement', async () => {
|
||||
process.env.CODEMAN_MULTIUSER = '1';
|
||||
expectEnabled(await put());
|
||||
});
|
||||
|
||||
it.each(['0', 'false', '', 'enabled'])('refuses non-true tunnel env value %j', async (value) => {
|
||||
process.env.CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL = value;
|
||||
expectRefused(await put());
|
||||
});
|
||||
|
||||
it('does not guard disabling a running tunnel', async () => {
|
||||
tunnel.isRunning.mockReturnValue(true);
|
||||
const res = await put({ tunnelEnabled: false });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(tunnel.stop).toHaveBeenCalledTimes(1);
|
||||
expect(tunnel.start.mock.calls).toEqual([]);
|
||||
expect(tunnel.stop.mock.calls).toEqual([[]]);
|
||||
expect(settingsWrites()).toEqual([[SETTINGS_PATH, JSON.stringify({ tunnelEnabled: false }, null, 2)]]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['password', 'CODEMAN_PASSWORD', 'test-password', false, true],
|
||||
['multi-user', 'CODEMAN_MULTIUSER', '1', false, true],
|
||||
['neither', undefined, undefined, false, false],
|
||||
['empty password', 'CODEMAN_PASSWORD', '', false, false],
|
||||
['network opt-in only', 'CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK', '1', false, false],
|
||||
['tunnel opt-in only', 'CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL', '1', false, false],
|
||||
['tunnel flag only', undefined, undefined, true, false],
|
||||
] as const)('status reports loginConfigured for %s', async (_label, key, value, flag, loginConfigured) => {
|
||||
if (key !== undefined) process.env[key] = value;
|
||||
(harness.ctx as unknown as { allowUnauthenticatedTunnel: boolean }).allowUnauthenticatedTunnel = flag;
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/tunnel/status' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ ...STATUS, loginConfigured });
|
||||
expect(tunnel.getStatus.mock.calls).toEqual([[]]);
|
||||
expect(mockedWriteFile.mock.calls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tunnel enable authorization across a concurrent stop', () => {
|
||||
let harness: RouteTestHarness;
|
||||
let tunnel: ReturnType<typeof makeTunnelManager>;
|
||||
let running: boolean;
|
||||
let stopDuringWrite: boolean;
|
||||
let afterWrite: (() => void) | undefined;
|
||||
let storedSettings: Record<string, boolean>;
|
||||
const envKeys = [
|
||||
'CODEMAN_PASSWORD',
|
||||
'CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK',
|
||||
'CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL',
|
||||
'CODEMAN_MULTIUSER',
|
||||
] as const;
|
||||
let savedEnv: (string | undefined)[];
|
||||
|
||||
beforeEach(async () => {
|
||||
savedEnv = envKeys.map((key) => process.env[key]);
|
||||
for (const key of envKeys) delete process.env[key];
|
||||
harness = await createRouteTestHarness(registerSystemRoutes, {
|
||||
authUser: { username: 'root', role: 'admin' },
|
||||
});
|
||||
vi.clearAllMocks();
|
||||
running = true;
|
||||
stopDuringWrite = true;
|
||||
afterWrite = undefined;
|
||||
storedSettings = { tunnelEnabled: false, subagentTrackingEnabled: false };
|
||||
tunnel = makeTunnelManager();
|
||||
tunnel.isRunning.mockImplementation(() => running);
|
||||
(harness.ctx as unknown as { tunnelManager: unknown }).tunnelManager = tunnel;
|
||||
(harness.ctx as unknown as { allowUnauthenticatedTunnel: boolean }).allowUnauthenticatedTunnel = false;
|
||||
vi.mocked(fs.readFile).mockImplementation(async (path) => {
|
||||
expect(path).toBe(SETTINGS_PATH);
|
||||
return JSON.stringify(storedSettings);
|
||||
});
|
||||
const pending = new Map<string, string>();
|
||||
const store = (contents: string) => {
|
||||
storedSettings = JSON.parse(contents);
|
||||
// The stop becomes visible during the awaited write, regardless of isRunning() call count.
|
||||
if (stopDuringWrite) running = false;
|
||||
afterWrite?.();
|
||||
};
|
||||
mockedWriteFile.mockImplementation(async (path, contents) => {
|
||||
// A direct write to settings.json lands at once, so the stored file is what the route really left;
|
||||
// settingsWrites() then fails it for not going through a temp file and a rename.
|
||||
if (path === SETTINGS_PATH) store(contents as string);
|
||||
else pending.set(String(path), contents as string);
|
||||
});
|
||||
mockedRename.mockImplementation(async (from, to) => {
|
||||
expect(to).toBe(SETTINGS_PATH);
|
||||
store(pending.get(String(from)) as string);
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
try {
|
||||
await harness?.app.close();
|
||||
} finally {
|
||||
envKeys.forEach((key, i) => {
|
||||
if (savedEnv[i] === undefined) delete process.env[key];
|
||||
else process.env[key] = savedEnv[i];
|
||||
});
|
||||
vi.mocked(fs.readFile).mockResolvedValue('{}');
|
||||
mockedWriteFile.mockResolvedValue(undefined);
|
||||
mockedRename.mockResolvedValue(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
const put = (acknowledgement: Record<string, boolean> = {}) =>
|
||||
harness.app.inject({
|
||||
method: 'PUT',
|
||||
url: '/api/settings',
|
||||
payload: { tunnelEnabled: true, autoNameSessions: false, ...acknowledgement },
|
||||
});
|
||||
|
||||
function expectWritten(tunnelEnabled: boolean) {
|
||||
const expected = { tunnelEnabled, subagentTrackingEnabled: false, autoNameSessions: false };
|
||||
// Check every write so a transient unauthorized enable followed by a rollback also fails.
|
||||
expect
|
||||
.soft(settingsWrites().map(([path, contents]) => ({ path, settings: JSON.parse(contents) })))
|
||||
.toEqual([{ path: SETTINGS_PATH, settings: expected }]);
|
||||
expect.soft(storedSettings).toEqual(expected);
|
||||
}
|
||||
|
||||
function expectLateRefusal(res: Awaited<ReturnType<typeof put>>) {
|
||||
expect.soft(res.statusCode).toBe(403);
|
||||
expect.soft(res.json()).toEqual({
|
||||
success: false,
|
||||
errorCode: 'OPERATION_FAILED',
|
||||
error: expect.any(String),
|
||||
});
|
||||
expect.soft(res.json().error).toContain('CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL');
|
||||
expect.soft(res.json().error).toMatch(/not (re)?start/i);
|
||||
expect.soft(tunnel.start.mock.calls).toEqual([]);
|
||||
expect.soft(tunnel.stop.mock.calls).toEqual([]);
|
||||
expectWritten(false);
|
||||
}
|
||||
|
||||
function expectAuthorizedRestart(res: Awaited<ReturnType<typeof put>>) {
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({});
|
||||
expect(tunnel.start.mock.calls).toEqual([[harness.ctx.port, harness.ctx.https]]);
|
||||
expect(tunnel.stop.mock.calls).toEqual([]);
|
||||
expectWritten(true);
|
||||
}
|
||||
|
||||
it('refuses an unauthorized restart after a concurrent stop while saving other settings', async () => {
|
||||
expectLateRefusal(await put());
|
||||
});
|
||||
|
||||
it.each(['password', 'tunnel env', 'route flag', 'per-request acknowledgement', 'multi-user admin'] as const)(
|
||||
'allows a restart with %s authorization',
|
||||
async (authorization) => {
|
||||
if (authorization === 'password') process.env.CODEMAN_PASSWORD = 'test-password';
|
||||
if (authorization === 'tunnel env') process.env.CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL = '1';
|
||||
if (authorization === 'route flag') {
|
||||
(harness.ctx as unknown as { allowUnauthenticatedTunnel: boolean }).allowUnauthenticatedTunnel = true;
|
||||
}
|
||||
if (authorization === 'multi-user admin') process.env.CODEMAN_MULTIUSER = '1';
|
||||
expectAuthorizedRestart(
|
||||
await put(authorization === 'per-request acknowledgement' ? { acknowledgeUnauthTunnel: true } : {})
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it.each([false, true])(
|
||||
'preserves stored tunnelEnabled=%s when an unauthorized tunnel stays running',
|
||||
async (tunnelEnabled) => {
|
||||
stopDuringWrite = false;
|
||||
storedSettings.tunnelEnabled = tunnelEnabled;
|
||||
const res = await put();
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({});
|
||||
expect(tunnel.start.mock.calls).toEqual([]);
|
||||
expect(tunnel.stop.mock.calls).toEqual([]);
|
||||
expectWritten(tunnelEnabled);
|
||||
}
|
||||
);
|
||||
|
||||
it('does not acquire restart authorization from an env opt-in added during the write', async () => {
|
||||
afterWrite = () => {
|
||||
process.env.CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL = '1';
|
||||
};
|
||||
expectLateRefusal(await put());
|
||||
});
|
||||
|
||||
it('retains the request authorization when the env opt-in is removed during the write', async () => {
|
||||
process.env.CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL = '1';
|
||||
afterWrite = () => {
|
||||
delete process.env.CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL;
|
||||
};
|
||||
expectAuthorizedRestart(await put());
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,10 @@
|
||||
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);
|
||||
|
||||
// ── Mocks ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -18,6 +22,11 @@ vi.mock('node:fs/promises', () => ({
|
||||
default: {
|
||||
readFile: vi.fn(async () => '{}'),
|
||||
writeFile: vi.fn(async () => undefined),
|
||||
// settings.json is written to a temp file and renamed over the real one (settings-writer.ts).
|
||||
realpath: vi.fn(async (p: string) => p),
|
||||
mkdir: vi.fn(async () => undefined),
|
||||
rename: vi.fn(async () => undefined),
|
||||
rm: vi.fn(async () => undefined),
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -326,6 +335,20 @@ describe('system-routes', () => {
|
||||
expect(body).toHaveProperty('cpu');
|
||||
expect(body).toHaveProperty('memory');
|
||||
});
|
||||
|
||||
it('adds no GPU or clock readings unless they are asked for', async () => {
|
||||
const body = JSON.parse((await harness.app.inject({ method: 'GET', url: '/api/system/stats' })).body);
|
||||
expect(body).not.toHaveProperty('gpu');
|
||||
expect(body).not.toHaveProperty('cpuMhz');
|
||||
});
|
||||
|
||||
it('passes only the requested readings on to the sensor reader', async () => {
|
||||
hostSensors.readHostSensors.mockClear();
|
||||
hostSensors.readHostSensors.mockResolvedValueOnce({ cpuMhz: 3200 });
|
||||
const res = await harness.app.inject({ method: 'GET', url: '/api/system/stats?cpumhz=1&gpu=0' });
|
||||
expect(hostSensors.readHostSensors).toHaveBeenCalledWith({ gpu: false, cpuMhz: true });
|
||||
expect(JSON.parse(res.body).cpuMhz).toBe(3200);
|
||||
});
|
||||
});
|
||||
|
||||
// ========== POST /api/cleanup-state ==========
|
||||
@@ -343,6 +366,73 @@ 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();
|
||||
}
|
||||
});
|
||||
|
||||
it('deletes the edit history of every session it cleaned (diffs can hold secrets)', async () => {
|
||||
harness.ctx.tabLayouts.runStaleSessionCleanup = vi.fn(async () => ({
|
||||
count: 2,
|
||||
cleaned: [
|
||||
{ id: 'stale-1', name: 'a' },
|
||||
{ id: 'stale-2', name: 'b' },
|
||||
],
|
||||
})) as never;
|
||||
const res = await harness.app.inject({ method: 'POST', url: '/api/cleanup-state' });
|
||||
expect(JSON.parse(res.body).cleanedSessions).toBe(2);
|
||||
expect(vi.mocked(harness.ctx.forgetEditHistory).mock.calls).toEqual([['stale-1'], ['stale-2']]);
|
||||
});
|
||||
});
|
||||
|
||||
// ========== GET /api/subagents ==========
|
||||
|
||||
Reference in new issue
Block a user