Files
waggle-os/packages/server/tests/local/route-proposals.test.ts
shumeiko.it 727c756651 refactor: route Best fit proposals to personas only
The executor router could propose Claude Code, Codex or Hermes and
dispatch the task as a Waggle Room run through POST /api/tools/run, which
is gone with the collaboration runtime. Confirming such a proposal could
only fail.

- ExecutorRegistry offers the five v1 personas; it no longer detects
  external tools.
- Route proposals dispatch persona chat turns only. The memory brief and
  its egress disclosure existed only for external executors, so
  executor-brief.ts, the egress fields and removeFrameIds go too.
- RouteProposalCard drops the memory disclosure, "Run without memory" and
  the link to an external run in the Room.
2026-11-01 11:06:43 +01:00

274 lines
8.8 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from 'vitest';
import Fastify, { type FastifyInstance } from 'fastify';
import { buildTaskFit, type ExecutorCandidate } from '@waggle/agent';
import { routeProposalRoutes } from '../../src/local/routes/route-proposals.js';
const NOW_MS = Date.UTC(2026, 6, 15, 10, 0, 0);
const WORKSPACE_ID = 'workspace-alpha';
const PROMPT = 'Implement the router tests';
const servers: FastifyInstance[] = [];
afterEach(async () => {
vi.useRealTimers();
await Promise.all(servers.splice(0).map((server) => server.close()));
});
function personaCandidate(overrides: Partial<ExecutorCandidate> = {}): ExecutorCandidate {
const id = overrides.id ?? 'persona:coder';
return {
id,
kind: 'persona',
displayName: 'Coder',
taskFit: buildTaskFit(id),
authClass: 'api-key',
installed: true,
healthy: true,
rateLimit: { state: 'available' },
supportsHeadless: false,
egressDestination: null,
...overrides,
};
}
interface HarnessOptions {
snapshots: ExecutorCandidate[][];
personaDispatcher?: (...args: unknown[]) => Promise<{
content: string;
approvalRequired: boolean;
error?: string;
}>;
}
async function createHarness(options: HarnessOptions) {
const server = Fastify({ logger: false });
servers.push(server);
let snapshotIndex = 0;
const snapshot = vi.fn(async () => {
const candidates = options.snapshots[Math.min(snapshotIndex, options.snapshots.length - 1)] ?? [];
snapshotIndex += 1;
return candidates;
});
const personaDispatcher = options.personaDispatcher ?? vi.fn(async () => ({
content: 'Dispatched',
approvalRequired: false,
}));
server.decorate('localConfig', {
dataDir: '',
port: 4567,
host: '127.0.0.1',
litellmUrl: '',
} as never);
server.decorate('agentState', { wsSessionToken: 'ws-session-token' } as never);
server.decorate('executorRegistry', {
snapshot,
noteRateLimit: vi.fn(),
noteHealthy: vi.fn(),
} as never);
server.decorate('routeProposalPersonaDispatcher', personaDispatcher as never);
await server.register(routeProposalRoutes);
return { server, snapshot, personaDispatcher };
}
async function propose(
server: FastifyInstance,
overrides: Record<string, unknown> = {},
) {
return server.inject({
method: 'POST',
url: '/api/route-proposals',
payload: {
workspaceId: WORKSPACE_ID,
prompt: PROMPT,
category: 'coding',
...overrides,
},
});
}
describe('route proposal routes', () => {
it('dispatches a persona with the bare persona id, router origin, and websocket token', async () => {
const personaDispatcher = vi.fn(async () => ({ content: 'Done', approvalRequired: false }));
const { server } = await createHarness({
snapshots: [[personaCandidate()], [personaCandidate()]],
personaDispatcher,
});
const proposed = await propose(server);
const { routeDecisionId } = proposed.json() as { routeDecisionId: string };
const confirmed = await server.inject({
method: 'POST',
url: `/api/route-proposals/${routeDecisionId}/confirm`,
payload: {},
});
expect(confirmed.statusCode).toBe(200);
expect(confirmed.json()).toEqual({ status: 'dispatched', resultText: 'Done' });
expect(personaDispatcher).toHaveBeenCalledWith({
port: 4567,
sessionToken: 'ws-session-token',
message: PROMPT,
workspace: WORKSPACE_ID,
session: WORKSPACE_ID,
persona: 'coder',
proposeHeld: true,
origin: 'router',
});
});
it('fails revalidation when the selected persona is rate limited by confirm time', async () => {
const { server, snapshot, personaDispatcher } = await createHarness({
snapshots: [
[personaCandidate()],
[personaCandidate({ rateLimit: { state: 'observed_exhausted' } })],
],
});
const proposed = await propose(server);
const { routeDecisionId } = proposed.json() as { routeDecisionId: string };
const confirmed = await server.inject({
method: 'POST',
url: `/api/route-proposals/${routeDecisionId}/confirm`,
payload: {},
});
expect(confirmed.statusCode).toBe(409);
expect(confirmed.json()).toMatchObject({
error: 'revalidation_failed',
reason: 'rate limit exhausted',
});
expect(snapshot).toHaveBeenCalledTimes(2);
expect(personaDispatcher).not.toHaveBeenCalled();
});
it('expires proposals after ten minutes', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(NOW_MS);
const { server, snapshot } = await createHarness({ snapshots: [[personaCandidate()]] });
const proposed = await propose(server);
const { routeDecisionId } = proposed.json() as { routeDecisionId: string };
vi.setSystemTime(NOW_MS + 10 * 60_000);
const confirmed = await server.inject({
method: 'POST',
url: `/api/route-proposals/${routeDecisionId}/confirm`,
payload: {},
});
expect(confirmed.statusCode).toBe(404);
expect(confirmed.json()).toEqual({ error: 'route_proposal_not_found' });
expect(snapshot).toHaveBeenCalledTimes(1);
});
it('allows a proposal to be confirmed only once', async () => {
const { server, personaDispatcher, snapshot } = await createHarness({
snapshots: [[personaCandidate()], [personaCandidate()]],
});
const proposed = await propose(server);
const { routeDecisionId } = proposed.json() as { routeDecisionId: string };
const first = await server.inject({
method: 'POST',
url: `/api/route-proposals/${routeDecisionId}/confirm`,
payload: {},
});
const second = await server.inject({
method: 'POST',
url: `/api/route-proposals/${routeDecisionId}/confirm`,
payload: {},
});
expect(first.statusCode).toBe(200);
expect(second.statusCode).toBe(409);
expect(second.json()).toEqual({
error: 'route_proposal_already_claimed',
status: 'dispatched',
});
expect(snapshot).toHaveBeenCalledTimes(2);
expect(personaDispatcher).toHaveBeenCalledTimes(1);
});
it('proposes only personas and states that they use the configured API key', async () => {
const { server } = await createHarness({
snapshots: [[personaCandidate()]],
});
const proposed = await propose(server);
expect(proposed.statusCode).toBe(200);
expect(proposed.json()).toMatchObject({
selected: { id: 'persona:coder' },
costLine: 'runs on your configured API key',
});
expect(proposed.json()).not.toHaveProperty('egress');
});
it('rejects memory removals at confirm: a persona run sends no memory brief', async () => {
const { server, personaDispatcher } = await createHarness({
snapshots: [[personaCandidate()], [personaCandidate()]],
});
const proposed = await propose(server);
const { routeDecisionId } = proposed.json() as { routeDecisionId: string };
const confirmed = await server.inject({
method: 'POST',
url: `/api/route-proposals/${routeDecisionId}/confirm`,
payload: { removeFrameIds: ['frame-1'] },
});
expect(confirmed.statusCode).toBe(400);
expect(personaDispatcher).not.toHaveBeenCalled();
});
it('rejects a proposed route and prevents it from being claimed later', async () => {
const { server, personaDispatcher } = await createHarness({
snapshots: [[personaCandidate()]],
});
const proposed = await propose(server);
const { routeDecisionId } = proposed.json() as { routeDecisionId: string };
const rejected = await server.inject({
method: 'POST',
url: `/api/route-proposals/${routeDecisionId}/reject`,
});
const confirmed = await server.inject({
method: 'POST',
url: `/api/route-proposals/${routeDecisionId}/confirm`,
payload: {},
});
expect(rejected.statusCode).toBe(200);
expect(rejected.json()).toEqual({ status: 'rejected' });
expect(confirmed.statusCode).toBe(409);
expect(confirmed.json()).toEqual({
error: 'route_proposal_already_claimed',
status: 'rejected',
});
expect(personaDispatcher).not.toHaveBeenCalled();
});
it('strictly validates proposal and confirmation input', async () => {
const { server, snapshot } = await createHarness({
snapshots: [[personaCandidate()]],
});
const extraProposalField = await propose(server, { unexpected: true });
const emptyPrompt = await propose(server, { prompt: '' });
const validProposal = await propose(server);
const { routeDecisionId } = validProposal.json() as { routeDecisionId: string };
const extraConfirmField = await server.inject({
method: 'POST',
url: `/api/route-proposals/${routeDecisionId}/confirm`,
payload: { unexpected: true },
});
expect(extraProposalField.statusCode).toBe(400);
expect(emptyPrompt.statusCode).toBe(400);
expect(extraConfirmField.statusCode).toBe(400);
expect(snapshot).toHaveBeenCalledTimes(1);
});
});