Open History to see the last commit
1import { it } from "@effect/vitest";
2import {
3 type ManagedPolicySummary,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 TextGeneratorConfig,
7} from "@t3tools/contracts";
8import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Schema from "effect/Schema";
12import * as FetchHttpClient from "effect/http/FetchHttpClient";
13import { expect, vi } from "vite-plus/test";
14β
15import * as ServerSettings from "../serverSettings.ts";
16import { SECRET_REDACTED } from "../settingsSecrets.ts";
17import { TEXT_GENERATOR_DRIVERS } from "./textGeneratorDrivers.ts";
18import * as TextGenerators from "./TextGenerators.ts";
19β
20const ID = ProviderInstanceId.make("router");
21const decodeTextGeneratorConfig = Schema.decodeUnknownEffect(TextGeneratorConfig);
22β
23const layer = (generator: Partial<TextGeneratorConfig>, policy?: ManagedPolicySummary) =>
24 Layer.effect(TextGenerators.TextGenerators, TextGenerators.make).pipe(
25 Layer.provideMerge(
26 ServerSettings.layerTest(
27 {
28 textGenerators: {
29 [ID]: { kind: "openaiCompatible", baseUrl: "https://api.test/v1", ...generator },
30 },
31 },
32 policy,
33 ),
34 ),
35 Layer.provide(FetchHttpClient.layer),
36 Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})),
37 );
38β
39const request = {
40 operation: "generateThreadTitle",
41 cwd: "/unused",
42 prompt: "Name this thread.",
43 outputSchema: Schema.Struct({ title: Schema.String }),
44 modelSelection: { instanceId: ID, model: "some/model" },
45} as const;
46β
47it.effect.each([
48 {
49 kind: "openaiCompatible",
50 path: "/v1/chat/completions",
51 auth: ["authorization", "Bearer secret"],
52 reply: { choices: [{ message: { content: '{"title":"Fix login"}' } }] },
53 },
54 {
55 kind: "anthropic",
56 path: "/v1/messages",
57 auth: ["x-api-key", "secret"],
58 reply: { content: [{ type: "text", text: '{"title":"Fix login"}' }] },
59 },
60] as const)("$kind generates structured text with its API's request shape", (api) =>
61 Effect.gen(function* () {
62 const upstream = vi.fn<typeof fetch>(async (url, init) => {
63 expect(new URL(String(url)).pathname).toBe(api.path);
64 expect(init?.redirect).toBe("error");
65 expect(new Headers(init?.headers).get(api.auth[0])).toBe(api.auth[1]);
66 const body = JSON.parse(String(init?.body));
67 expect(body.model).toBe("some/model");
68 expect(body.messages).toEqual([{ role: "user", content: "Name this thread." }]);
69 return Response.json(api.reply);
70 });
71 const generators = yield* TextGenerators.TextGenerators.pipe(
72 Effect.provide(layer({ kind: api.kind, apiKey: "secret" })),
73 );
74 const run = yield* generators.runner(ID);
75 expect(run).toBeDefined();
76 const result = yield* run!(request).pipe(
77 Effect.provideService(FetchHttpClient.Fetch, upstream),
78 );
79 expect(result).toEqual({ title: "Fix login" });
80 expect(yield* generators.runner(ProviderInstanceId.make("codex"))).toBeUndefined();
81β
82 upstream.mockResolvedValueOnce(
83 Response.json({ error: { message: "Incorrect API key provided" } }, { status: 401 }),
84 );
85 const failure = yield* Effect.flip(
86 run!(request).pipe(Effect.provideService(FetchHttpClient.Fetch, upstream)),
87 );
88 expect(failure.detail).toMatch(/rejected the API key: Incorrect API key provided$/);
89 }),
90);
91β
92it.effect("HTTP error detail does not split an emoji at the cutoff", () =>
93 Effect.gen(function* () {
94 const prefix = "a".repeat(299);
95 const upstream: typeof fetch = async () =>
96 Response.json({ error: { message: `${prefix}π` } }, { status: 400 });
97 const failure = yield* TEXT_GENERATOR_DRIVERS.openaiCompatible
98 .listModels({ baseUrl: "https://api.test/v1", apiKey: "", label: "Test API" })
99 .pipe(
100 Effect.provide(FetchHttpClient.layer),
101 Effect.provideService(FetchHttpClient.Fetch, upstream),
102 Effect.flip,
103 );
104β
105 expect(failure.detail).toBe(`Test API returned HTTP 400: ${prefix}`);
106 }),
107);
108β
109it.effect("a turned-off text generator fails instead of calling its API", () =>
110 Effect.gen(function* () {
111 const upstream = vi.fn<typeof fetch>();
112 const generators = yield* TextGenerators.TextGenerators.pipe(
113 Effect.provide(layer({ enabled: false, label: "OpenRouter" })),
114 );
115 const run = yield* generators.runner(ID);
116 const failure = yield* Effect.flip(
117 run!(request).pipe(Effect.provideService(FetchHttpClient.Fetch, upstream)),
118 );
119 expect(failure.detail).toBe("OpenRouter is off. Turn it on in Settings β Providers.");
120 expect(upstream).not.toHaveBeenCalled();
121 }),
122);
123β
124it.effect("lists models once per config, following Anthropic pagination, until refreshed", () =>
125 Effect.gen(function* () {
126 const upstream = vi.fn<typeof fetch>(async (url) => {
127 const parsed = new URL(String(url));
128 expect(parsed.pathname).toBe("/v1/models");
129 return parsed.searchParams.get("after_id") === "claude-b"
130 ? Response.json({ data: [{ id: "claude-a" }], has_more: false })
131 : Response.json({
132 data: [{ id: "claude-b", display_name: "Claude B" }],
133 has_more: true,
134 last_id: "claude-b",
135 });
136 });
137 const program = Effect.gen(function* () {
138 const generators = yield* TextGenerators.TextGenerators;
139 const settings = yield* ServerSettings.ServerSettingsService;
140 const list = (refresh?: boolean) =>
141 generators
142 .listModels({ id: ID, ...(refresh ? { refresh } : {}) })
143 .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream));
144β
145 expect((yield* list()).models).toEqual([
146 { id: "claude-a", name: "claude-a" },
147 { id: "claude-b", name: "Claude B" },
148 ]);
149 yield* list();
150 expect(upstream).toHaveBeenCalledTimes(2);
151β
152 yield* list(true);
153 expect(upstream).toHaveBeenCalledTimes(4);
154β
155 yield* settings.updateSettings({
156 textGenerators: {
157 [ID]: {
158 kind: "anthropic",
159 baseUrl: "https://api.test/v1",
160 apiKey: "rotated",
161 enabled: true,
162 },
163 },
164 });
165 yield* list();
166 expect(upstream).toHaveBeenCalledTimes(6);
167 });
168 yield* program.pipe(Effect.provide(layer({ kind: "anthropic", apiKey: "secret" })));
169 }),
170);
171β
172it.effect("checks unsaved settings, keeping the saved key behind a redaction marker", () =>
173 Effect.gen(function* () {
174 const seen: Array<{ url: string; auth: string | null }> = [];
175 const upstream = vi.fn<typeof fetch>(async (url, init) => {
176 seen.push({ url: String(url), auth: new Headers(init?.headers).get("authorization") });
177 return String(url).endsWith("/chat/completions")
178 ? Response.json({
179 model: JSON.parse(String(init?.body)).model,
180 choices: [{ finish_reason: "stop", message: { content: "OK" } }],
181 })
182 : Response.json({ data: [{ id: "model-a" }] });
183 });
184 const generators = yield* TextGenerators.TextGenerators.pipe(
185 Effect.provide(layer({ apiKey: "saved-key" })),
186 );
187 const list = (id: string, config: Partial<TextGeneratorConfig>) =>
188 generators
189 .listModels({
190 id: ProviderInstanceId.make(id),
191 config: {
192 kind: "openaiCompatible",
193 baseUrl: "https://new.test/v1",
194 apiKey: "",
195 enabled: true,
196 ...config,
197 },
198 })
199 .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream));
200β
201 expect((yield* list("draft", { apiKey: "typed-key" })).models).toEqual([
202 { id: "model-a", name: "model-a" },
203 ]);
204 yield* list(ID, { apiKey: SECRET_REDACTED, baseUrl: "https://api.test/v1" });
205 // The saved key goes only to the endpoint it was saved for.
206 yield* list(ID, { apiKey: SECRET_REDACTED });
207 expect(seen).toEqual([
208 { url: "https://new.test/v1/models", auth: "Bearer typed-key" },
209 { url: "https://api.test/v1/models", auth: "Bearer saved-key" },
210 { url: "https://new.test/v1/models", auth: null },
211 ]);
212β
213 // Listing alone proves nothing about the key on some APIs; a test asks the model itself.
214 const tested = yield* generators
215 .listModels({ id: ID, test: true, model: "chosen/model" })
216 .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream));
217 expect(tested.testedModel).toBe("chosen/model");
218 expect(seen.at(-1)).toEqual({
219 url: "https://api.test/v1/chat/completions",
220 auth: "Bearer saved-key",
221 });
222β
223 // An allow-list names agent drivers only, so no unsaved config may reach an API either.
224 const managed = yield* TextGenerators.TextGenerators.pipe(
225 Effect.provide(
226 layer(
227 { apiKey: "saved-key" },
228 {
229 organization: "Example Corp",
230 lockedSettings: [],
231 limits: {
232 providers: {
233 allowedDrivers: [ProviderDriverKind.make("codex")],
234 lockedInstanceFields: {},
235 },
236 },
237 },
238 ),
239 ),
240 );
241 const requestsBefore = seen.length;
242 const refused = yield* managed
243 .listModels({
244 id: ProviderInstanceId.make("draft"),
245 config: {
246 kind: "openaiCompatible",
247 baseUrl: "https://new.test/v1",
248 apiKey: "k",
249 enabled: true,
250 },
251 test: true,
252 })
253 .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream), Effect.flip);
254 expect(refused.detail).toContain("policy");
255 expect(seen).toHaveLength(requestsBefore);
256 }),
257);
258β
259it.effect.each([
260 {
261 kind: "openaiCompatible",
262 generatePath: "/v1/chat/completions",
263 modelsSearch: "",
264 reply: { choices: [{ message: { content: "OK" } }] },
265 },
266 {
267 kind: "anthropic",
268 generatePath: "/v1/messages",
269 modelsSearch: "?limit=1000",
270 reply: { content: [{ type: "text", text: "OK" }] },
271 },
272] as const)(
273 "$kind keeps endpoints in the pathname when baseUrl ends with empty query or fragment",
274 (api) =>
275 Effect.gen(function* () {
276 const generators = yield* TextGenerators.TextGenerators.pipe(Effect.provide(layer({})));
277 for (const baseUrl of [
278 "https://api.test/v1?",
279 "https://api.test/v1#",
280 "https://api.test/v1/?#",
281 ]) {
282 const seen: Array<{ pathname: string; search: string; hash: string }> = [];
283 const upstream = vi.fn<typeof fetch>(async (url, init) => {
284 const parsed = new URL(String(url));
285 seen.push({ pathname: parsed.pathname, search: parsed.search, hash: parsed.hash });
286 return (init?.method ?? "GET") === "GET"
287 ? Response.json({ data: [{ id: "some/model" }] })
288 : Response.json(api.reply);
289 });
290 const config = yield* decodeTextGeneratorConfig({
291 kind: api.kind,
292 baseUrl,
293 apiKey: "secret",
294 enabled: true,
295 });
296 yield* generators
297 .listModels({ id: ID, config, test: true, model: "some/model" })
298 .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream));
299 expect(seen).toEqual([
300 { pathname: "/v1/models", search: api.modelsSearch, hash: "" },
301 { pathname: api.generatePath, search: "", hash: "" },
302 ]);
303 }
304 }),
305);