fix(server): send the session token on the sidecar's calls to its own proxy (UF-044)
Since the server stopped trusting loopback callers, the built-in model proxy needs the session token like every other route, but the sidecar's own calls to it sent none. The Models key check read the proxy's 401 as a rejected key, so a working Anthropic key showed "Key found but not responding". Scheduled AI tasks and loops, the dream diary narrative and the profile calls failed the same way; the profile calls also built the port from address().toString(), and the scheduled tasks used the configured port, which the desktop app's port fallback can leave pointing at another Waggle server. self-request.ts now builds the address from the bound port and adds the session token; all these calls and command.ts use it, and the token is never sent to Ollama. An end-to-end test runs the key check through the real middleware and proxy with localhost trust off; it fails without the fix. UF-045 records the persona generator, which posts to a route that does not exist; it is left open.
This commit is contained in:
@@ -72,6 +72,8 @@ Baseline: commit `b20b138` of `git.os-dev.tech/oleg.m/waggle-os`.
|
||||
| UF-041 | The CLI server does not exit on Ctrl+C or SIGTERM | Fixed | Sidecar, CLI |
|
||||
| UF-042 | Sidebar hints repeat the visible labels and are partly hidden behind the main area | Fixed | Web UI |
|
||||
| UF-043 | The chat composer draws two focus outlines | Fixed | Web UI |
|
||||
| UF-044 | A working API key shows as not responding, and other internal model calls fail | Fixed | Sidecar, models, auth |
|
||||
| UF-045 | Generating a persona from a description calls a route that does not exist | Open | Sidecar, agents |
|
||||
|
||||
## Entries
|
||||
|
||||
@@ -435,3 +437,21 @@ Entries UF-010 to UF-019 come from the UI audit `anti-slop/audit-001-2026-10-14.
|
||||
- Cause: the textarea has its own `focus-visible:ring-2` while its box already shows focus with `focus-within:border-[var(--focus-ring)]` and a glow.
|
||||
- What we did: removed the ring from the textarea. The box's border stays the single focus indicator; it measures 8.14:1 against the composer in the dark theme and 4.92:1 in the light theme. The composer test now checks for one indicator.
|
||||
- Recommendation: apply the same change in the main project.
|
||||
|
||||
### UF-044. A working API key shows as not responding, and other internal model calls fail
|
||||
- Status: Fixed
|
||||
- Found: 2026-10-26
|
||||
- Where: at commit `b20b138`, `packages/server/src/local/routes/settings.ts:309-360` (`POST /api/settings/probe-model`, the request at :344 sends no session token); the same unauthenticated requests to the built-in proxy in `packages/server/src/local/index.ts:1901`, 2117, 2297 and 2428 (scheduled AI tasks and loops), `routes/dreams.ts:31` (dream diary narrative) and `routes/profile.ts:289`, 346 and 423 (style analysis and related profile calls); the bearer check in `security-middleware.ts`, which trusts loopback callers only with `WAGGLE_TRUST_LOCALHOST=1`
|
||||
- Symptom: Settings → Models shows "Key found but not responding" for an Anthropic key that works, so the key looks as if it keeps dropping off. On a real machine the check answered `rejected`, while the same request sent with the session token got a normal model reply. Scheduled AI tasks and loops, the dream diary narrative and the profile calls fail with HTTP 401 the same way. The profile calls also built the proxy address from `address().toString()`, which is `[object Object]`, and the scheduled tasks used the configured port, which in the desktop app (port fallback) can belong to another Waggle server.
|
||||
- Cause: since the server stopped trusting loopback callers (D1), the built-in proxy needs the session token like every other route, but these internal calls do not send it. The key check reads the proxy's own 401 as a rejected key. `vitest.setup.ts` turns localhost trust on for every test, so the suites never saw it; `routes/command.ts` had the same bug fixed locally.
|
||||
- What we did: `packages/server/src/local/self-request.ts` builds the address from the port the server is bound to and adds the session token. The key check, the scheduled tasks, the dream diary, the profile calls and `command.ts` use it; the token is never sent to Ollama. A route test checks the header, and an end-to-end test with localhost trust off checks that a working key verifies through the real middleware and proxy; it fails without the fix.
|
||||
- Recommendation: apply the same change in the main project, and run the auth-sensitive suites with localhost trust off.
|
||||
|
||||
### UF-045. Generating a persona from a description calls a route that does not exist
|
||||
- Status: Open
|
||||
- Found: 2026-10-26
|
||||
- Where: at commit `b20b138`, `packages/server/src/local/routes/personas.ts:160` (`POST /api/personas/generate`, used by the agent templates view)
|
||||
- Symptom: generating an agent persona from a text description cannot get an answer from the model.
|
||||
- Cause: the route posts to `/api/anthropic/v1/messages`, which no route serves. The request also has no session token, and its port comes from `address().toString()`, which is `[object Object]`.
|
||||
- What we did: nothing yet. The fix means moving the call to the built-in proxy (`/v1/chat/completions` through `self-request.ts`) and reading its OpenAI-format reply.
|
||||
- Recommendation: move the call to the built-in proxy in the main project as well.
|
||||
|
||||
@@ -13,6 +13,7 @@ import websocket from '@fastify/websocket';
|
||||
import { WaggleDB, importLegacyMindData, workspaceDataScope, type LegacyMindSource, WorkspaceManager, WaggleConfig, createEmbeddingProvider, type EmbeddingProviderConfig, type EmbeddingProviderInstance, CronStore, AwarenessLayer, VaultStore, SkillHashStore, TelemetryStore, TELEMETRY_EVENTS, ExecutionTraceStore } from '@waggle/core';
|
||||
import { corsOriginAllowed } from './cors-config.js';
|
||||
import { InstallAuditStore } from './install-audit.js';
|
||||
import { selfBaseUrl, selfRequestHeaders } from './self-request.js';
|
||||
import { getStorageProvider } from './storage/index.js';
|
||||
import { isLoopbackBind, resolveBindHost } from './net-config.js';
|
||||
import { isLocalRequest } from './origin-guard.js';
|
||||
@@ -1550,10 +1551,10 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
}
|
||||
|
||||
// Use the built-in Anthropic proxy to process the prompt
|
||||
const proxyUrl = `http://127.0.0.1:${fullConfig.port ?? 3333}/v1/chat/completions`;
|
||||
const proxyUrl = `${selfBaseUrl(server)}/v1/chat/completions`;
|
||||
const response = await fetch(proxyUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: selfRequestHeaders(server),
|
||||
body: JSON.stringify({
|
||||
model: server.agentState.currentModel ?? 'claude-sonnet-4-6',
|
||||
max_tokens: 2048,
|
||||
@@ -1662,11 +1663,11 @@ export async function buildLocalServer(config: Partial<LocalConfig> = {}) {
|
||||
}
|
||||
if (wsId && wsId !== '*') activateWorkspaceMind(wsId);
|
||||
const loopModel = server.agentState.currentModel ?? 'claude-sonnet-4-6';
|
||||
const loopProxyUrl = `http://127.0.0.1:${fullConfig.port ?? 3333}/v1/chat/completions`;
|
||||
const loopProxyUrl = `${selfBaseUrl(server)}/v1/chat/completions`;
|
||||
const loopChat = async (prompt: string, maxTokens = 2048): Promise<string> => {
|
||||
const resp = await fetch(loopProxyUrl, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: selfRequestHeaders(server),
|
||||
body: JSON.stringify({
|
||||
model: loopModel,
|
||||
max_tokens: maxTokens,
|
||||
|
||||
@@ -28,6 +28,7 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { selfBaseUrl, selfRequestHeaders } from '../self-request.js';
|
||||
import type { CommandResult, Command } from '@waggle/shared';
|
||||
import type { Orchestrator, LoadedSkill } from '@waggle/agent';
|
||||
import { loadSkills } from '@waggle/agent';
|
||||
@@ -321,25 +322,16 @@ export const commandRoutes: FastifyPluginAsync = async (server) => {
|
||||
(m) => server.log.warn(m),
|
||||
);
|
||||
|
||||
// Fast-model call via the in-process OpenAI-compatible proxy. The proxy is
|
||||
// served on this server's own port and behind the same bearer auth as every
|
||||
// other route, so we read the bound port from `address().port` (NOT
|
||||
// `.toString()`, which is `[object Object]`) and pass the session token.
|
||||
// Fast-model call via the in-process OpenAI-compatible proxy, which sits
|
||||
// behind the same bearer auth as every other route (see self-request.ts).
|
||||
// No key / non-200 / throw → null → graceful Tier-0 fallback.
|
||||
const llm = async (systemPrompt: string, userText: string): Promise<string | null> => {
|
||||
const apiKey = server.vault?.get('anthropic')?.value;
|
||||
if (!apiKey) return null;
|
||||
const addr = server.server.address();
|
||||
const envPort = Number(process.env.WAGGLE_PORT);
|
||||
const port = (addr && typeof addr === 'object' ? addr.port : undefined) ?? (Number.isFinite(envPort) ? envPort : 3333);
|
||||
const token = server.agentState.wsSessionToken;
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
|
||||
const res = await fetch(`${selfBaseUrl(server)}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
headers: selfRequestHeaders(server),
|
||||
body: JSON.stringify({
|
||||
model: 'claude-haiku-4-5',
|
||||
max_tokens: 600,
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
* skip the LLM entirely.
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import type { FastifyInstance, FastifyPluginAsync } from 'fastify';
|
||||
import { selfBaseUrl, selfRequestHeaders } from '../self-request.js';
|
||||
import { createLogger } from '../logger.js';
|
||||
import { isLocalRequest } from '../origin-guard.js';
|
||||
import { DreamJournal, QUIET_NIGHT_SUMMARY, type DreamDay } from '../dream-journal.js';
|
||||
@@ -28,7 +29,7 @@ declare module 'fastify' {
|
||||
export type NarrativePolish = (day: DreamDay) => Promise<string>;
|
||||
|
||||
/** Build the default polish fn — one proxy call, fast tier, hard length cap. */
|
||||
export function makeProxyPolish(port: number): NarrativePolish {
|
||||
export function makeProxyPolish(server: FastifyInstance): NarrativePolish {
|
||||
return async (day: DreamDay): Promise<string> => {
|
||||
const prompt =
|
||||
'You are Waggle, a personal AI with persistent memory. While the user slept, ' +
|
||||
@@ -36,9 +37,9 @@ export function makeProxyPolish(port: number): NarrativePolish {
|
||||
`${day.summary}\nRaw counters: ${JSON.stringify(day.events.map(e => ({ action: e.action, ...e.stats })))}\n\n` +
|
||||
'Write 2-3 warm first-person sentences telling the user what you did overnight. ' +
|
||||
'Mention only work reflected in the counters. No greetings, no markdown, no emoji.';
|
||||
const res = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, {
|
||||
const res = await fetch(`${selfBaseUrl(server)}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: selfRequestHeaders(server),
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
body: JSON.stringify({
|
||||
model: 'claude-haiku-4-5',
|
||||
@@ -61,7 +62,7 @@ export interface DreamRoutesOptions {
|
||||
|
||||
export const dreamRoutes: FastifyPluginAsync<DreamRoutesOptions> = async (server, opts) => {
|
||||
const polish = opts.polish
|
||||
?? makeProxyPolish(server.localConfig?.port ?? 3333);
|
||||
?? makeProxyPolish(server);
|
||||
// Single-flight guard per date — a 5s-polling Home card must not stack
|
||||
// duplicate LLM calls while the first one is in flight.
|
||||
const polishInFlight = new Set<string>();
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
*/
|
||||
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
import { selfBaseUrl, selfRequestHeaders } from '../self-request.js';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { PERSONAL_SCOPE } from '@waggle/memory-contract';
|
||||
@@ -289,10 +290,10 @@ export const profileRoutes: FastifyPluginAsync = async (fastify) => {
|
||||
return reply.code(503).send({ error: 'No Anthropic key — cannot analyze style' });
|
||||
}
|
||||
|
||||
const proxyUrl = `http://127.0.0.1:${fastify.server.address()?.toString().split(':').pop() ?? '3333'}`;
|
||||
const proxyUrl = selfBaseUrl(fastify);
|
||||
const res = await fetch(`${proxyUrl}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: selfRequestHeaders(fastify),
|
||||
body: JSON.stringify({
|
||||
model: 'claude-haiku-4-5',
|
||||
max_tokens: 500,
|
||||
@@ -346,10 +347,10 @@ Sample text:
|
||||
return reply.code(503).send({ error: 'No Anthropic key — cannot analyze brand' });
|
||||
}
|
||||
|
||||
const proxyUrl = `http://127.0.0.1:${fastify.server.address()?.toString().split(':').pop() ?? '3333'}`;
|
||||
const proxyUrl = selfBaseUrl(fastify);
|
||||
const res = await fetch(`${proxyUrl}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: selfRequestHeaders(fastify),
|
||||
body: JSON.stringify({
|
||||
model: 'claude-haiku-4-5',
|
||||
max_tokens: 500,
|
||||
@@ -423,10 +424,10 @@ Brand description:
|
||||
return reply.code(503).send({ error: 'No Anthropic key for research' });
|
||||
}
|
||||
|
||||
const proxyUrl = `http://127.0.0.1:${fastify.server.address()?.toString().split(':').pop() ?? '3333'}`;
|
||||
const proxyUrl = selfBaseUrl(fastify);
|
||||
const res = await fetch(`${proxyUrl}/v1/chat/completions`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: selfRequestHeaders(fastify),
|
||||
body: JSON.stringify({
|
||||
model: 'claude-haiku-4-5',
|
||||
max_tokens: 500,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { WaggleConfig } from '@waggle/core';
|
||||
import type { AutonomyLevel } from '@waggle/agent';
|
||||
import { validateBody } from '../../validate-body.js';
|
||||
import { probeProviderKey, validateKeyFormat } from '../llm-key-probe.js';
|
||||
import { selfBaseUrl, selfRequestHeaders } from '../self-request.js';
|
||||
import { resolveExplicitRoutableModel, resolveUsableModel } from '../model-availability.js';
|
||||
import { applyProviderKeyToEnv } from '../provider-env.js';
|
||||
import { refreshManagedLiteLLM, type LiteLLMRefreshResult } from '../litellm-runtime-config.js';
|
||||
@@ -320,14 +321,12 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
|
||||
// Endpoint selection mirrors chat.ts: Ollama models go direct to Ollama's
|
||||
// OpenAI-compatible endpoint (strip the 'ollama/' prefix); everything else
|
||||
// through the built-in proxy on this same sidecar (port from the address
|
||||
// info, harvest.ts pattern).
|
||||
// through the built-in proxy on this same sidecar, with the session token
|
||||
// (UF-044). The token never goes to Ollama.
|
||||
const isOllama = model.startsWith('ollama/');
|
||||
const addr = server.server.address();
|
||||
const port = typeof addr === 'object' && addr ? addr.port : server.localConfig.port;
|
||||
const url = isOllama
|
||||
? (process.env.OLLAMA_HOST?.replace(/\/+$/, '') ?? 'http://localhost:11434') + '/v1/chat/completions'
|
||||
: `http://127.0.0.1:${port}/v1/chat/completions`;
|
||||
: `${selfBaseUrl(server)}/v1/chat/completions`;
|
||||
const sendModel = isOllama ? model.slice('ollama/'.length) : model;
|
||||
|
||||
const controller = new AbortController();
|
||||
@@ -335,7 +334,7 @@ export const settingsRoutes: FastifyPluginAsync = async (server) => {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: isOllama ? { 'Content-Type': 'application/json' } : selfRequestHeaders(server),
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({ model: sendModel, max_tokens: 1, messages: [{ role: 'user', content: 'hi' }] }),
|
||||
});
|
||||
|
||||
25
packages/server/src/local/self-request.ts
Normal file
25
packages/server/src/local/self-request.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Requests the sidecar sends to its own routes: the built-in model proxy at
|
||||
* /v1/chat/completions and /api/anthropic/*. The server does not trust loopback
|
||||
* callers (D1), so these carry the session token like any other client. They
|
||||
* target the port the server is bound to, which differs from the configured one
|
||||
* when the desktop shell falls back to a free port. Resolve both when the
|
||||
* request is made: the address is known only once the server listens.
|
||||
*/
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
|
||||
export function selfBaseUrl(server: FastifyInstance): string {
|
||||
const addr = server.server.address();
|
||||
const envPort = Number(process.env.WAGGLE_PORT);
|
||||
const port = (addr && typeof addr === 'object' ? addr.port : undefined)
|
||||
?? (Number.isInteger(envPort) && envPort > 0 ? envPort : 3333);
|
||||
return `http://127.0.0.1:${port}`;
|
||||
}
|
||||
|
||||
export function selfRequestHeaders(server: FastifyInstance): Record<string, string> {
|
||||
const token = server.agentState.wsSessionToken;
|
||||
return {
|
||||
'Content-Type': 'application/json',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
};
|
||||
}
|
||||
63
packages/server/tests/local/probe-model-proxy.test.ts
Normal file
63
packages/server/tests/local/probe-model-proxy.test.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* UF-044 end to end: the Models screen's key check goes through this server's
|
||||
* own auth middleware and built-in proxy. Only the upstream Anthropic call is
|
||||
* faked, so a check that reaches the proxy without the session token fails here.
|
||||
*/
|
||||
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('probe-model through the built-in proxy (UF-044)', () => {
|
||||
let server: FastifyInstance;
|
||||
let tmpDir: string;
|
||||
const realFetch = globalThis.fetch;
|
||||
const priorTrustLocalhost = process.env.WAGGLE_TRUST_LOCALHOST;
|
||||
|
||||
beforeAll(async () => {
|
||||
// The production default: loopback callers need the session token too.
|
||||
// vitest.setup.ts turns localhost trust on for the older suites.
|
||||
process.env.WAGGLE_TRUST_LOCALHOST = '0';
|
||||
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-probe-proxy-'));
|
||||
server = await buildLocalServer({ dataDir: tmpDir });
|
||||
await server.listen({ port: 0, host: '127.0.0.1' });
|
||||
server.vault.set('anthropic', 'sk-ant-test-key');
|
||||
});
|
||||
|
||||
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('verifies a working key', async () => {
|
||||
const upstream = vi.fn(async () => new Response(JSON.stringify({
|
||||
id: 'msg_probe',
|
||||
type: 'message',
|
||||
role: 'assistant',
|
||||
model: 'claude-haiku-4-5',
|
||||
content: [{ type: 'text', text: 'h' }],
|
||||
stop_reason: 'max_tokens',
|
||||
usage: { input_tokens: 1, output_tokens: 1 },
|
||||
}), { 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/settings/probe-model',
|
||||
payload: { model: 'claude-haiku-4-5' },
|
||||
});
|
||||
|
||||
expect(JSON.parse(res.body)).toMatchObject({ configured: true, verified: true });
|
||||
expect(upstream).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
43
packages/server/tests/local/self-request.test.ts
Normal file
43
packages/server/tests/local/self-request.test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* UF-044 — requests the sidecar sends to its own routes must carry the session
|
||||
* token (the server does not trust loopback callers) and target the port the
|
||||
* server is actually bound to.
|
||||
*/
|
||||
import { describe, it, expect, afterEach } from 'vitest';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { selfBaseUrl, selfRequestHeaders } from '../../src/local/self-request.js';
|
||||
|
||||
function fakeServer(address: unknown, token: string | undefined): FastifyInstance {
|
||||
return {
|
||||
server: { address: () => address },
|
||||
agentState: { wsSessionToken: token },
|
||||
} as unknown as FastifyInstance;
|
||||
}
|
||||
|
||||
describe('self requests (UF-044)', () => {
|
||||
const priorPort = process.env.WAGGLE_PORT;
|
||||
afterEach(() => {
|
||||
if (priorPort === undefined) delete process.env.WAGGLE_PORT;
|
||||
else process.env.WAGGLE_PORT = priorPort;
|
||||
});
|
||||
|
||||
it('targets the port the server is bound to', () => {
|
||||
process.env.WAGGLE_PORT = '3333';
|
||||
const server = fakeServer({ address: '127.0.0.1', family: 'IPv4', port: 53204 }, 't');
|
||||
expect(selfBaseUrl(server)).toBe('http://127.0.0.1:53204');
|
||||
});
|
||||
|
||||
it('falls back to WAGGLE_PORT, then 3333, before the server listens', () => {
|
||||
process.env.WAGGLE_PORT = '4100';
|
||||
expect(selfBaseUrl(fakeServer(null, 't'))).toBe('http://127.0.0.1:4100');
|
||||
delete process.env.WAGGLE_PORT;
|
||||
expect(selfBaseUrl(fakeServer(null, 't'))).toBe('http://127.0.0.1:3333');
|
||||
});
|
||||
|
||||
it('sends the session token as a bearer credential', () => {
|
||||
expect(selfRequestHeaders(fakeServer(null, 'session-123'))).toEqual({
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer session-123',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -752,6 +752,27 @@ describe('Workspace & Session API', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('probe-model sends the session token to the built-in proxy (UF-044)', async () => {
|
||||
const restoreModel = configureExactProbeModel();
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response('{}', { status: 200 }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
try {
|
||||
await injectWithAuth(server, {
|
||||
method: 'POST',
|
||||
url: '/api/settings/probe-model',
|
||||
payload: { model: exactProbeModel },
|
||||
});
|
||||
const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
|
||||
expect(url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/v1\/chat\/completions$/);
|
||||
expect(init.headers).toMatchObject({
|
||||
Authorization: `Bearer ${server.agentState.wsSessionToken}`,
|
||||
});
|
||||
} finally {
|
||||
restoreModel();
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it('probe-model reports rejected on a 401 from the model endpoint', async () => {
|
||||
const restoreModel = configureExactProbeModel();
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('unauthorized', { status: 401 })));
|
||||
|
||||
Reference in New Issue
Block a user