-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.test.ts
More file actions
292 lines (262 loc) · 11.3 KB
/
Copy pathproxy.test.ts
File metadata and controls
292 lines (262 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// secret-scan: allow-fixture
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { CommandCenterDashboard } from "../src/core/dashboard.js";
import { ConfigManager, type SemanticConfig } from "../src/core/config.js";
import { EventStore } from "../src/history/event-store.js";
describe("dashboard OpenAI-compatible proxy route", () => {
let testDir: string;
let repoDir: string;
let store: EventStore;
const semanticConfig: SemanticConfig = {
localEnabled: true,
mcpSamplingEnabled: false,
baseUrl: "http://127.0.0.1:9000/v1",
models: ["gemma3:12b"],
timeoutMs: 1_000,
temperature: 0.2,
allowNonLoopback: false,
};
beforeEach(() => {
testDir = fs.mkdtempSync(path.join(os.tmpdir(), "proxy-route-"));
repoDir = path.join(testDir, "repo");
fs.mkdirSync(repoDir, { recursive: true });
process.env.PROMPT_REFINER_GLOBAL_DIR = path.join(testDir, "global");
(EventStore as unknown as { instance: EventStore | null }).instance = null;
store = EventStore.getInstance();
vi.spyOn(ConfigManager, "getSemanticConfig").mockReturnValue(semanticConfig);
});
afterEach(() => {
vi.restoreAllMocks();
store.close();
(EventStore as unknown as { instance: EventStore | null }).instance = null;
delete process.env.PROMPT_REFINER_GLOBAL_DIR;
fs.rmSync(testDir, { recursive: true, force: true });
});
it("records the prompt, forwards the request, and records a completed execution", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response("mock LLM response", {
status: 200,
headers: { "content-type": "text/plain" },
}));
vi.stubGlobal("fetch", fetchMock);
const app = CommandCenterDashboard.createApp(repoDir);
const response = await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: {
"content-type": "application/json",
authorization: "Bearer local-token",
},
body: JSON.stringify({
messages: [{ role: "user", content: "Improve this prompt" }],
}),
});
expect(response.status).toBe(200);
expect(await response.text()).toBe("mock LLM response");
expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:9000/v1/chat/completions", expect.objectContaining({
method: "POST",
headers: expect.objectContaining({
"Content-Type": "application/json",
"Authorization": "Bearer local-token",
}),
}));
const db = (store as any).db;
const prompt = db.prepare("SELECT * FROM prompts WHERE client = ?").get("API_PROXY");
expect(prompt.raw_prompt).toBe("Improve this prompt");
const execution = db.prepare("SELECT * FROM executions WHERE prompt_id = ?").get(prompt.id);
expect(execution).toMatchObject({
workflow_name: "proxy_forward",
executor_name: "LocalLLM",
status: "completed",
artifacts_json: "{}",
});
});
it("supports trailing-slash base URLs and falls back when no prompt message is present", async () => {
vi.spyOn(ConfigManager, "getSemanticConfig").mockReturnValueOnce({
...semanticConfig,
baseUrl: "http://127.0.0.1:9000/v1/",
});
const fetchMock = vi.fn().mockResolvedValue(new Response("ok", { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
const app = CommandCenterDashboard.createApp(repoDir);
const response = await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ messages: "not-an-array" }),
});
expect(response.status).toBe(200);
expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:9000/v1/chat/completions", expect.objectContaining({
headers: { "Content-Type": "application/json" },
}));
const db = (store as any).db;
expect(db.prepare("SELECT raw_prompt FROM prompts WHERE client = ?").get("API_PROXY"))
.toEqual({ raw_prompt: "Unknown proxy prompt" });
});
it("rejects malformed proxy requests before forwarding", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const app = CommandCenterDashboard.createApp(repoDir);
expect((await app.request("/proxy/v1/chat/completions", { method: "POST", body: "{}" })).status).toBe(415);
expect((await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{",
})).status).toBe(400);
vi.spyOn(ConfigManager, "getSemanticConfig").mockReturnValueOnce({
...semanticConfig,
baseUrl: "https://remote.example/v1",
allowNonLoopback: false,
});
expect((await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{}",
})).status).toBe(403);
vi.spyOn(ConfigManager, "getSemanticConfig").mockReturnValueOnce({
...semanticConfig,
baseUrl: "not a url",
});
expect((await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{}",
})).status).toBe(400);
expect(fetchMock).not.toHaveBeenCalled();
});
it("records failed executions for upstream HTTP and network failures", async () => {
const app = CommandCenterDashboard.createApp(repoDir);
vi.stubGlobal("fetch", vi.fn()
.mockResolvedValueOnce(new Response("token=secret-value", { status: 503, statusText: "Unavailable" }))
.mockRejectedValueOnce(new Error("connection refused with token=secret-value")));
const upstreamFailure = await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: "First" }] }),
});
expect(upstreamFailure.status).toBe(503);
expect(await upstreamFailure.text()).toBe("token=secret-value");
const networkFailure = await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: "Second" }] }),
});
expect(networkFailure.status).toBe(502);
expect(await networkFailure.json()).toEqual({ error: "Proxy request failed" });
const db = (store as any).db;
const failures = db.prepare("SELECT * FROM executions WHERE status = 'failed' ORDER BY started_at ASC").all();
expect(failures).toHaveLength(2);
expect(failures[0].result_summary).toContain("Upstream error: 503");
expect(failures[0].artifacts_json).toContain("token=[REDACTED]");
expect(failures[1].result_summary).toContain("Network error reaching upstream");
expect(failures[1].artifacts_json).toContain("token=[REDACTED]");
});
it("records non-Error network failures", async () => {
const app = CommandCenterDashboard.createApp(repoDir);
vi.stubGlobal("fetch", vi.fn().mockRejectedValue("string failure token=secret-value"));
const response = await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: "Prompt" }] }),
});
expect(response.status).toBe(502);
const db = (store as any).db;
const failure = db.prepare("SELECT * FROM executions WHERE status = 'failed'").get();
expect(failure.result_summary).toContain("string failure");
expect(failure.artifacts_json).toContain("token=[REDACTED]");
});
it("uses approved minified templates transparently and ignores invalid template regexes", async () => {
const repoId = store.ensureRepository(repoDir).id;
store.recordTemplate({
id: "non-minified",
repo_id: repoId,
category: "Feature",
title: "Non-minified",
template_text: "feature",
usage_notes: "^Verbose prompt$",
source_type: "test",
success_score: 200,
approved: 1,
});
store.recordTemplate({
id: "bad-regex",
repo_id: repoId,
category: "Minified",
title: "Bad regex",
template_text: "bad",
usage_notes: "[",
source_type: "test",
success_score: 150,
approved: 1,
});
store.recordTemplate({
id: "approved-minified",
repo_id: repoId,
category: "Minified",
title: "Approved minified",
template_text: "Short prompt",
usage_notes: "^Verbose prompt$",
source_type: "test",
success_score: 100,
approved: 1,
});
const fetchMock = vi.fn().mockResolvedValue(new Response("ok", { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
const app = CommandCenterDashboard.createApp(repoDir);
const response = await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ messages: [{ role: "user", content: "Verbose prompt" }] }),
});
expect(response.status).toBe(200);
expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:9000/v1/chat/completions", expect.objectContaining({
body: JSON.stringify({ messages: [{ role: "user", content: "Short prompt" }] }),
}));
const db = (store as any).db;
expect(db.prepare("SELECT raw_prompt, normalized_prompt FROM prompts WHERE client = ?").get("API_PROXY"))
.toEqual({ raw_prompt: "Verbose prompt", normalized_prompt: "Short prompt" });
});
it("records a matching minified fallback without mutating non-string message content", async () => {
const repoId = store.ensureRepository(repoDir).id;
store.recordTemplate({
id: "unknown-minified",
repo_id: repoId,
category: "Minified",
title: "Unknown fallback",
template_text: "Short fallback",
usage_notes: "^Unknown proxy prompt$",
source_type: "test",
success_score: 100,
approved: 1,
});
const fetchMock = vi.fn().mockResolvedValue(new Response("ok", { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
const app = CommandCenterDashboard.createApp(repoDir);
const body = { messages: [{ role: "user", content: { text: "not a string" } }] };
const response = await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
expect(response.status).toBe(200);
expect(fetchMock).toHaveBeenCalledWith("http://127.0.0.1:9000/v1/chat/completions", expect.objectContaining({
body: JSON.stringify(body),
}));
const db = (store as any).db;
expect(db.prepare("SELECT raw_prompt, normalized_prompt FROM prompts WHERE client = ?").get("API_PROXY"))
.toEqual({ raw_prompt: "Unknown proxy prompt", normalized_prompt: "Short fallback" });
});
it("returns a sanitized route failure when proxy bookkeeping fails", async () => {
const app = CommandCenterDashboard.createApp(repoDir);
vi.spyOn(EventStore, "getInstance").mockImplementationOnce(() => {
throw new Error("store secret");
});
const response = await app.request("/proxy/v1/chat/completions", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ messages: [] }),
});
expect(response.status).toBe(502);
expect(await response.json()).toEqual({ error: "Proxy request failed" });
});
});