/** * UF-045 — generating a persona from a description goes through the built-in * proxy with the session token, and reads the proxy's OpenAI-format reply. * Runs against a listening server with localhost trust off; only the upstream * Anthropic call is faked. */ import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import type { FastifyInstance } from 'fastify'; import { buildLocalServer } from '../../src/local/index.js'; import { injectWithAuth } from '../test-utils.js'; describe('POST /api/personas/generate (UF-045)', () => { let server: FastifyInstance; let tmpDir: string; const realFetch = globalThis.fetch; const priorTrustLocalhost = process.env.WAGGLE_TRUST_LOCALHOST; beforeAll(async () => { process.env.WAGGLE_TRUST_LOCALHOST = '0'; tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-personas-gen-')); server = await buildLocalServer({ dataDir: tmpDir }); await server.listen({ port: 0, host: '127.0.0.1' }); server.vault.set('anthropic', 'sk-ant-test-key'); // startService sets the provider status; buildLocalServer alone does not. server.agentState.llmProvider = { provider: 'anthropic-proxy', health: 'degraded', detail: 'Built-in provider proxy (verification pending)', checkedAt: new Date().toISOString(), }; }); afterEach(() => vi.unstubAllGlobals()); afterAll(async () => { await server.close(); fs.rmSync(tmpDir, { recursive: true, force: true }); if (priorTrustLocalhost === undefined) delete process.env.WAGGLE_TRUST_LOCALHOST; else process.env.WAGGLE_TRUST_LOCALHOST = priorTrustLocalhost; }); it('returns the persona the model wrote', async () => { const persona = { name: 'Release Scout', description: 'Tracks what changed between releases.', icon: '🔭', systemPrompt: 'You compare release notes and summarise breaking changes.', tools: ['web_search', 'document_processing'], }; const upstream = vi.fn(async () => new Response(JSON.stringify({ id: 'msg_persona', type: 'message', role: 'assistant', model: 'claude-sonnet-4-6', content: [{ type: 'text', text: JSON.stringify(persona) }], stop_reason: 'end_turn', usage: { input_tokens: 10, output_tokens: 40 }, }), { status: 200, headers: { 'content-type': 'application/json' } })); vi.stubGlobal('fetch', (input: RequestInfo | URL, init?: RequestInit) => { const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; return url.startsWith('https://api.anthropic.com/') ? upstream() : realFetch(input, init); }); const res = await injectWithAuth(server, { method: 'POST', url: '/api/personas/generate', payload: { prompt: 'An agent that watches our release notes' }, }); expect(res.statusCode).toBe(200); expect(JSON.parse(res.body)).toEqual(persona); expect(upstream).toHaveBeenCalledTimes(1); }); });