@devries-cameron20 / t3code Mirror · read-only / commits / eb97d82156
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 02:00 UTC

feat: text generators let model APIs write titles, commits, and transcript cleanup (#33147)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 8, 2026 at 20:37 UTC eb97d82156f031d0533d4de80d4eeb9ad82788e7
40 files changed +2482 -144
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -88,6 +88,7 @@ const RPC_AGGREGATES = {
88 [WS_METHODS.serverGetResourceTelemetryHistory]: "server",
89 [WS_METHODS.serverRetryResourceTelemetry]: "server",
90 [WS_METHODS.serverCheckOtlpEndpoint]: "server",
91 + [WS_METHODS.serverListTextGeneratorModels]: "server",
92 [WS_METHODS.serverPrepareTriage]: "server",
93 [WS_METHODS.serverGetUsageSummary]: "server",
94 [WS_METHODS.serverRefreshUsageRates]: "server",
apps/server/src/policy/managedProviders.ts
+2
@@ -389,6 +389,8 @@ export function makeManagedProviders(
389 const result: ServerSettings = {
390 ...settings,
391 providerInstances: providerInstances as ServerSettings["providerInstances"],
392 + // An allow-list names agent drivers; text generators would send code to any other API.
393 + ...(allowed === undefined ? {} : { textGenerators: {} }),
394 sourceControlWriterModelSelection: allowedSelection(
395 settings,
396 settings.sourceControlWriterModelSelection,
apps/server/src/serverSettings.test.ts
+13
@@ -1751,8 +1751,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1751 const antigravity = ProviderInstanceId.make("antigravity");
1752 const openCode = ProviderInstanceId.make("opencode");
1753 const hub = UsageLimitSourceId.make("hub");
1754 + const router = ProviderInstanceId.make("openrouter");
1755 const withUsage = yield* serverSettings.updateSettings({
1756 cloudSpeechCredentials: { openai: usageReference, xai: "literal-fixture" },
1757 + textGenerators: {
1758 + [router]: {
1759 + kind: "openaiCompatible",
1760 + baseUrl: "https://openrouter.ai/api/v1",
1761 + apiKey: usageReference,
1762 + enabled: true,
1763 + },
1764 + },
1765 usageLimitSources: {
1766 [hub]: {
1767 kind: "cliproxy",
@@ -1805,6 +1814,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1814 });
1815 assert.equal(legacy.sourceControlHosts.bitbucket?.accessToken, SECRET_REDACTED);
1816 assert.equal(legacy.usageLimitSources[hub]?.managementKey, SECRET_REDACTED);
1817 + assert.equal(legacy.textGenerators[router]?.apiKey, SECRET_REDACTED);
1818 assert.equal(legacy.easDeviceHosts[0]?.accessToken, SECRET_REDACTED);
1819 assert.equal(legacy.simlockDeviceHosts[0]?.agentToken, SECRET_REDACTED);
1820 const configOf = (settings: ServerSettings, id: ProviderInstanceId) =>
@@ -1815,6 +1825,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1825 cloudSpeechCredentials: legacy.cloudSpeechCredentials,
1826 sourceControlHosts: legacy.sourceControlHosts,
1827 usageLimitSources: legacy.usageLimitSources,
1828 + textGenerators: legacy.textGenerators,
1829 easDeviceHosts: legacy.easDeviceHosts,
1830 simlockDeviceHosts: legacy.simlockDeviceHosts,
1831 providerInstances: legacy.providerInstances,
@@ -1825,6 +1836,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1836 "ghe.acme.test": "ghp_ghe",
1837 });
1838 assert.deepEqual(echoed.usageLimitSources[hub]?.managementKey, usageReference);
1839 + assert.deepEqual(echoed.textGenerators[router]?.apiKey, usageReference);
1840 assert.deepEqual(echoed.cloudSpeechCredentials, {
1841 openai: usageReference,
1842 xai: "literal-fixture",
@@ -1930,6 +1942,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings"
1942 "easDeviceHosts.[].accessToken",
1943 "simlockDeviceHosts.[].agentToken",
1944 "usageLimitSources.*.managementKey",
1945 + "textGenerators.*.apiKey",
1946 ]);
1947 }),
1948 );
apps/server/src/settingsSecrets.ts
+16
@@ -8,6 +8,7 @@ import {
8 type ServerSettings,
9 type SettingsSecretValue,
10 SimlockDeviceHostConfig,
11 + TextGeneratorConfig,
12 UsageLimitSourceConfig,
13 isSecretReference,
14 secretSettingsFields,
@@ -46,6 +47,7 @@ const providerSecretFields = new Map([
47 ),
48 ]);
49 const usageLimitSecretFields = secretSettingsFields(UsageLimitSourceConfig);
50 +const textGeneratorSecretFields = secretSettingsFields(TextGeneratorConfig);
51 const voiceSecretFields = secretSettingsFields(CloudSpeechCredentials);
52 const easDeviceHostSecretFields = secretSettingsFields(EasDeviceHostConfig);
53 const simlockDeviceHostSecretFields = secretSettingsFields(SimlockDeviceHostConfig);
@@ -209,6 +211,19 @@ function mapSecretFieldGroups(
211 ]),
212 ) as ServerSettings["usageLimitSources"];
213
214 + const textGenerators = Object.fromEntries(
215 + Object.entries(settings.textGenerators).map(([id, generator]) => [
216 + id,
217 + mapFields(
218 + generator,
219 + textGeneratorSecretFields,
220 + (field, serverHost) =>
221 + `text-generator-${encode(id)}-${encode(field)}` +
222 + (serverHost === null ? "" : `-${encode(serverHost)}`),
223 + ),
224 + ]),
225 + ) as ServerSettings["textGenerators"];
226 +
227 const easDeviceHosts = settings.easDeviceHosts.map(
228 (host) =>
229 mapFields(
@@ -242,6 +257,7 @@ function mapSecretFieldGroups(
257 providerInstances,
258 sourceControlHosts,
259 usageLimitSources,
260 + textGenerators,
261 easDeviceHosts,
262 simlockDeviceHosts,
263 };
apps/server/src/sourceControl/sourceControlHostSecrets.test.ts
+1
@@ -178,6 +178,7 @@ it.effect("reads a collected reference again once it is invalidated", () =>
178 sourceControlHosts: hosts,
179 cloudSpeechCredentials: { openai: source("voice#key"), xai: "", openrouter: "" },
180 usageLimitSources,
181 + textGenerators: {},
182 easDeviceHosts,
183 simlockDeviceHosts,
184 }),
apps/server/src/sourceControl/sourceControlHostSecrets.ts
+4
@@ -120,6 +120,7 @@ export const invalidateSettingsSecrets = Effect.fn("SettingsSecrets.invalidate")
120 ServerSettings,
121 | "sourceControlHosts"
122 | "usageLimitSources"
123 + | "textGenerators"
124 | "easDeviceHosts"
125 | "simlockDeviceHosts"
126 | "cloudSpeechCredentials"
@@ -131,6 +132,9 @@ export const invalidateSettingsSecrets = Effect.fn("SettingsSecrets.invalidate")
132 Effect.map((current) => [
133 ...collectSourceControlHostSecretReferences(current.sourceControlHosts),
134 ...collectUsageLimitSecretReferences(current.usageLimitSources),
135 + ...Object.values(current.textGenerators).flatMap(({ apiKey }) =>
136 + isSecretReference(apiKey) ? [apiKey] : [],
137 + ),
138 ...collectDeviceHostSecretReferences(current),
139 ...Object.values(current.cloudSpeechCredentials).filter(isSecretReference),
140 ]),
apps/server/src/textGeneration/CodexTextGeneration.test.ts
+89
@@ -27,6 +27,7 @@ import { CodexSettings, ProviderInstanceId } from "@t3tools/contracts";
27 import * as ServerConfig from "../config.ts";
28 import { makeProcessProbe, processProbeSource } from "../testUtils/processProbe.ts";
29 import * as TextGeneration from "./TextGeneration.ts";
30 +import * as TextGenerators from "./TextGenerators.ts";
31 import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
32 import { writeFakeCli } from "@t3tools/provider-testing/fakeCli";
33 const decodeCodexSettings = Schema.decodeSync(CodexSettings);
@@ -625,6 +626,7 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima
626 [fallback]: { driver: ProviderDriverKind.make("claudeAgent"), config: {} },
627 },
628 }),
629 + Layer.mock(TextGenerators.TextGenerators)({ runner: () => Effect.undefined }),
630 Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
631 resolveLink: () => Effect.die("unused"),
632 }),
@@ -652,3 +654,90 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima
654 ]);
655 }),
656 );
657 +
658 +it.effect(
659 + "a review guide aimed at a text generator falls back to an agent that can read the checkout",
660 + () =>
661 + Effect.gen(function* () {
662 + const claude = ProviderInstanceId.make("claudeAgent");
663 + const driver = ProviderDriverKind.make("claudeAgent");
664 + const calls: ModelSelection[] = [];
665 + const instance = {
666 + instanceId: claude,
667 + driverKind: driver,
668 + continuationIdentity: { driverKind: driver, continuationKey: claude },
669 + displayName: undefined,
670 + enabled: true,
671 + snapshot: {
672 + getSnapshot: Effect.succeed<ServerProvider>({
673 + instanceId: claude,
674 + driver,
675 + enabled: true,
676 + installed: true,
677 + status: "ready",
678 + auth: { status: "authenticated" },
679 + version: null,
680 + checkedAt: "1970-01-01T00:00:00Z",
681 + models: [],
682 + slashCommands: [],
683 + skills: [],
684 + }),
685 + } as ProviderInstance["snapshot"],
686 + orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
687 + textGeneration: TextGeneration.TextGeneration.of({
688 + generateCommitMessage: () => Effect.die("unused"),
689 + generatePrContent: () => Effect.die("unused"),
690 + generateBranchName: () => Effect.die("unused"),
691 + generateThreadTitle: () => Effect.die("unused"),
692 + generateTranscriptionPostProcessing: () => Effect.die("unused"),
693 + generateReviewGuide: (input) =>
694 + Effect.sync(() => {
695 + calls.push(input.modelSelection);
696 + return {} as TextGeneration.ReviewGuideGenerationResult;
697 + }),
698 + }),
699 + } satisfies ProviderInstance;
700 + const serviceWith = (instances: ReadonlyArray<ProviderInstance>) =>
701 + TextGeneration.make.pipe(
702 + Effect.provide(
703 + Layer.mergeAll(
704 + Layer.mock(ProviderInstanceRegistry.ProviderInstanceRegistry)({
705 + listInstances: Effect.succeed(instances),
706 + getInstance: (id) =>
707 + Effect.succeed(instances.find((candidate) => candidate.instanceId === id)),
708 + }),
709 + ServerSettings.layerTest({}),
710 + Layer.mock(TextGenerators.TextGenerators)({
711 + runner: (id) =>
712 + Effect.succeed(
713 + id === "openrouter"
714 + ? () => Effect.die("a text generator cannot investigate")
715 + : undefined,
716 + ),
717 + }),
718 + Layer.mock(SourceControlProviderRegistry.SourceControlProviderRegistry)({
719 + resolveLink: () => Effect.die("unused"),
720 + }),
721 + ),
722 + ),
723 + );
724 + const input = {
725 + cwd: "/tmp",
726 + number: 1,
727 + title: "Change",
728 + description: "",
729 + baseBranch: "main",
730 + baseCommit: "abc",
731 + settledReview: "",
732 + modelSelection: { instanceId: ProviderInstanceId.make("openrouter"), model: "some/model" },
733 + };
734 + yield* (yield* serviceWith([instance])).generateReviewGuide(input);
735 + expect(calls.map((selection) => selection.instanceId)).toEqual([claude]);
736 +
737 + // With no agent ready, it says what is missing instead of looking up a provider by that id.
738 + const failure = yield* Effect.flip((yield* serviceWith([])).generateReviewGuide(input));
739 + expect(failure.detail).toMatch(
740 + /^Review guides need a coding agent that can read the checkout/,
741 + );
742 + }),
743 +);
apps/server/src/textGeneration/TextGeneration.ts
+28 -4
@@ -21,6 +21,8 @@ import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.
21 import type { ProviderInstance } from "@t3tools/provider-core/server/driver";
22 import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
23 import * as ThreadTitleLinks from "./ThreadTitleLinks.ts";
24 +import * as TextGenerators from "./TextGenerators.ts";
25 +import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
26
27 export type {
28 BranchNameGenerationInput,
@@ -75,6 +77,7 @@ export const make = Effect.gen(function* () {
77 const registry = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
78 const sourceControl = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
79 const serverSettings = yield* ServerSettings.ServerSettingsService;
80 + const textGenerators = yield* TextGenerators.TextGenerators;
81 const generate = Effect.fn("TextGeneration.generate")(function* <A>(
82 operation: TextGenerationOp,
83 selection: ModelSelection,
@@ -83,6 +86,17 @@ export const make = Effect.gen(function* () {
86 modelSelection: ModelSelection,
87 ) => Effect.Effect<A, TextGenerationError>,
88 ) {
89 + const textGenerator = yield* textGenerators.runner(selection.instanceId);
90 + // A review guide reaches a text generator only through a fallback; it needs an agent instead.
91 + const textGeneratorId = selection.instanceId;
92 + const textGeneratorCannotRun =
93 + textGenerator !== undefined && operation === "generateReviewGuide";
94 + if (textGenerator !== undefined && !textGeneratorCannotRun) {
95 + return yield* invoke(
96 + TextGenerationOperations.fromRunner("TextGenerator", textGenerator),
97 + selection,
98 + );
99 + }
100 const snapshots = yield* registry.listInstances.pipe(
101 Effect.flatMap((instances) =>
102 Effect.forEach(instances, (instance) => instance.snapshot.getSnapshot),
@@ -92,9 +106,10 @@ export const make = Effect.gen(function* () {
106 const selected = snapshots.find((provider) => provider.instanceId === selection.instanceId);
107 // Only a failed probe counts: a pending one is also not installed yet.
108 const unusable =
95 - selected?.enabled === true &&
96 - selected.status === "error" &&
97 - (!selected.installed || selected.auth.status === "unauthenticated");
109 + textGeneratorCannotRun ||
110 + (selected?.enabled === true &&
111 + selected.status === "error" &&
112 + (!selected.installed || selected.auth.status === "unauthenticated"));
113 if (unusable || exhaustedUsageWindow(selected, now, selection.model)) {
114 const settings = yield* serverSettings.getSettings.pipe(
115 Effect.mapError(
@@ -127,6 +142,13 @@ export const make = Effect.gen(function* () {
142 { includeConfiguredInstances: true },
143 ) ?? selection;
144 }
145 + if (textGeneratorCannotRun && selection.instanceId === textGeneratorId) {
146 + return yield* new TextGenerationError({
147 + operation,
148 + detail:
149 + "Review guides need a coding agent that can read the checkout. None is ready. Pick Codex or Claude as the review guide model in Settings → Source control.",
150 + });
151 + }
152 return yield* resolveInstance(registry, operation, selection.instanceId).pipe(
153 Effect.flatMap((service) => invoke(service, selection)),
154 );
@@ -187,4 +209,6 @@ export const make = Effect.gen(function* () {
209 });
210 });
211
190 -export const layer = Layer.effect(TextGeneration, make);
212 +export const layer = Layer.effect(TextGeneration, make).pipe(
213 + Layer.provideMerge(TextGenerators.layer),
214 +);
apps/server/src/textGeneration/TextGenerators.test.ts new
+235
@@ -0,0 +1,235 @@
1 +import { it } from "@effect/vitest";
2 +import {
3 + type ManagedPolicySummary,
4 + ProviderDriverKind,
5 + ProviderInstanceId,
6 + type TextGeneratorConfig,
7 +} from "@t3tools/contracts";
8 +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
9 +import * as Effect from "effect/Effect";
10 +import * as Layer from "effect/Layer";
11 +import * as Schema from "effect/Schema";
12 +import * as FetchHttpClient from "effect/http/FetchHttpClient";
13 +import { expect, vi } from "vite-plus/test";
14 +
15 +import * as ServerSettings from "../serverSettings.ts";
16 +import { SECRET_REDACTED } from "../settingsSecrets.ts";
17 +import * as TextGenerators from "./TextGenerators.ts";
18 +
19 +const ID = ProviderInstanceId.make("router");
20 +
21 +const layer = (generator: Partial<TextGeneratorConfig>, policy?: ManagedPolicySummary) =>
22 + Layer.effect(TextGenerators.TextGenerators, TextGenerators.make).pipe(
23 + Layer.provideMerge(
24 + ServerSettings.layerTest(
25 + {
26 + textGenerators: {
27 + [ID]: { kind: "openaiCompatible", baseUrl: "https://api.test/v1", ...generator },
28 + },
29 + },
30 + policy,
31 + ),
32 + ),
33 + Layer.provide(FetchHttpClient.layer),
34 + Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})),
35 + );
36 +
37 +const request = {
38 + operation: "generateThreadTitle",
39 + cwd: "/unused",
40 + prompt: "Name this thread.",
41 + outputSchema: Schema.Struct({ title: Schema.String }),
42 + modelSelection: { instanceId: ID, model: "some/model" },
43 +} as const;
44 +
45 +it.effect.each([
46 + {
47 + kind: "openaiCompatible",
48 + path: "/v1/chat/completions",
49 + auth: ["authorization", "Bearer secret"],
50 + reply: { choices: [{ finish_reason: "stop", message: { content: '{"title":"Fix login"}' } }] },
51 + },
52 + {
53 + kind: "anthropic",
54 + path: "/v1/messages",
55 + auth: ["x-api-key", "secret"],
56 + reply: { stop_reason: "end_turn", content: [{ type: "text", text: '{"title":"Fix login"}' }] },
57 + },
58 +] as const)("$kind generates structured text with its API's request shape", (api) =>
59 + Effect.gen(function* () {
60 + const upstream = vi.fn<typeof fetch>(async (url, init) => {
61 + expect(new URL(String(url)).pathname).toBe(api.path);
62 + expect(init?.redirect).toBe("error");
63 + expect(new Headers(init?.headers).get(api.auth[0])).toBe(api.auth[1]);
64 + const body = JSON.parse(String(init?.body));
65 + expect(body.model).toBe("some/model");
66 + expect(body.messages).toEqual([{ role: "user", content: "Name this thread." }]);
67 + return Response.json(api.reply);
68 + });
69 + const generators = yield* TextGenerators.TextGenerators.pipe(
70 + Effect.provide(layer({ kind: api.kind, apiKey: "secret" })),
71 + );
72 + const run = yield* generators.runner(ID);
73 + expect(run).toBeDefined();
74 + const result = yield* run!(request).pipe(
75 + Effect.provideService(FetchHttpClient.Fetch, upstream),
76 + );
77 + expect(result).toEqual({ title: "Fix login" });
78 + expect(yield* generators.runner(ProviderInstanceId.make("codex"))).toBeUndefined();
79 +
80 + upstream.mockResolvedValueOnce(
81 + Response.json({ error: { message: "Incorrect API key provided" } }, { status: 401 }),
82 + );
83 + const failure = yield* Effect.flip(
84 + run!(request).pipe(Effect.provideService(FetchHttpClient.Fetch, upstream)),
85 + );
86 + expect(failure.detail).toMatch(/rejected the API key: Incorrect API key provided$/);
87 + }),
88 +);
89 +
90 +it.effect("a turned-off text generator fails instead of calling its API", () =>
91 + Effect.gen(function* () {
92 + const upstream = vi.fn<typeof fetch>();
93 + const generators = yield* TextGenerators.TextGenerators.pipe(
94 + Effect.provide(layer({ enabled: false, label: "OpenRouter" })),
95 + );
96 + const run = yield* generators.runner(ID);
97 + const failure = yield* Effect.flip(
98 + run!(request).pipe(Effect.provideService(FetchHttpClient.Fetch, upstream)),
99 + );
100 + expect(failure.detail).toBe("OpenRouter is off. Turn it on in Settings → Providers.");
101 + expect(upstream).not.toHaveBeenCalled();
102 + }),
103 +);
104 +
105 +it.effect("lists models once per config, following Anthropic pagination, until refreshed", () =>
106 + Effect.gen(function* () {
107 + const upstream = vi.fn<typeof fetch>(async (url) => {
108 + const parsed = new URL(String(url));
109 + expect(parsed.pathname).toBe("/v1/models");
110 + return parsed.searchParams.get("after_id") === "claude-b"
111 + ? Response.json({ data: [{ id: "claude-a" }], has_more: false })
112 + : Response.json({
113 + data: [{ id: "claude-b", display_name: "Claude B" }],
114 + has_more: true,
115 + last_id: "claude-b",
116 + });
117 + });
118 + const program = Effect.gen(function* () {
119 + const generators = yield* TextGenerators.TextGenerators;
120 + const settings = yield* ServerSettings.ServerSettingsService;
121 + const list = (refresh?: boolean) =>
122 + generators
123 + .listModels({ id: ID, ...(refresh ? { refresh } : {}) })
124 + .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream));
125 +
126 + expect((yield* list()).models).toEqual([
127 + { id: "claude-a", name: "claude-a" },
128 + { id: "claude-b", name: "Claude B" },
129 + ]);
130 + yield* list();
131 + expect(upstream).toHaveBeenCalledTimes(2);
132 +
133 + yield* list(true);
134 + expect(upstream).toHaveBeenCalledTimes(4);
135 +
136 + yield* settings.updateSettings({
137 + textGenerators: {
138 + [ID]: {
139 + kind: "anthropic",
140 + baseUrl: "https://api.test/v1",
141 + apiKey: "rotated",
142 + enabled: true,
143 + },
144 + },
145 + });
146 + yield* list();
147 + expect(upstream).toHaveBeenCalledTimes(6);
148 + });
149 + yield* program.pipe(Effect.provide(layer({ kind: "anthropic", apiKey: "secret" })));
150 + }),
151 +);
152 +
153 +it.effect("checks unsaved settings, keeping the saved key behind a redaction marker", () =>
154 + Effect.gen(function* () {
155 + const seen: Array<{ url: string; auth: string | null }> = [];
156 + const upstream = vi.fn<typeof fetch>(async (url, init) => {
157 + seen.push({ url: String(url), auth: new Headers(init?.headers).get("authorization") });
158 + return String(url).endsWith("/chat/completions")
159 + ? Response.json({
160 + model: JSON.parse(String(init?.body)).model,
161 + choices: [{ finish_reason: "stop", message: { content: "OK" } }],
162 + })
163 + : Response.json({ data: [{ id: "model-a" }] });
164 + });
165 + const generators = yield* TextGenerators.TextGenerators.pipe(
166 + Effect.provide(layer({ apiKey: "saved-key" })),
167 + );
168 + const list = (id: string, config: Partial<TextGeneratorConfig>) =>
169 + generators
170 + .listModels({
171 + id: ProviderInstanceId.make(id),
172 + config: {
173 + kind: "openaiCompatible",
174 + baseUrl: "https://new.test/v1",
175 + apiKey: "",
176 + enabled: true,
177 + ...config,
178 + },
179 + })
180 + .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream));
181 +
182 + expect((yield* list("draft", { apiKey: "typed-key" })).models).toEqual([
183 + { id: "model-a", name: "model-a" },
184 + ]);
185 + yield* list(ID, { apiKey: SECRET_REDACTED });
186 + expect(seen).toEqual([
187 + { url: "https://new.test/v1/models", auth: "Bearer typed-key" },
188 + { url: "https://new.test/v1/models", auth: "Bearer saved-key" },
189 + ]);
190 +
191 + // Listing alone proves nothing about the key on some APIs; a test asks the model itself.
192 + const tested = yield* generators
193 + .listModels({ id: ID, test: true, model: "chosen/model" })
194 + .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream));
195 + expect(tested.testedModel).toBe("chosen/model");
196 + expect(seen.at(-1)).toEqual({
197 + url: "https://api.test/v1/chat/completions",
198 + auth: "Bearer saved-key",
199 + });
200 +
201 + // An allow-list names agent drivers only, so no unsaved config may reach an API either.
202 + const managed = yield* TextGenerators.TextGenerators.pipe(
203 + Effect.provide(
204 + layer(
205 + { apiKey: "saved-key" },
206 + {
207 + organization: "Example Corp",
208 + lockedSettings: [],
209 + limits: {
210 + providers: {
211 + allowedDrivers: [ProviderDriverKind.make("codex")],
212 + lockedInstanceFields: {},
213 + },
214 + },
215 + },
216 + ),
217 + ),
218 + );
219 + const requestsBefore = seen.length;
220 + const refused = yield* managed
221 + .listModels({
222 + id: ProviderInstanceId.make("draft"),
223 + config: {
224 + kind: "openaiCompatible",
225 + baseUrl: "https://new.test/v1",
226 + apiKey: "k",
227 + enabled: true,
228 + },
229 + test: true,
230 + })
231 + .pipe(Effect.provideService(FetchHttpClient.Fetch, upstream), Effect.flip);
232 + expect(refused.detail).toContain("policy");
233 + expect(seen).toHaveLength(requestsBefore);
234 + }),
235 +);
apps/server/src/textGeneration/TextGenerators.ts new
+190
@@ -0,0 +1,190 @@
1 +import {
2 + type ListTextGeneratorModelsInput,
3 + type ListTextGeneratorModelsResult,
4 + type ProviderInstanceId,
5 + TextGenerationError,
6 + type TextGeneratorConfig,
7 + TextGeneratorError,
8 + type TextGeneratorModel,
9 + textGeneratorForSelection,
10 +} from "@t3tools/contracts";
11 +import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations";
12 +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
13 +import * as Context from "effect/Context";
14 +import * as Effect from "effect/Effect";
15 +import * as Equal from "effect/Equal";
16 +import * as Layer from "effect/Layer";
17 +import * as Ref from "effect/Ref";
18 +import { FetchHttpClient, HttpClient } from "effect/http";
19 +
20 +import * as SecretResolverLayer from "../secrets/SecretResolver.ts";
21 +import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts";
22 +import * as ServerSettings from "../serverSettings.ts";
23 +import { SECRET_REDACTED } from "../settingsSecrets.ts";
24 +import {
25 + TEXT_GENERATOR_DRIVERS,
26 + type TextGeneratorConnection,
27 + TextGeneratorRequestError,
28 +} from "./textGeneratorDrivers.ts";
29 +
30 +/** Text generators configured in settings: model APIs that generate text but cannot run agents. */
31 +export class TextGenerators extends Context.Service<
32 + TextGenerators,
33 + {
34 + /** The runner for a text generator id, or undefined when the id names no text generator. */
35 + readonly runner: (
36 + id: ProviderInstanceId,
37 + ) => Effect.Effect<TextGenerationOperations.Runner | undefined>;
38 + readonly listModels: (
39 + input: ListTextGeneratorModelsInput,
40 + ) => Effect.Effect<ListTextGeneratorModelsResult, TextGeneratorError>;
41 + }
42 +>()("t3/textGeneration/TextGenerators") {}
43 +
44 +interface CachedModels {
45 + readonly config: TextGeneratorConfig;
46 + readonly models: ReadonlyArray<TextGeneratorModel>;
47 +}
48 +
49 +/** The generator's name for messages: its label, else the host it reaches. */
50 +const generatorLabel = (config: TextGeneratorConfig) => {
51 + if (config.label) return config.label;
52 + try {
53 + return new URL(config.baseUrl).host;
54 + } catch {
55 + return "The model API";
56 + }
57 +};
58 +
59 +/** @public */
60 +export const make = Effect.gen(function* () {
61 + const settingsService = yield* ServerSettings.ServerSettingsService;
62 + const secrets = yield* SecretResolver.SecretResolver;
63 + const http = yield* HttpClient.HttpClient;
64 + const modelCache = yield* Ref.make(new Map<ProviderInstanceId, CachedModels>());
65 + // Settings already drop saved generators under an allow-list; this stops unsaved ones too.
66 + const allowListed =
67 + settingsService.managedPolicy?.limits?.providers?.allowedDrivers !== undefined;
68 +
69 + const readConfig = Effect.fn("TextGenerators.readConfig")(function* (id: ProviderInstanceId) {
70 + const settings = yield* settingsService.getSettings.pipe(
71 + Effect.mapError(
72 + () =>
73 + new TextGeneratorRequestError({ detail: "Couldn't read this environment's settings." }),
74 + ),
75 + );
76 + return textGeneratorForSelection(settings, id);
77 + });
78 +
79 + const connect = Effect.fn("TextGenerators.connect")(function* (config: TextGeneratorConfig) {
80 + const label = generatorLabel(config);
81 + const apiKey = yield* requireSettingsSecret(secrets, config.apiKey).pipe(
82 + Effect.mapError((cause) => new TextGeneratorRequestError({ detail: cause.message, cause })),
83 + );
84 + return { baseUrl: config.baseUrl, apiKey, label } satisfies TextGeneratorConnection;
85 + });
86 +
87 + const runnerFor =
88 + (config: TextGeneratorConfig): TextGenerationOperations.Runner =>
89 + (request) => {
90 + const driver = TEXT_GENERATOR_DRIVERS[config.kind];
91 + const label = generatorLabel(config);
92 + return connect(config).pipe(
93 + Effect.flatMap((connection) =>
94 + driver.generate(connection, request.modelSelection.model, request.prompt),
95 + ),
96 + Effect.provideService(HttpClient.HttpClient, http),
97 + Effect.mapError(
98 + (error) =>
99 + new TextGenerationError({
100 + operation: request.operation,
101 + detail: error.detail,
102 + cause: error,
103 + }),
104 + ),
105 + Effect.flatMap((text) => TextGenerationOperations.decodeJsonReply(request, label, text)),
106 + );
107 + };
108 +
109 + const runner = Effect.fn("TextGenerators.runner")(function* (id: ProviderInstanceId) {
110 + const config = yield* readConfig(id).pipe(Effect.orElseSucceed(() => undefined));
111 + if (config === undefined) return undefined;
112 + const label = generatorLabel(config);
113 + if (!config.enabled) {
114 + return ((request) =>
115 + Effect.fail(
116 + new TextGenerationError({
117 + operation: request.operation,
118 + detail: `${label} is off. Turn it on in Settings → Providers.`,
119 + }),
120 + )) satisfies TextGenerationOperations.Runner;
121 + }
122 + return TextGenerationOperations.withoutInvestigation(label, runnerFor(config));
123 + });
124 +
125 + const listModels = Effect.fn("TextGenerators.listModels")(
126 + function* (input: ListTextGeneratorModelsInput) {
127 + if (allowListed) {
128 + return yield* new TextGeneratorRequestError({
129 + detail: "Your organization's provider policy turns off text generators.",
130 + });
131 + }
132 + const saved = yield* readConfig(input.id);
133 + const config =
134 + input.config === undefined
135 + ? saved
136 + : input.config.apiKey === SECRET_REDACTED
137 + ? { ...input.config, apiKey: saved?.apiKey ?? "" }
138 + : input.config;
139 + if (config === undefined) {
140 + return yield* new TextGeneratorRequestError({
141 + detail: "That text generator no longer exists.",
142 + });
143 + }
144 + // Checking unsaved settings, or testing, must reach the API rather than trust the cache.
145 + const fresh = input.config !== undefined || input.test === true;
146 + const cached = (yield* Ref.get(modelCache)).get(input.id);
147 + // Keyed on the whole config so a changed URL or key never serves another API's list.
148 + if (
149 + !fresh &&
150 + input.refresh !== true &&
151 + cached !== undefined &&
152 + Equal.equals(cached.config, config)
153 + ) {
154 + return { models: cached.models };
155 + }
156 + const connection = yield* connect(config);
157 + const driver = TEXT_GENERATOR_DRIVERS[config.kind];
158 + const models = yield* driver
159 + .listModels(connection)
160 + .pipe(Effect.provideService(HttpClient.HttpClient, http));
161 + if (input.test === true) {
162 + // An explicit test sends one tiny request: some APIs list models without checking the key.
163 + const model =
164 + input.model ??
165 + (models.find((candidate) => /haiku|mini|flash|nano/i.test(candidate.id)) ?? models[0])
166 + ?.id;
167 + if (model === undefined) {
168 + return yield* new TextGeneratorRequestError({
169 + detail: `${connection.label} lists no models to test with.`,
170 + });
171 + }
172 + yield* driver
173 + .generate(connection, model, "Reply with OK.")
174 + .pipe(Effect.provideService(HttpClient.HttpClient, http));
175 + return { models, testedModel: model };
176 + }
177 + yield* Ref.update(modelCache, (current) =>
178 + new Map(current).set(input.id, { config, models }),
179 + );
180 + return { models };
181 + },
182 + Effect.mapError((error) => new TextGeneratorError({ detail: error.detail })),
183 + );
184 +
185 + return TextGenerators.of({ runner, listModels });
186 +});
187 +
188 +export const layer = Layer.effect(TextGenerators, make).pipe(
189 + Layer.provide([SecretResolverLayer.layer, FetchHttpClient.layer]),
190 +);
apps/server/src/textGeneration/textGeneratorDrivers.ts new
+257
@@ -0,0 +1,257 @@
1 +import type { TextGeneratorKind, TextGeneratorModel } from "@t3tools/contracts";
2 +import * as Effect from "effect/Effect";
3 +import * as Schema from "effect/Schema";
4 +import {
5 + FetchHttpClient,
6 + HttpClient,
7 + HttpClientRequest,
8 + type HttpClientResponse,
9 +} from "effect/http";
10 +
11 +/** Where a text generator is reached, with its key already read from wherever settings keep it. */
12 +export interface TextGeneratorConnection {
13 + readonly baseUrl: string;
14 + readonly apiKey: string;
15 + /** Names the generator in errors, such as its label or host. */
16 + readonly label: string;
17 +}
18 +
19 +/** Why a model API call failed, worded for the person who configured it. */
20 +export class TextGeneratorRequestError extends Schema.TaggedError<TextGeneratorRequestError>()(
21 + "TextGeneratorRequestError",
22 + { detail: Schema.String, cause: Schema.optional(Schema.Defect()) },
23 +) {}
24 +
25 +export interface TextGeneratorDriver {
26 + readonly kind: TextGeneratorKind;
27 + readonly generate: (
28 + connection: TextGeneratorConnection,
29 + model: string,
30 + prompt: string,
31 + ) => Effect.Effect<string, TextGeneratorRequestError, HttpClient.HttpClient>;
32 + readonly listModels: (
33 + connection: TextGeneratorConnection,
34 + ) => Effect.Effect<
35 + ReadonlyArray<TextGeneratorModel>,
36 + TextGeneratorRequestError,
37 + HttpClient.HttpClient
38 + >;
39 +}
40 +
41 +const GENERATE_TIMEOUT = "2 minutes";
42 +const LIST_MODELS_TIMEOUT = "25 seconds";
43 +const MAX_MODEL_PAGES = 10;
44 +
45 +const ApiErrorBody = Schema.Struct({
46 + error: Schema.Struct({ message: Schema.String }),
47 +});
48 +const decodeApiErrorBody = Schema.decodeUnknownOption(ApiErrorBody);
49 +
50 +const describeStatus = (label: string, status: number, message: string | undefined) => {
51 + const reason =
52 + status === 401 || status === 403
53 + ? "rejected the API key"
54 + : status === 404
55 + ? "couldn't find that model or endpoint"
56 + : status === 429
57 + ? "is rate-limiting requests"
58 + : `returned HTTP ${status}`;
59 + const detail = message?.trim().slice(0, 300);
60 + return `${label} ${reason}${detail ? `: ${detail}` : "."}`;
61 +};
62 +
63 +const endpoint = (connection: TextGeneratorConnection, path: string) =>
64 + `${connection.baseUrl.replace(/\/+$/, "")}${path}`;
65 +
66 +/** Sends a request and decodes a 2xx JSON body; anything else becomes a readable error. */
67 +const sendJson = Effect.fn("TextGenerator.sendJson")(function* <S extends Schema.Top>(
68 + label: string,
69 + request: HttpClientRequest.HttpClientRequest,
70 + schema: S,
71 +) {
72 + const http = yield* HttpClient.HttpClient;
73 + const response: HttpClientResponse.HttpClientResponse = yield* http.execute(request).pipe(
74 + // A redirect could carry the key to another origin.
75 + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }),
76 + Effect.provideService(HttpClient.TracerPropagationEnabled, false),
77 + Effect.mapError(
78 + (cause) =>
79 + new TextGeneratorRequestError({
80 + detail: `Couldn't reach ${label}. Check the base URL and your connection.`,
81 + cause,
82 + }),
83 + ),
84 + );
85 + const body = yield* response.json.pipe(Effect.orElseSucceed((): unknown => undefined));
86 + if (response.status < 200 || response.status >= 300) {
87 + const message = decodeApiErrorBody(body).pipe((option) =>
88 + option._tag === "Some" ? option.value.error.message : undefined,
89 + );
90 + return yield* new TextGeneratorRequestError({
91 + detail: describeStatus(label, response.status, message),
92 + });
93 + }
94 + return yield* Schema.decodeUnknownEffect(schema)(body).pipe(
95 + Effect.mapError(
96 + (cause) =>
97 + new TextGeneratorRequestError({
98 + detail: `${label} returned a reply T3 Code couldn't read.`,
99 + cause,
100 + }),
101 + ),
102 + );
103 +});
104 +
105 +const withTimeout =
106 + (label: string, duration: typeof GENERATE_TIMEOUT | typeof LIST_MODELS_TIMEOUT) =>
107 + <A, R>(effect: Effect.Effect<A, TextGeneratorRequestError, R>) =>
108 + effect.pipe(
109 + Effect.timeoutOrElse({
110 + duration,
111 + orElse: () =>
112 + Effect.fail(
113 + new TextGeneratorRequestError({ detail: `${label} took too long to respond.` }),
114 + ),
115 + }),
116 + );
117 +
118 +const sortModels = (models: Iterable<TextGeneratorModel>) =>
119 + [...models].sort((left, right) => left.id.localeCompare(right.id));
120 +
121 +const readModel = (entry: { readonly id: string; readonly name?: string | undefined }) => {
122 + const id = entry.id.trim();
123 + return id ? { id, name: entry.name?.trim() || id } : undefined;
124 +};
125 +
126 +const ChatCompletion = Schema.Struct({
127 + choices: Schema.Array(
128 + Schema.Struct({
129 + finish_reason: Schema.NullOr(Schema.String),
130 + message: Schema.Struct({ content: Schema.NullOr(Schema.String) }),
131 + }),
132 + ),
133 +});
134 +const OpenAIModelList = Schema.Struct({
135 + data: Schema.Array(Schema.Struct({ id: Schema.String, name: Schema.optional(Schema.String) })),
136 +});
137 +
138 +const openAICompatible: TextGeneratorDriver = {
139 + kind: "openaiCompatible",
140 + generate: (connection, model, prompt) => {
141 + const { label } = connection;
142 + let request = HttpClientRequest.post(endpoint(connection, "/chat/completions")).pipe(
143 + HttpClientRequest.bodyJsonUnsafe({ model, messages: [{ role: "user", content: prompt }] }),
144 + );
145 + if (connection.apiKey) request = HttpClientRequest.bearerToken(request, connection.apiKey);
146 + return sendJson(label, request, ChatCompletion).pipe(
147 + Effect.flatMap((completion) => {
148 + const choice = completion.choices[0];
149 + const text = choice?.message.content?.trim();
150 + if (choice?.finish_reason === "length") {
151 + return Effect.fail(
152 + new TextGeneratorRequestError({ detail: `${label} reached its output limit.` }),
153 + );
154 + }
155 + return text
156 + ? Effect.succeed(text)
157 + : Effect.fail(new TextGeneratorRequestError({ detail: `${label} returned no text.` }));
158 + }),
159 + withTimeout(label, GENERATE_TIMEOUT),
160 + );
161 + },
162 + listModels: (connection) => {
163 + const { label } = connection;
164 + let request = HttpClientRequest.get(endpoint(connection, "/models"));
165 + if (connection.apiKey) request = HttpClientRequest.bearerToken(request, connection.apiKey);
166 + return sendJson(label, request, OpenAIModelList).pipe(
167 + Effect.map((list) => sortModels(list.data.flatMap((entry) => readModel(entry) ?? []))),
168 + withTimeout(label, LIST_MODELS_TIMEOUT),
169 + );
170 + },
171 +};
172 +
173 +const ANTHROPIC_VERSION = "2023-06-01";
174 +const AnthropicMessage = Schema.Struct({
175 + stop_reason: Schema.NullOr(Schema.String),
176 + content: Schema.Array(
177 + Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) }),
178 + ),
179 +});
180 +const AnthropicModelPage = Schema.Struct({
181 + data: Schema.Array(
182 + Schema.Struct({ id: Schema.String, display_name: Schema.optional(Schema.String) }),
183 + ),
184 + has_more: Schema.optional(Schema.Boolean),
185 + last_id: Schema.optional(Schema.NullOr(Schema.String)),
186 +});
187 +
188 +const anthropicRequest = (request: HttpClientRequest.HttpClientRequest, apiKey: string) =>
189 + request.pipe(
190 + HttpClientRequest.setHeader("x-api-key", apiKey),
191 + HttpClientRequest.setHeader("anthropic-version", ANTHROPIC_VERSION),
192 + );
193 +
194 +const anthropic: TextGeneratorDriver = {
195 + kind: "anthropic",
196 + generate: (connection, model, prompt) => {
197 + const { label } = connection;
198 + const request = anthropicRequest(
199 + HttpClientRequest.post(endpoint(connection, "/messages")).pipe(
200 + HttpClientRequest.bodyJsonUnsafe({
201 + model,
202 + max_tokens: 8192,
203 + messages: [{ role: "user", content: prompt }],
204 + }),
205 + ),
206 + connection.apiKey,
207 + );
208 + return sendJson(label, request, AnthropicMessage).pipe(
209 + Effect.flatMap((message) => {
210 + if (message.stop_reason === "max_tokens") {
211 + return Effect.fail(
212 + new TextGeneratorRequestError({ detail: `${label} reached its output limit.` }),
213 + );
214 + }
215 + const text = message.content
216 + .flatMap((block) => (block.type === "text" && block.text ? [block.text] : []))
217 + .join("")
218 + .trim();
219 + return text
220 + ? Effect.succeed(text)
221 + : Effect.fail(new TextGeneratorRequestError({ detail: `${label} returned no text.` }));
222 + }),
223 + withTimeout(label, GENERATE_TIMEOUT),
224 + );
225 + },
226 + listModels: Effect.fn("TextGenerator.anthropic.listModels")(
227 + function* (connection) {
228 + const { label } = connection;
229 + const models = new Map<string, TextGeneratorModel>();
230 + let after: string | undefined;
231 + for (let page = 0; page < MAX_MODEL_PAGES; page++) {
232 + let request = HttpClientRequest.get(endpoint(connection, "/models")).pipe(
233 + HttpClientRequest.setUrlParam("limit", "1000"),
234 + );
235 + if (after) request = HttpClientRequest.setUrlParam(request, "after_id", after);
236 + const result = yield* sendJson(
237 + label,
238 + anthropicRequest(request, connection.apiKey),
239 + AnthropicModelPage,
240 + );
241 + for (const entry of result.data) {
242 + const model = readModel({ id: entry.id, name: entry.display_name });
243 + if (model) models.set(model.id, model);
244 + }
245 + if (!result.has_more || !result.last_id || result.last_id === after) break;
246 + after = result.last_id;
247 + }
248 + return sortModels(models.values());
249 + },
250 + (effect, connection) => effect.pipe(withTimeout(connection.label, LIST_MODELS_TIMEOUT)),
251 + ),
252 +};
253 +
254 +export const TEXT_GENERATOR_DRIVERS: Readonly<Record<TextGeneratorKind, TextGeneratorDriver>> = {
255 + openaiCompatible: openAICompatible,
256 + anthropic,
257 +};
apps/server/src/ws.test.ts
+2
@@ -121,6 +121,7 @@ import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";
121 import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
122 import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
123 import * as TriageService from "./triage/TriageService.ts";
124 +import * as TextGenerators from "./textGeneration/TextGenerators.ts";
125 import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
126 import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
127 import * as ServerConfigModule from "./config.ts";
@@ -769,6 +770,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
770 Layer.mock(WorkspacePaths.WorkspacePaths)({}),
771 Layer.mock(TraceDiagnostics.TraceDiagnostics)({}),
772 Layer.mock(TriageService.TriageService)({}),
773 + Layer.mock(TextGenerators.TextGenerators)({}),
774 Layer.mock(ProjectFaviconResolver.ProjectFaviconResolver)({}),
775 Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({}),
776 Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({}),
apps/server/src/ws.ts
+3
@@ -252,6 +252,7 @@ import * as SqlClient from "effect/sql/SqlClient";
252 import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
253 import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
254 import * as OtlpEndpointCheck from "./observability/OtlpEndpointCheck.ts";
255 +import * as TextGenerators from "./textGeneration/TextGenerators.ts";
256 import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
257 import * as SourceControlSignIn from "./sourceControl/SourceControlSignIn.ts";
258 import * as SourceControlBuiltInDrivers from "./sourceControl/builtInDrivers.ts";
@@ -1538,6 +1539,7 @@ export const layerWsRpc = (
1539 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
1540 const sourceControlDiscovery = yield* SourceControlDiscovery.SourceControlDiscovery;
1541 const otlpEndpointCheck = yield* OtlpEndpointCheck.OtlpEndpointCheck;
1542 + const textGenerators = yield* TextGenerators.TextGenerators;
1543 const sourceControlRepositories =
1544 yield* SourceControlRepositoryService.SourceControlRepositoryService;
1545 const sourceControlSignIn = yield* SourceControlSignIn.SourceControlSignIn;
@@ -2734,6 +2736,7 @@ export const layerWsRpc = (
2736 [WS_METHODS.serverRefreshUsageRates]: (_input) => usage.refreshRates,
2737 [WS_METHODS.serverRetryResourceTelemetry]: (_input) => resourceTelemetry.retry,
2738 [WS_METHODS.serverCheckOtlpEndpoint]: (input) => otlpEndpointCheck.check(input),
2739 + [WS_METHODS.serverListTextGeneratorModels]: (input) => textGenerators.listModels(input),
2740 [WS_METHODS.serverPrepareTriage]: (input) => triage.prepare(input),
2741 [WS_METHODS.serverSignalProcess]: (input) => processDiagnostics.signal(input),
2742 [WS_METHODS.serverReportClientActivity]: (input, metadata) =>
apps/web/src/components/Icons.tsx
+19
@@ -428,6 +428,25 @@ export const ClaudeAI: Icon = ({ className, ...props }) => (
428 </svg>
429 );
430
431 +// Brand marks from Simple Icons (CC0).
432 +export const OpenRouterIcon: Icon = ({ className, ...props }) => (
433 + <svg {...props} viewBox="0 0 24 24" className={cn("fill-current", className)}>
434 + <path d="M16.778 1.844v1.919q-.569-.026-1.138-.032-.708-.008-1.415.037c-1.93.126-4.023.728-6.149 2.237-2.911 2.066-2.731 1.95-4.14 2.75-.396.223-1.342.574-2.185.798-.841.225-1.753.333-1.751.333v4.229s.768.108 1.61.333c.842.224 1.789.575 2.185.799 1.41.798 1.228.683 4.14 2.75 2.126 1.509 4.22 2.11 6.148 2.236.88.058 1.716.041 2.555.005v1.918l7.222-4.168-7.222-4.17v2.176c-.86.038-1.611.065-2.278.021-1.364-.09-2.417-.357-3.979-1.465-2.244-1.593-2.866-2.027-3.68-2.508.889-.518 1.449-.906 3.822-2.59 1.56-1.109 2.614-1.377 3.978-1.466.667-.044 1.418-.017 2.278.02v2.176L24 6.014Z" />
435 + </svg>
436 +);
437 +
438 +export const OllamaIcon: Icon = ({ className, ...props }) => (
439 + <svg {...props} viewBox="0 0 24 24" className={cn("fill-current", className)}>
440 + <path d="M16.361 10.26a.894.894 0 0 0-.558.47l-.072.148.001.207c0 .193.004.217.059.353.076.193.152.312.291.448.24.238.51.3.872.205a.86.86 0 0 0 .517-.436.752.752 0 0 0 .08-.498c-.064-.453-.33-.782-.724-.897a1.06 1.06 0 0 0-.466 0zm-9.203.005c-.305.096-.533.32-.65.639a1.187 1.187 0 0 0-.06.52c.057.309.31.59.598.667.362.095.632.033.872-.205.14-.136.215-.255.291-.448.055-.136.059-.16.059-.353l.001-.207-.072-.148a.894.894 0 0 0-.565-.472 1.02 1.02 0 0 0-.474.007Zm4.184 2c-.131.071-.223.25-.195.383.031.143.157.288.353.407.105.063.112.072.117.136.004.038-.01.146-.029.243-.02.094-.036.194-.036.222.002.074.07.195.143.253.064.052.076.054.255.059.164.005.198.001.264-.03.169-.082.212-.234.15-.525-.052-.243-.042-.28.087-.355.137-.08.281-.219.324-.314a.365.365 0 0 0-.175-.48.394.394 0 0 0-.181-.033c-.126 0-.207.03-.355.124l-.085.053-.053-.032c-.219-.13-.259-.145-.391-.143a.396.396 0 0 0-.193.032zm.39-2.195c-.373.036-.475.05-.654.086-.291.06-.68.195-.951.328-.94.46-1.589 1.226-1.787 2.114-.04.176-.045.234-.045.53 0 .294.005.357.043.524.264 1.16 1.332 2.017 2.714 2.173.3.033 1.596.033 1.896 0 1.11-.125 2.064-.727 2.493-1.571.114-.226.169-.372.22-.602.039-.167.044-.23.044-.523 0-.297-.005-.355-.045-.531-.288-1.29-1.539-2.304-3.072-2.497a6.873 6.873 0 0 0-.855-.031zm.645.937a3.283 3.283 0 0 1 1.44.514c.223.148.537.458.671.662.166.251.26.508.303.82.02.143.01.251-.043.482-.08.345-.332.705-.672.957a3.115 3.115 0 0 1-.689.348c-.382.122-.632.144-1.525.138-.582-.006-.686-.01-.853-.042-.57-.107-1.022-.334-1.35-.68-.264-.28-.385-.535-.45-.946-.03-.192.025-.509.137-.776.136-.326.488-.73.836-.963.403-.269.934-.46 1.422-.512.187-.02.586-.02.773-.002zm-5.503-11a1.653 1.653 0 0 0-.683.298C5.617.74 5.173 1.666 4.985 2.819c-.07.436-.119 1.04-.119 1.503 0 .544.064 1.24.155 1.721.02.107.031.202.023.208a8.12 8.12 0 0 1-.187.152 5.324 5.324 0 0 0-.949 1.02 5.49 5.49 0 0 0-.94 2.339 6.625 6.625 0 0 0-.023 1.357c.091.78.325 1.438.727 2.04l.13.195-.037.064c-.269.452-.498 1.105-.605 1.732-.084.496-.095.629-.095 1.294 0 .67.009.803.088 1.266.095.555.288 1.143.503 1.534.071.128.243.393.264.407.007.003-.014.067-.046.141a7.405 7.405 0 0 0-.548 1.873c-.062.417-.071.552-.071.991 0 .56.031.832.148 1.279L3.42 24h1.478l-.05-.091c-.297-.552-.325-1.575-.068-2.597.117-.472.25-.819.498-1.296l.148-.29v-.177c0-.165-.003-.184-.057-.293a.915.915 0 0 0-.194-.25 1.74 1.74 0 0 1-.385-.543c-.424-.92-.506-2.286-.208-3.451.124-.486.329-.918.544-1.154a.787.787 0 0 0 .223-.531c0-.195-.07-.355-.224-.522a3.136 3.136 0 0 1-.817-1.729c-.14-.96.114-2.005.69-2.834.563-.814 1.353-1.336 2.237-1.475.199-.033.57-.028.776.01.226.04.367.028.512-.041.179-.085.268-.19.374-.431.093-.215.165-.333.36-.576.234-.29.46-.489.822-.729.413-.27.884-.467 1.352-.561.17-.035.25-.04.569-.04.319 0 .398.005.569.04a4.07 4.07 0 0 1 1.914.997c.117.109.398.457.488.602.034.057.095.177.132.267.105.241.195.346.374.43.14.068.286.082.503.045.343-.058.607-.053.943.016 1.144.23 2.14 1.173 2.581 2.437.385 1.108.276 2.267-.296 3.153-.097.15-.193.27-.333.419-.301.322-.301.722-.001 1.053.493.539.801 1.866.708 3.036-.062.772-.26 1.463-.533 1.854a2.096 2.096 0 0 1-.224.258.916.916 0 0 0-.194.25c-.054.109-.057.128-.057.293v.178l.148.29c.248.476.38.823.498 1.295.253 1.008.231 2.01-.059 2.581a.845.845 0 0 0-.044.098c0 .006.329.009.732.009h.73l.02-.074.036-.134c.019-.076.057-.3.088-.516.029-.217.029-1.016 0-1.258-.11-.875-.295-1.57-.597-2.226-.032-.074-.053-.138-.046-.141.008-.005.057-.074.108-.152.376-.569.607-1.284.724-2.228.031-.26.031-1.378 0-1.628-.083-.645-.182-1.082-.348-1.525a6.083 6.083 0 0 0-.329-.7l-.038-.064.131-.194c.402-.604.636-1.262.727-2.04a6.625 6.625 0 0 0-.024-1.358 5.512 5.512 0 0 0-.939-2.339 5.325 5.325 0 0 0-.95-1.02 8.097 8.097 0 0 1-.186-.152.692.692 0 0 1 .023-.208c.208-1.087.201-2.443-.017-3.503-.19-.924-.535-1.658-.98-2.082-.354-.338-.716-.482-1.15-.455-.996.059-1.8 1.205-2.116 3.01a6.805 6.805 0 0 0-.097.726c0 .036-.007.066-.015.066a.96.96 0 0 1-.149-.078A4.857 4.857 0 0 0 12 3.03c-.832 0-1.687.243-2.456.698a.958.958 0 0 1-.148.078c-.008 0-.015-.03-.015-.066a6.71 6.71 0 0 0-.097-.725C8.997 1.392 8.337.319 7.46.048a2.096 2.096 0 0 0-.585-.041Zm.293 1.402c.248.197.523.759.682 1.388.03.113.06.244.069.292.007.047.026.152.041.233.067.365.098.76.102 1.24l.002.475-.12.175-.118.178h-.278c-.324 0-.646.041-.954.124l-.238.06c-.033.007-.038-.003-.057-.144a8.438 8.438 0 0 1 .016-2.323c.124-.788.413-1.501.696-1.711.067-.05.079-.049.157.013zm9.825-.012c.17.126.358.46.498.888.28.854.36 2.028.212 3.145-.019.14-.024.151-.057.144l-.238-.06a3.693 3.693 0 0 0-.954-.124h-.278l-.119-.178-.119-.175.002-.474c.004-.669.066-1.19.214-1.772.157-.623.434-1.185.68-1.382.078-.062.09-.063.159-.012z" />
441 + </svg>
442 +);
443 +
444 +export const AnthropicIcon: Icon = ({ className, ...props }) => (
445 + <svg {...props} viewBox="0 0 24 24" className={cn("fill-current", className)}>
446 + <path d="M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z" />
447 + </svg>
448 +);
449 +
450 const ANTIGRAVITY_ICON_DATA_URL =
451 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAQAElEQVR4nOx9CbhsVXXmWvucqst7AmpQwDmoDUgQpTtGmcRIBEHhAwxEMRpCjEOa2NoK7/Hw02drGGSUJE3brdGOHe2gaaLSUdMmxAAyPhklpuOswYHG/sLorTp776z/X+vUvQY1DHeoe9/deqnp1Kl6tdZew7/+tU6StbVVryRra6teawqwla81BdjK15oCbOWrla1o3X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jPh/JUz8ty9ate+iVL2W4AyKBQBBmKAAABz0lEQVSW0qWD057nfv9gixSePJmEToDHyV2xuwPdE3cJ3t0agQcYSXLamvCXfm05Rd9uEnu5/d3Z22WvCdQJ5wKrBJWoTyMDKBKOpG/Lsdi9L07Fx7NUb1t1dy8e+TulI9yChPl3RbnN1OFlN67A6R2rZV23UT9h2/nfmuAv87qBOJtIHCGMUEDnEwqqxLQ9HpwONMc+eHwP5CT1qfUMAznQMtpXe2BHo0JR9LPjHw0OvX7jcNX18K20BULtlk36Ytu6bKmr4smZz6rsiVg1rrLugWENK15qeVxKRX4g/XV4Yh6v7/ZGYqaJxmQLDLIe2Sk2m8k/EXi1rK2pWYYavtekvI9J97oejO8zAwdjomYvfqFbTx7SDRbqDy7WCYQTbL15/Xq80p7DfFeUlF960ykzH5W1NZXrulP1lus26QtN4q83z30bc7ri81l6BNE7jv3aRqrj8ynoZ5157y8Vya+xgP9pHvmLD/RRvdmcyZaayiU3bVi/aDPr19bCr0MvqDO33yvHm7SfbfnBk+yppxqwvz2ajs0EXG253Xuu2UBrMbeeeXp9dE2jnUvN99y6cf23ZG2t+qWytrbq9fDbw9fWil5rCrCVrzUF2MrXPwMAAP//z9dnYQAAAAZJREFUAwCDZN+FnSK/OAAAAABJRU5ErkJggg==";
452
apps/web/src/components/chat/ProviderInstanceIcon.tsx
+44 -2
@@ -7,7 +7,15 @@ import {
7 } from "@t3tools/client-runtime/state/provider-instance-display";
8
9 import { ProviderDriverKind } from "@t3tools/contracts";
10 -import { AntigravityIcon, ClaudeAI, Icon, OpenAI } from "../Icons";
10 +import {
11 + AnthropicIcon,
12 + AntigravityIcon,
13 + ClaudeAI,
14 + Icon,
15 + OllamaIcon,
16 + OpenAI,
17 + OpenRouterIcon,
18 +} from "../Icons";
19
20 import { cn } from "~/lib/utils";
21 import { providerClients } from "../settings/providerDriverMeta";
@@ -22,12 +30,21 @@ const PROVIDER_ICON_BY_PROVIDER: Partial<Record<ProviderDriverKind, Icon>> = {
30 [ProviderDriverKind.make("codex")]: OpenAI,
31 [ProviderDriverKind.make("claudeAgent")]: ClaudeAI,
32 [ProviderDriverKind.make("antigravity")]: AntigravityIcon,
33 + // Text generators, by the service they reach (see textGeneratorBrand).
34 + [ProviderDriverKind.make("openai")]: OpenAI,
35 + [ProviderDriverKind.make("anthropic")]: AnthropicIcon,
36 + [ProviderDriverKind.make("openrouter")]: OpenRouterIcon,
37 + [ProviderDriverKind.make("ollama")]: OllamaIcon,
38 };
39
40 const PROVIDER_TEXT_COLOR_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
41 [ProviderDriverKind.make("codex")]: "text-black dark:text-white",
42 [ProviderDriverKind.make("claudeAgent")]: "text-[#d97757]",
43 [ProviderDriverKind.make("antigravity")]: "text-[#5b87bf]",
44 + [ProviderDriverKind.make("openai")]: "text-black dark:text-white",
45 + [ProviderDriverKind.make("anthropic")]: "text-black dark:text-white",
46 + [ProviderDriverKind.make("openrouter")]: "text-black dark:text-white",
47 + [ProviderDriverKind.make("ollama")]: "text-black dark:text-white",
48 };
49
50 export function providerTextColor(driverKind: ProviderDriverKind): {
@@ -84,6 +101,8 @@ export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: {
101 const badgeContent = props.badgeContent ?? "initials";
102 const iconClassName = cn(props.size === "compact" && "size-3.5", props.iconClassName);
103 const isAcpRegistry = props.driverKind === "acpRegistry";
104 + // A custom OpenAI-compatible endpoint has no brand: show its name, marked with the protocol.
105 + const isCustomEndpoint = props.driverKind === "openaiCompatible";
106 const acpRegistryIconUrl = resolveProviderInstanceAcpRegistryIconUrl({
107 driverKind: props.driverKind,
108 agentId: props.acpRegistryAgentId,
@@ -105,6 +124,29 @@ export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: {
124 fallbackClassName="size-full"
125 icon={acpRegistryIconUrl}
126 />
127 + ) : isCustomEndpoint ? (
128 + // The tile is a size container: below ~18px it keeps one letter and drops the mark.
129 + <span
130 + className={cn(
131 + "@container relative flex size-5 shrink-0 items-center justify-center rounded-md border bg-card text-4xs font-semibold leading-none text-foreground",
132 + iconClassName,
133 + )}
134 + aria-hidden
135 + >
136 + {Array.from(providerInstanceInitials(props.displayName))[0]}
137 + <span className="@max-[1.1rem]:hidden">
138 + {Array.from(providerInstanceInitials(props.displayName)).slice(1).join("")}
139 + </span>
140 + <span
141 + className={cn(
142 + "pointer-events-none absolute right-[-0.3125rem] bottom-[-0.3125rem] z-10 flex size-3 items-center justify-center rounded-full border bg-card text-foreground shadow-sm @max-[1.1rem]:hidden",
143 + props.badgeClassName,
144 + )}
145 + style={{ borderColor: indicatorBackground }}
146 + >
147 + <OpenAI className="size-2" />
148 + </span>
149 + </span>
150 ) : packageIcon ? (
151 <ProviderPackageIcon
152 icon={packageIcon}
@@ -118,7 +160,7 @@ export const ProviderInstanceIcon = memo(function ProviderInstanceIcon(props: {
160 {providerInstanceInitials(props.displayName)}
161 </span>
162 )}
121 - {props.showBadge ? (
163 + {isCustomEndpoint ? null : props.showBadge ? (
164 <span
165 className={cn(
166 "pointer-events-none absolute right-0 bottom-0 z-10 flex h-3.5 min-w-3.5 items-center justify-center rounded-full border px-0.5 text-4xs font-semibold leading-none shadow-sm",
apps/web/src/components/settings/ProviderSettingsPanel.tsx
+12
@@ -96,6 +96,7 @@ import { ExpandableText } from "./ExpandableText";
96 import { IntervalSecondsField } from "./IntervalSecondsField";
97 import { ProviderInstanceCard } from "./ProviderInstanceCard";
98 import { useSecretSources } from "./SecretSourceInput";
99 +import { TextGeneratorsSettings } from "./TextGeneratorsSettings";
100 import { UsageProviderSettings } from "./UsageProviderSettings";
101 import { ProviderSetupSection, readAntigravityAuthMethod } from "./ProviderSetupSection";
102 import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection";
@@ -1092,6 +1093,17 @@ export function EnvironmentProviderSettings({
1093 readOnly={readOnly}
1094 />
1095
1096 + {/* The server drops text generators under a provider allow-list. */}
1097 + {managedPolicy?.limits?.providers?.allowedDrivers === undefined ? (
1098 + <TextGeneratorsSettings
1099 + key={`text-generators:${environmentId}`}
1100 + environmentId={environmentId}
1101 + environmentLabel={environmentLabel}
1102 + providers={serverProviders}
1103 + readOnly={readOnly}
1104 + />
1105 + ) : null}
1106 +
1107 <SettingsSection title="Advanced">
1108 <SettingsRow
1109 id={searchableSetting("provider-health-check-interval").id}
apps/web/src/components/settings/SecretsSettings.logic.ts
+10
@@ -6,6 +6,7 @@ import {
6 secretReferencesInSettings,
7 type ServerSettings,
8 SimlockDeviceHostConfig,
9 + TextGeneratorConfig,
10 UsageLimitSourceConfig,
11 } from "@t3tools/contracts";
12 import { getProviderClient } from "@t3tools/client-runtime/provider-clients";
@@ -18,6 +19,7 @@ type SecretUseSettings = Pick<
19 | "providerInstances"
20 | "sourceControlHosts"
21 | "usageLimitSources"
22 + | "textGenerators"
23 | "easDeviceHosts"
24 | "simlockDeviceHosts"
25 | "cloudSpeechCredentials"
@@ -91,6 +93,14 @@ export function secretProviderUses(
93 source,
94 ),
95 ),
96 + ...Object.entries(settings.textGenerators).flatMap(([id, generator]) =>
97 + uses(
98 + { settingsSchema: TextGeneratorConfig },
99 + `text-generator:${id}`,
100 + generator.label ?? generator.baseUrl,
101 + generator,
102 + ),
103 + ),
104 ...settings.easDeviceHosts.flatMap((host) =>
105 uses({ settingsSchema: EasDeviceHostConfig }, `eas:${host.id}`, host.label, host),
106 ),
apps/web/src/components/settings/SettingsPanels.tsx
+11 -10
@@ -69,7 +69,7 @@ import {
69 resolveAppModelSelectionState,
70 selectsPlanAgent,
71 } from "../../modelSelection";
72 -import { providerInstanceEntriesFor } from "../../providerInstances";
72 +import { useTextGenerationTargets } from "../../textGenerators";
73 import { ensureLocalApi, readLocalApi } from "../../localApi";
74 import { isMacPlatform } from "../../lib/utils";
75 import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
@@ -1533,9 +1533,14 @@ export function ThreadsSettingsPanel() {
1533 (target) => target.serverConfig?.environment.capabilities.threadAutoSettlementScope === true,
1534 );
1535
1536 - const textGenerationProviders = serverProviders.filter(
1537 - (provider) => provider.supportsTextGeneration !== false,
1538 - );
1536 + const textGenerationTargets = useTextGenerationTargets({
1537 + environmentId,
1538 + settings,
1539 + providers: serverProviders.filter((provider) => provider.supportsTextGeneration !== false),
1540 + projectId: target?.projectId ?? null,
1541 + selections: [settings.textGenerationModelSelection],
1542 + });
1543 + const textGenerationProviders = textGenerationTargets.providers;
1544 const textGenerationModelSelection = resolveAppModelSelectionState(
1545 settings,
1546 textGenerationProviders,
@@ -1543,11 +1548,7 @@ export function ThreadsSettingsPanel() {
1548 const textGenInstanceId = textGenerationModelSelection.instanceId;
1549 const textGenModel = textGenerationModelSelection.model;
1550 const textGenModelOptions = textGenerationModelSelection.options;
1546 - const textGenerationModelInstanceEntries = providerInstanceEntriesFor(
1547 - textGenerationProviders,
1548 - settings,
1549 - target?.projectId ?? null,
1550 - );
1551 + const textGenerationModelInstanceEntries = textGenerationTargets.entries;
1552 const hasTextGenerationProvider = textGenerationModelInstanceEntries.some(
1553 (entry) => entry.enabled && entry.isAvailable,
1554 );
@@ -1780,7 +1781,7 @@ export function ThreadsSettingsPanel() {
1781 serverScoped
1782 settingKeys={["textGenerationModelSelection"]}
1783 {...searchableSetting("text-generation-model")}
1783 - description="Used for thread titles and other generated text on connected devices with this provider. Source control can override it."
1784 + description="For thread titles and other generated text. Source control has its own setting. Text generators from Providers also appear here."
1785 resetAction={
1786 hasServerTargets && isTextGenerationModelDirty ? (
1787 <SettingResetButton
apps/web/src/components/settings/SourceControlWritingSettings.tsx
+45 -24
@@ -1,9 +1,10 @@
1 import { useNavigate } from "@tanstack/react-router";
2 import { useRef, useState } from "react";
3 -import type {
4 - ProviderInstanceId,
5 - ServerSettings,
6 - SourceControlWritingStyleMode,
3 +import {
4 + type ProviderInstanceId,
5 + type ServerSettings,
6 + type SourceControlWritingStyleMode,
7 + textGeneratorForSelection,
8 } from "@t3tools/contracts";
9 import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
10 import { createModelSelection } from "@t3tools/shared/model";
@@ -20,6 +21,7 @@ import {
21 import { useScopedModelDisabledReason } from "./useScopedModelAvailability";
22 import { useSettingsScope } from "./SettingsScopeContext";
23 import { providerInstanceEntriesFor } from "../../providerInstances";
24 +import { useTextGenerationTargets } from "../../textGenerators";
25 import {
26 getCustomModelOptionsByInstance,
27 resolveAppModelSelectionState,
@@ -111,12 +113,21 @@ export function SourceControlWritingSettingsSection() {
113 settings,
114 target?.projectId ?? null,
115 );
116 + // Text generators may write source control text, but never review guides.
117 + const writerTargets = useTextGenerationTargets({
118 + environmentId,
119 + settings,
120 + providers: textGenerationProviders,
121 + projectId: target?.projectId ?? null,
122 + selections: [settings.sourceControlWriterModelSelection, settings.textGenerationModelSelection],
123 + });
124 + const writerEntries = writerTargets.entries;
125 const projectEnabledInstanceIds = new Set(
115 - instanceEntries
126 + writerEntries
127 .filter((entry) => entry.enabled && entry.isAvailable)
128 .map((entry) => entry.instanceId),
129 );
119 - const projectEffectiveTextGenerationProviders = textGenerationProviders.filter((provider) =>
130 + const projectEffectiveTextGenerationProviders = writerTargets.providers.filter((provider) =>
131 projectEnabledInstanceIds.has(provider.instanceId),
132 );
133 const defaultModelSelection = resolveAppModelSelectionState(
@@ -135,7 +146,7 @@ export function SourceControlWritingSettingsSection() {
146 },
147 projectEffectiveTextGenerationProviders,
148 );
138 - const canEnableDedicatedModel = instanceEntries.some(
149 + const canEnableDedicatedModel = writerEntries.some(
150 (entry) =>
151 entry.instanceId === defaultModelSelection.instanceId && entry.enabled && entry.isAvailable,
152 );
@@ -145,28 +156,38 @@ export function SourceControlWritingSettingsSection() {
156 activeSelection.instanceId,
157 activeSelection.model,
158 );
148 - const writerModelDisabledReason = useScopedModelDisabledReason(settings, instanceEntries);
149 - const writerInstanceEntry = instanceEntries.find(
159 + const writerModelDisabledReason = useScopedModelDisabledReason(settings, writerEntries);
160 + const writerInstanceEntry = writerEntries.find(
161 (entry) => entry.instanceId === activeSelection.instanceId,
162 );
163 const usesReviewGuideModel = settings.reviewGuideModelSelection !== null;
164 + // Resolve against agents this project can use, so the fallback never lands on one it turned off.
165 + const projectAgentProviders = textGenerationProviders.filter((provider) =>
166 + instanceEntries.some(
167 + (entry) => entry.instanceId === provider.instanceId && entry.enabled && entry.isAvailable,
168 + ),
169 + );
170 const reviewGuideSelection = resolveAppModelSelectionState(
171 {
172 ...settings,
173 textGenerationModelSelection: resolveReviewGuideModelSelection(
174 settings,
158 - textGenerationProviders,
175 + projectAgentProviders,
176 target?.projectId ?? null,
177 ),
178 },
162 - textGenerationProviders,
179 + projectAgentProviders,
180 );
181 const reviewGuideModelOptionsByInstance = getCustomModelOptionsByInstance(
182 settings,
166 - textGenerationProviders,
183 + projectAgentProviders,
184 reviewGuideSelection.instanceId,
185 reviewGuideSelection.model,
186 );
187 + const canEnableReviewGuideModel = instanceEntries.some(
188 + (entry) =>
189 + entry.instanceId === reviewGuideSelection.instanceId && entry.enabled && entry.isAvailable,
190 + );
191 const reviewGuideInstanceEntry = instanceEntries.find(
192 (entry) => entry.instanceId === reviewGuideSelection.instanceId,
193 );
@@ -312,7 +333,7 @@ export function SourceControlWritingSettingsSection() {
333 serverScoped
334 settingKeys={["reviewGuideModelSelection"]}
335 {...searchableSetting("review-guide-model")}
315 - description="Model that reads a pull request to write its review guide. It reads the change itself over many steps, so a stronger model helps. Off uses the source control writer model."
336 + description="Must be a coding agent: it reads the pull request over many steps. Off uses the writer model, or Codex or Claude if that model is a text generator."
337 control={
338 !hasServerTargets ? (
339 <span className="text-sm text-muted-foreground">
@@ -320,7 +341,7 @@ export function SourceControlWritingSettingsSection() {
341 </span>
342 ) : (
343 <div className="flex flex-wrap items-center justify-end gap-2">
323 - {(usesReviewGuideModel || mixedReviewGuideModel) && canEnableDedicatedModel ? (
344 + {(usesReviewGuideModel || mixedReviewGuideModel) && canEnableReviewGuideModel ? (
345 <ProviderModelPicker
346 environmentId={environmentId}
347 activeInstanceId={reviewGuideSelection.instanceId}
@@ -349,7 +370,7 @@ export function SourceControlWritingSettingsSection() {
370 />
371 ) : null}
372 {usesReviewGuideModel &&
352 - canEnableDedicatedModel &&
373 + canEnableReviewGuideModel &&
374 !mixedReviewGuideModel &&
375 reviewGuideInstanceEntry ? (
376 <TraitsPicker
@@ -374,16 +395,16 @@ export function SourceControlWritingSettingsSection() {
395 <Switch
396 mixed={mixedReviewGuideModel}
397 checked={mixedReviewGuideModel ? false : usesReviewGuideModel}
377 - disabled={!usesReviewGuideModel && !canEnableDedicatedModel}
398 + disabled={!usesReviewGuideModel && !canEnableReviewGuideModel}
399 onCheckedChange={(checked) => {
400 if (!checked) {
401 updateSettings({ reviewGuideModelSelection: null });
402 return;
403 }
383 - const reason = writerModelDisabledReason(
384 - activeSelection.instanceId,
385 - activeSelection.model,
386 - );
404 + const seed = textGeneratorForSelection(settings, activeSelection.instanceId)
405 + ? reviewGuideSelection
406 + : activeSelection;
407 + const reason = writerModelDisabledReason(seed.instanceId, seed.model);
408 if (reason) {
409 toastManager.add({
410 type: "error",
@@ -394,9 +415,9 @@ export function SourceControlWritingSettingsSection() {
415 }
416 updateSettings({
417 reviewGuideModelSelection: createModelSelection(
397 - activeSelection.instanceId,
398 - activeSelection.model,
399 - activeSelection.options,
418 + seed.instanceId,
419 + seed.model,
420 + seed.options,
421 ),
422 });
423 }}
@@ -515,7 +536,7 @@ export function SourceControlWritingSettingsSection() {
536 activeInstanceId={activeSelection.instanceId}
537 model={activeSelection.model}
538 lockedProvider={null}
518 - instanceEntries={instanceEntries}
539 + instanceEntries={writerEntries}
540 modelOptionsByInstance={modelOptionsByInstance}
541 triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
542 triggerAriaLabel="Source control writer model"
apps/web/src/components/settings/TextGeneratorsSettings.tsx new
+751
@@ -0,0 +1,751 @@
1 +import {
2 + type EnvironmentId,
3 + isSecretReference,
4 + type ProviderInstanceId,
5 + type SecretReference,
6 + type ServerProvider,
7 + TextGeneratorConfig,
8 + type TextGeneratorModel,
9 +} from "@t3tools/contracts";
10 +import { createModelSelection } from "@t3tools/shared/model";
11 +import { AsyncResult } from "effect/reactivity";
12 +import * as Option from "effect/Option";
13 +import * as Schema from "effect/Schema";
14 +import { CheckIcon, MoreVertical, PlusIcon, ServerIcon } from "lucide-react";
15 +import { useState } from "react";
16 +
17 +import { useEnvironmentSettings, useUpdateEnvironmentSettings } from "../../hooks/useSettings";
18 +import {
19 + checkTextGeneratorConfig,
20 + rereadTextGeneratorModels,
21 + nextTextGeneratorId,
22 + refreshTextGeneratorModels,
23 + testTextGeneratorModel,
24 + useTextGenerationTargets,
25 + useTextGeneratorModels,
26 + TEXT_GENERATOR_PRESETS,
27 + type TextGeneratorPreset,
28 + textGeneratorBrand,
29 + textGeneratorDisplayName,
30 +} from "../../textGenerators";
31 +import { getCustomModelOptionsByInstance } from "../../modelSelection";
32 +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon";
33 +import { ProviderModelPicker } from "../chat/ProviderModelPicker";
34 +import {
35 + AlertDialog,
36 + AlertDialogClose,
37 + AlertDialogDescription,
38 + AlertDialogFooter,
39 + AlertDialogHeader,
40 + AlertDialogPopup,
41 + AlertDialogTitle,
42 +} from "../ui/alert-dialog";
43 +import { Button } from "../ui/button";
44 +import { RefreshIcon } from "../ui/refresh-icon";
45 +import { toastManager } from "../ui/toast";
46 +import {
47 + Dialog,
48 + DialogDescription,
49 + DialogFooter,
50 + DialogHeader,
51 + DialogPanel,
52 + DialogPopup,
53 + DialogTitle,
54 +} from "../ui/dialog";
55 +import { Input } from "../ui/input";
56 +import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
57 +import { Label } from "../ui/label";
58 +import { Spinner } from "../ui/spinner";
59 +import { Switch } from "../ui/switch";
60 +import { WizardFooter, WizardHeader, WizardPanel, WizardPopup, WizardSteps } from "../ui/wizard";
61 +import { SecretSourceInput, useSecretSources } from "./SecretSourceInput";
62 +import { searchableSetting } from "./settingsSearch";
63 +import { SETTINGS_PICKER_TRIGGER_CLASSNAME, SettingsRow, SettingsSection } from "./settingsLayout";
64 +
65 +const decodeTextGenerator = Schema.decodeUnknownOption(TextGeneratorConfig);
66 +
67 +type Saved = { readonly id: ProviderInstanceId; readonly config: TextGeneratorConfig };
68 +type Editing = Saved | "new";
69 +
70 +/** Rows that list, add, edit, and remove one environment's text generators. */
71 +export function TextGeneratorsSettings({
72 + environmentId,
73 + environmentLabel,
74 + providers,
75 + readOnly,
76 +}: {
77 + readonly environmentId: EnvironmentId;
78 + readonly environmentLabel: string;
79 + readonly providers: ReadonlyArray<ServerProvider>;
80 + readonly readOnly: boolean;
81 +}) {
82 + const settings = useEnvironmentSettings(environmentId);
83 + const updateSettings = useUpdateEnvironmentSettings(environmentId);
84 + const [editing, setEditing] = useState<Editing | null>(null);
85 + const [removing, setRemoving] = useState<ProviderInstanceId | null>(null);
86 + const [viewing, setViewing] = useState<Saved | null>(null);
87 + const generators = Object.entries(settings.textGenerators) as Array<
88 + [ProviderInstanceId, TextGeneratorConfig]
89 + >;
90 + const removingConfig = removing === null ? undefined : settings.textGenerators[removing];
91 +
92 + return (
93 + <>
94 + <SettingsSection
95 + {...searchableSetting("text-generators")}
96 + headerAction={
97 + !readOnly ? (
98 + <Button size="xs" variant="outline" onClick={() => setEditing("new")}>
99 + <PlusIcon className="size-3" aria-hidden />
100 + Add generator
101 + </Button>
102 + ) : null
103 + }
104 + >
105 + {generators.length === 0 ? (
106 + <SettingsRow
107 + title="No text generators yet"
108 + description="Add a model API to write thread titles, commit messages, and other short text without starting a coding agent."
109 + />
110 + ) : null}
111 + {generators.map(([id, config]) => {
112 + const name = textGeneratorDisplayName(config);
113 + return (
114 + <SettingsRow
115 + key={id}
116 + title={
117 + <span className="inline-flex items-center gap-2.5">
118 + <ProviderInstanceIcon
119 + driverKind={textGeneratorBrand(config)}
120 + displayName={name}
121 + badgeContent="none"
122 + />
123 + {name}
124 + </span>
125 + }
126 + description={
127 + // Indented past the icon so it lines up with the name.
128 + <span className="block truncate ps-7.5">
129 + {config.enabled ? "" : "Off · "}
130 + {config.baseUrl.replace(/^https?:\/\//, "")}
131 + </span>
132 + }
133 + control={
134 + readOnly ? null : (
135 + <div className="flex items-center gap-2">
136 + <Menu>
137 + <MenuTrigger
138 + render={
139 + <Button
140 + size="icon-sm"
141 + variant="ghost-muted"
142 + aria-label={`More actions for ${name}`}
143 + />
144 + }
145 + >
146 + <MoreVertical />
147 + </MenuTrigger>
148 + <MenuPopup align="end">
149 + <MenuItem onClick={() => setEditing({ id, config })}>Edit</MenuItem>
150 + <MenuItem
151 + disabled={!config.enabled}
152 + onClick={() => setViewing({ id, config })}
153 + >
154 + Show models
155 + </MenuItem>
156 + <MenuItem variant="destructive" onClick={() => setRemoving(id)}>
157 + Remove
158 + </MenuItem>
159 + </MenuPopup>
160 + </Menu>
161 + <Switch
162 + checked={config.enabled}
163 + onCheckedChange={(enabled) =>
164 + updateSettings({ textGenerators: { [id]: { ...config, enabled } } })
165 + }
166 + aria-label={`Enable ${name}`}
167 + />
168 + </div>
169 + )
170 + }
171 + />
172 + );
173 + })}
174 + </SettingsSection>
175 + {editing !== null ? (
176 + <TextGeneratorWizard
177 + environmentId={environmentId}
178 + editing={editing}
179 + providers={providers}
180 + onClose={() => setEditing(null)}
181 + onSave={(id, config) =>
182 + updateSettings(
183 + { textGenerators: { [id]: config } },
184 + { onSaved: () => rereadTextGeneratorModels(environmentId, id) },
185 + )
186 + }
187 + newId={(preset) => nextTextGeneratorId(preset.id, settings, providers)}
188 + />
189 + ) : null}
190 + {viewing !== null ? (
191 + <TextGeneratorModelsDialog
192 + environmentId={environmentId}
193 + saved={viewing}
194 + onClose={() => setViewing(null)}
195 + />
196 + ) : null}
197 + <AlertDialog
198 + open={removingConfig !== undefined}
199 + onOpenChange={(open) => {
200 + if (!open) setRemoving(null);
201 + }}
202 + >
203 + <AlertDialogPopup>
204 + <AlertDialogHeader>
205 + <AlertDialogTitle>
206 + Remove {removingConfig ? textGeneratorDisplayName(removingConfig) : ""}?
207 + </AlertDialogTitle>
208 + <AlertDialogDescription>
209 + This deletes the API key stored on {environmentLabel}. Anything set to use this
210 + generator falls back to the text generation model.
211 + </AlertDialogDescription>
212 + </AlertDialogHeader>
213 + <AlertDialogFooter>
214 + <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
215 + <Button
216 + variant="destructive"
217 + onClick={() => {
218 + if (removing !== null) updateSettings({ textGenerators: { [removing]: null } });
219 + setRemoving(null);
220 + }}
221 + >
222 + Remove
223 + </Button>
224 + </AlertDialogFooter>
225 + </AlertDialogPopup>
226 + </AlertDialog>
227 + </>
228 + );
229 +}
230 +
231 +const STEPS = ["Connect", "Use it"] as const;
232 +
233 +/** Text tasks a generator can write, in the order the settings pages show them. */
234 +const TASKS = [
235 + { key: "textGenerationModelSelection", label: "Thread titles and other generated text" },
236 + {
237 + key: "sourceControlWriterModelSelection",
238 + label: "Commit messages, pull requests, and branch names",
239 + },
240 + { key: "speechPostProcessingModelSelection", label: "Voice transcript cleanup" },
241 +] as const;
242 +
243 +/**
244 + * Connect checks the settings by listing the service's models and saves the generator; Use it then
245 + * shows each text task's model picker, so any of them can switch to it. The key goes once to the
246 + * environment's secret storage; settings keep only a redaction marker.
247 + */
248 +function TextGeneratorWizard({
249 + environmentId,
250 + editing,
251 + providers,
252 + onClose,
253 + onSave,
254 + newId,
255 +}: {
256 + readonly environmentId: EnvironmentId;
257 + readonly editing: Editing;
258 + readonly providers: ReadonlyArray<ServerProvider>;
259 + readonly onClose: () => void;
260 + readonly onSave: (id: ProviderInstanceId, config: TextGeneratorConfig) => void;
261 + readonly newId: (preset: TextGeneratorPreset) => ProviderInstanceId;
262 +}) {
263 + const existing = editing === "new" ? null : editing.config;
264 + const [step, setStep] = useState(0);
265 + const [preset, setPreset] = useState(TEXT_GENERATOR_PRESETS[0]!);
266 + const [baseUrl, setBaseUrl] = useState(existing?.baseUrl ?? preset.baseUrl);
267 + const [label, setLabel] = useState(existing?.label ?? "");
268 + const secretSources = useSecretSources(environmentId);
269 + const [keyDraft, setKeyDraft] = useState<string | SecretReference>(
270 + isSecretReference(existing?.apiKey) ? existing.apiKey : "",
271 + );
272 + const [keyValid, setKeyValid] = useState(true);
273 + const [checking, setChecking] = useState(false);
274 + const [checkError, setCheckError] = useState<string | null>(null);
275 + const [modelCount, setModelCount] = useState(0);
276 + // Fixed once saved, so editing the form again after Back updates the same generator.
277 + const [savedId, setSavedId] = useState<ProviderInstanceId | null>(
278 + editing === "new" ? null : editing.id,
279 + );
280 +
281 + // A saved literal key arrives redacted; sending the marker back keeps it.
282 + const storedKey = typeof existing?.apiKey === "string" ? existing.apiKey : "";
283 + const apiKey = typeof keyDraft === "string" ? keyDraft.trim() || storedKey : keyDraft;
284 + const kind = existing?.kind ?? preset.kind;
285 + const config = decodeTextGenerator({
286 + kind,
287 + ...(label.trim() ? { label: label.trim() } : {}),
288 + baseUrl: baseUrl.trim(),
289 + apiKey,
290 + enabled: existing?.enabled ?? true,
291 + });
292 + const keyRequired = existing === null && preset.id !== "custom";
293 + // Presets know their URL; only a custom endpoint, or one already saved as such, asks for it.
294 + const showBaseUrl =
295 + existing === null
296 + ? preset.id === "custom"
297 + : !["openai", "anthropic", "openrouter"].includes(textGeneratorBrand(existing));
298 + const canConnect = keyValid && Option.isSome(config) && (!keyRequired || apiKey !== "");
299 + const name = Option.isSome(config) ? textGeneratorDisplayName(config.value) : preset.label;
300 +
301 + const connect = async () => {
302 + if (!canConnect || checking) return;
303 + const id = savedId ?? newId(preset);
304 + setChecking(true);
305 + setCheckError(null);
306 + // The form is disabled while this runs, so the checked config is the one saved below.
307 + const result = await checkTextGeneratorConfig(environmentId, id, config.value);
308 + setChecking(false);
309 + if ("error" in result) {
310 + setCheckError(result.error);
311 + return;
312 + }
313 + onSave(id, config.value);
314 + setSavedId(id);
315 + setModelCount(result.models.length);
316 + setStep(1);
317 + };
318 +
319 + return (
320 + <Dialog
321 + open
322 + onOpenChange={(open) => {
323 + if (!open) onClose();
324 + }}
325 + >
326 + <WizardPopup>
327 + <WizardHeader
328 + title={existing ? `Edit ${textGeneratorDisplayName(existing)}` : "Add a text generator"}
329 + description="Writes thread titles, commit messages, and other short text without starting a coding agent. Your API key is stored on this environment."
330 + >
331 + <WizardSteps
332 + steps={STEPS}
333 + currentStep={step}
334 + isStepDisabled={(index) => index > step}
335 + onStepChange={setStep}
336 + />
337 + </WizardHeader>
338 + <WizardPanel>
339 + {step === 0 ? (
340 + <form
341 + className="grid gap-4"
342 + onSubmit={(event) => {
343 + event.preventDefault();
344 + void connect();
345 + }}
346 + >
347 + <fieldset disabled={checking} className="contents">
348 + {existing === null ? (
349 + <div className="grid gap-1.5">
350 + <span className="text-sm font-medium">Service</span>
351 + <div
352 + role="radiogroup"
353 + aria-label="Service"
354 + className="grid grid-cols-2 gap-2 sm:grid-cols-4"
355 + >
356 + {TEXT_GENERATOR_PRESETS.map((candidate) => {
357 + const selected = candidate.id === preset.id;
358 + return (
359 + <button
360 + key={candidate.id}
361 + type="button"
362 + role="radio"
363 + aria-checked={selected}
364 + className={
365 + selected
366 + ? "flex flex-col items-center gap-2 rounded-lg border border-primary bg-primary/5 px-2 py-3 text-sm font-medium text-foreground ring-1 ring-primary ring-inset outline-none focus-visible:ring-2 focus-visible:ring-inset"
367 + : "flex flex-col items-center gap-2 rounded-lg border bg-background px-2 py-3 text-sm text-muted-foreground outline-none hover:bg-accent/50 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"
368 + }
369 + onClick={() => {
370 + setPreset(candidate);
371 + setBaseUrl(candidate.baseUrl);
372 + setCheckError(null);
373 + }}
374 + >
375 + {candidate.id === "custom" ? (
376 + <ServerIcon className="size-5" aria-hidden />
377 + ) : (
378 + <ProviderInstanceIcon
379 + driverKind={textGeneratorBrand(candidate)}
380 + displayName={candidate.label}
381 + badgeContent="none"
382 + />
383 + )}
384 + {candidate.id === "custom" ? "Custom" : candidate.label}
385 + </button>
386 + );
387 + })}
388 + </div>
389 + </div>
390 + ) : null}
391 + {showBaseUrl ? (
392 + <div className="grid gap-1.5">
393 + <Label htmlFor="text-generator-url">Base URL</Label>
394 + <Input
395 + id="text-generator-url"
396 + placeholder="http://localhost:11434/v1"
397 + value={baseUrl}
398 + onChange={(event) => {
399 + setBaseUrl(event.target.value);
400 + setCheckError(null);
401 + }}
402 + spellCheck={false}
403 + autoFocus={existing === null && preset.id === "custom"}
404 + />
405 + </div>
406 + ) : null}
407 + <div className="grid gap-1.5">
408 + <Label htmlFor="text-generator-key">
409 + {keyRequired ? "API key" : "API key (optional)"}
410 + </Label>
411 + <SecretSourceInput
412 + id="text-generator-key"
413 + aria-label="API key"
414 + value={keyDraft}
415 + configured={storedKey !== ""}
416 + sources={secretSources}
417 + onChange={(event) => {
418 + setKeyDraft(event.target.value);
419 + setCheckError(null);
420 + }}
421 + onSecretChange={(secret) => setKeyDraft(secret ?? "")}
422 + autoFocus={existing === null && preset.id !== "custom"}
423 + onValidityChange={setKeyValid}
424 + />
425 + </div>
426 + <div className="grid gap-1.5">
427 + <Label htmlFor="text-generator-label">Name (optional)</Label>
428 + <Input
429 + id="text-generator-label"
430 + placeholder={
431 + existing !== null
432 + ? textGeneratorDisplayName(existing)
433 + : preset.id === "custom"
434 + ? "e.g. My local model"
435 + : preset.label
436 + }
437 + value={label}
438 + onChange={(event) => setLabel(event.target.value)}
439 + />
440 + </div>
441 + {checkError ? (
442 + <p role="alert" className="text-sm text-destructive">
443 + {checkError}
444 + </p>
445 + ) : null}
446 + </fieldset>
447 + </form>
448 + ) : (
449 + <div className="grid gap-4">
450 + <p className="text-sm text-muted-foreground">
451 + {name} is connected and lists {modelCount} {modelCount === 1 ? "model" : "models"}.
452 + Switch any of these to it, or keep what they use now.
453 + </p>
454 + {/* One grid for all rows, so pickers and Test buttons line up in columns. */}
455 + <div className="grid grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-x-2 gap-y-4">
456 + {TASKS.map((task) => (
457 + <TextGenerationTaskPicker
458 + key={task.key}
459 + environmentId={environmentId}
460 + providers={providers}
461 + settingKey={task.key}
462 + label={task.label}
463 + />
464 + ))}
465 + </div>
466 + </div>
467 + )}
468 + </WizardPanel>
469 + <WizardFooter
470 + leading={
471 + step > 0 ? (
472 + <Button variant="ghost" onClick={() => setStep(0)}>
473 + Back
474 + </Button>
475 + ) : null
476 + }
477 + >
478 + {step === 0 ? (
479 + <>
480 + <Button variant="outline" onClick={onClose}>
481 + Cancel
482 + </Button>
483 + <Button onClick={() => void connect()} disabled={!canConnect || checking}>
484 + {checking ? <Spinner /> : null}
485 + {checking ? "Connecting" : existing ? "Save and continue" : "Connect"}
486 + </Button>
487 + </>
488 + ) : (
489 + // Connect's button unmounts here; without this, focus lands on the step list.
490 + <Button autoFocus onClick={onClose}>
491 + Done
492 + </Button>
493 + )}
494 + </WizardFooter>
495 + </WizardPopup>
496 + </Dialog>
497 + );
498 +}
499 +
500 +/** One text task's model, saved as it changes, with every text generation target to pick from. */
501 +function TextGenerationTaskPicker({
502 + environmentId,
503 + providers,
504 + settingKey,
505 + label,
506 +}: {
507 + readonly environmentId: EnvironmentId;
508 + readonly providers: ReadonlyArray<ServerProvider>;
509 + readonly settingKey: (typeof TASKS)[number]["key"];
510 + readonly label: string;
511 +}) {
512 + const settings = useEnvironmentSettings(environmentId);
513 + const updateSettings = useUpdateEnvironmentSettings(environmentId);
514 + const own = settings[settingKey];
515 + // Source control and voice follow the text generation model until they get their own.
516 + const selection = own ?? settings.textGenerationModelSelection;
517 + const targets = useTextGenerationTargets({
518 + environmentId,
519 + settings,
520 + providers: providers.filter((provider) => provider.supportsTextGeneration !== false),
521 + projectId: null,
522 + selections: [selection],
523 + });
524 + // Only a text generator's model can be tried cheaply; agents start a whole session.
525 + const testable = Object.hasOwn(settings.textGenerators, selection.instanceId);
526 + const testKey = `${selection.instanceId}:${selection.model}`;
527 + const [testing, setTesting] = useState(false);
528 + const [result, setResult] = useState<{
529 + readonly key: string;
530 + readonly error: string | null;
531 + } | null>(null);
532 + const shown = result?.key === testKey ? result : null;
533 + const test = async () => {
534 + setTesting(true);
535 + const error = await testTextGeneratorModel(
536 + environmentId,
537 + selection.instanceId,
538 + selection.model,
539 + );
540 + setTesting(false);
541 + setResult({ key: testKey, error });
542 + };
543 + return (
544 + <>
545 + <div className="grid min-w-0 gap-0.5 pe-2">
546 + <span className="text-sm">{label}</span>
547 + {shown?.error ? (
548 + <span role="alert" className="text-xs text-destructive">
549 + {shown.error}
550 + </span>
551 + ) : shown ? (
552 + <span role="status" className="text-xs text-muted-foreground">
553 + {selection.model} answered. It works.
554 + </span>
555 + ) : own === null ? (
556 + <span className="text-xs text-muted-foreground">Follows the text generation model</span>
557 + ) : null}
558 + </div>
559 + <div className="justify-self-end">
560 + <ProviderModelPicker
561 + environmentId={environmentId}
562 + activeInstanceId={selection.instanceId}
563 + model={selection.model}
564 + lockedProvider={null}
565 + instanceEntries={targets.entries}
566 + modelOptionsByInstance={getCustomModelOptionsByInstance(
567 + settings,
568 + targets.providers,
569 + selection.instanceId,
570 + selection.model,
571 + )}
572 + triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
573 + onInstanceModelChange={(instanceId, model) =>
574 + updateSettings({ [settingKey]: createModelSelection(instanceId, model) })
575 + }
576 + />
577 + </div>
578 + <div className="justify-self-end">
579 + {testable ? (
580 + <Button
581 + size="xs"
582 + variant="outline"
583 + aria-busy={testing}
584 + disabled={testing}
585 + onClick={() => void test()}
586 + >
587 + {/* Keeps the label's width while testing, so the row never reflows. */}
588 + <span className="relative">
589 + <span className={testing ? "invisible" : undefined}>Test</span>
590 + {testing ? (
591 + <span className="absolute inset-0 flex items-center justify-center">
592 + <Spinner />
593 + </span>
594 + ) : null}
595 + </span>
596 + </Button>
597 + ) : null}
598 + </div>
599 + </>
600 + );
601 +}
602 +
603 +/** Searchable models; selectable when `onSelect` is given. */
604 +function TextGeneratorModelList({
605 + models,
606 + selected,
607 + onSelect,
608 +}: {
609 + readonly models: ReadonlyArray<TextGeneratorModel>;
610 + readonly selected?: string | null;
611 + readonly onSelect?: (id: string) => void;
612 +}) {
613 + const [query, setQuery] = useState("");
614 + const needle = query.trim().toLowerCase();
615 + const shown = needle
616 + ? models.filter(
617 + (model) =>
618 + model.id.toLowerCase().includes(needle) || model.name.toLowerCase().includes(needle),
619 + )
620 + : models;
621 + return (
622 + <div className="grid gap-2">
623 + {models.length > 8 ? (
624 + <Input
625 + type="search"
626 + placeholder="Search models"
627 + aria-label="Search models"
628 + autoFocus
629 + value={query}
630 + onChange={(event) => setQuery(event.target.value)}
631 + />
632 + ) : null}
633 + <div className="max-h-80 overflow-y-auto rounded-lg border divide-y divide-border/60">
634 + {shown.length === 0 ? (
635 + <p className="px-3 py-2 text-sm text-muted-foreground">No models match.</p>
636 + ) : (
637 + <ul role={onSelect ? "listbox" : "list"} aria-label="Models">
638 + {shown.map((model) => {
639 + const isSelected = model.id === selected;
640 + const label = (
641 + <>
642 + <span className="grid min-w-0 flex-1">
643 + <span className="truncate">{model.name}</span>
644 + {model.name !== model.id ? (
645 + <span className="truncate font-mono text-xs text-muted-foreground">
646 + {model.id}
647 + </span>
648 + ) : null}
649 + </span>
650 + {isSelected ? <CheckIcon className="size-4 shrink-0 text-primary" /> : null}
651 + </>
652 + );
653 + return (
654 + <li
655 + key={model.id}
656 + role={onSelect ? "option" : undefined}
657 + aria-selected={onSelect ? isSelected : undefined}
658 + >
659 + {onSelect ? (
660 + <button
661 + type="button"
662 + className="flex w-full items-center gap-2 px-3 py-2 text-left text-sm hover:bg-accent focus-visible:bg-accent focus-visible:outline-none"
663 + onClick={() => onSelect(model.id)}
664 + >
665 + {label}
666 + </button>
667 + ) : (
668 + <div className="flex items-center gap-2 px-3 py-2 text-sm">{label}</div>
669 + )}
670 + </li>
671 + );
672 + })}
673 + </ul>
674 + )}
675 + </div>
676 + </div>
677 + );
678 +}
679 +
680 +/** A saved generator's models, with a refresh that asks the API again. */
681 +function TextGeneratorModelsDialog({
682 + environmentId,
683 + saved,
684 + onClose,
685 +}: {
686 + readonly environmentId: EnvironmentId;
687 + readonly saved: Saved;
688 + readonly onClose: () => void;
689 +}) {
690 + const name = textGeneratorDisplayName(saved.config);
691 + const result = useTextGeneratorModels(environmentId, saved.id, saved.config);
692 + const [refreshing, setRefreshing] = useState(false);
693 + const refresh = async () => {
694 + setRefreshing(true);
695 + const outcome = await refreshTextGeneratorModels(environmentId, saved.id);
696 + setRefreshing(false);
697 + if ("error" in outcome) {
698 + toastManager.add({
699 + type: "error",
700 + title: `Couldn't load ${name} models`,
701 + description: outcome.error,
702 + });
703 + }
704 + };
705 + const models = AsyncResult.isSuccess(result) ? result.value : null;
706 + const error = Option.getOrUndefined(AsyncResult.error(result));
707 + return (
708 + <Dialog
709 + open
710 + onOpenChange={(open) => {
711 + if (!open) onClose();
712 + }}
713 + >
714 + <DialogPopup className="max-w-md">
715 + <DialogHeader>
716 + <DialogTitle>{name} models</DialogTitle>
717 + <DialogDescription>
718 + {models === null
719 + ? error
720 + ? "The model list couldn't load."
721 + : "Loading the model list."
722 + : `${models.length} ${models.length === 1 ? "model" : "models"} available. Pick one in a text generation model picker.`}
723 + </DialogDescription>
724 + </DialogHeader>
725 + <DialogPanel>
726 + {error ? (
727 + <p role="alert" className="text-sm text-destructive">
728 + {error}
729 + </p>
730 + ) : models === null ? (
731 + <Spinner tone="muted" />
732 + ) : (
733 + <TextGeneratorModelList models={models} />
734 + )}
735 + </DialogPanel>
736 + <DialogFooter variant="bare">
737 + <Button
738 + variant="outline"
739 + aria-busy={refreshing}
740 + disabled={refreshing}
741 + onClick={() => void refresh()}
742 + >
743 + <RefreshIcon refreshing={refreshing} />
744 + Refresh
745 + </Button>
746 + <Button onClick={onClose}>Done</Button>
747 + </DialogFooter>
748 + </DialogPopup>
749 + </Dialog>
750 + );
751 +}
apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx
+1 -1
@@ -399,7 +399,7 @@ it.each([
399 .element(screen.getByRole("combobox", { name: "Transcribe with" }))
400 .toHaveTextContent("Off");
401 await expect
402 - .element(screen.getByRole("switch", { name: "Clean up transcripts with a provider" }))
402 + .element(screen.getByRole("switch", { name: "Clean up transcripts" }))
403 .not.toBeChecked();
404 },
405 );
apps/web/src/components/settings/VoiceSettingsPanel.tsx
+65 -47
@@ -59,7 +59,7 @@ import {
59 getCustomModelOptionsByInstance,
60 resolveAppModelSelectionState,
61 } from "../../modelSelection";
62 -import { providerInstanceEntriesFor } from "../../providerInstances";
62 +import { useTextGenerationTargets } from "../../textGenerators";
63 import { useEnvironmentProviders, useEnvironments } from "../../state/environments";
64 import { useEnvironmentScope } from "../../state/session";
65 import { EMPTY_SERVER_PROVIDERS } from "../../state/server";
@@ -110,7 +110,6 @@ import { filterSpeechModels, type SpeechModelSort } from "./speechModelBrowser";
110 import { AdvancedSettings } from "./AdvancedSettings";
111 import {
112 SETTINGS_PICKER_TRIGGER_CLASSNAME,
113 - SettingResetButton,
113 SettingsPageContainer,
114 SettingsRow,
115 SettingsSearchTarget,
@@ -461,10 +460,18 @@ function CleanupModelRow() {
460 (environment?.serverConfig
461 ? providersByEnvironment.get(environment.environmentId)
462 : undefined) ?? EMPTY_SERVER_PROVIDERS;
464 - const textGenerationProviders = providers.filter(
465 - (provider) => provider.supportsTextGeneration !== false,
466 - );
467 - const instanceEntries = providerInstanceEntriesFor(textGenerationProviders, settings, null);
463 + const targets = useTextGenerationTargets({
464 + environmentId: environment?.environmentId ?? null,
465 + settings,
466 + providers: providers.filter((provider) => provider.supportsTextGeneration !== false),
467 + projectId: null,
468 + selections: [
469 + settings.speechPostProcessingModelSelection,
470 + settings.textGenerationModelSelection,
471 + ],
472 + });
473 + const textGenerationProviders = targets.providers;
474 + const instanceEntries = targets.entries;
475 const hasProvider = instanceEntries.some((entry) => entry.enabled && entry.isAvailable);
476 const dedicated = settings.speechPostProcessingModelSelection !== null;
477 const selection = resolveAppModelSelectionState(
@@ -499,49 +506,60 @@ function CleanupModelRow() {
506 settingKeys={["speechPostProcessingModelSelection"]}
507 {...searchableSetting("speech-post-processing-model")}
508 title="Cleanup model"
502 - description={
503 - dedicated
504 - ? `Drafts on ${environment?.label ?? "this environment"} use this model for cleanup instead of the environment’s text generation model.`
505 - : `Cleanup currently uses the text generation model on ${environment?.label ?? "this environment"}. Pick another model if you want a cheaper or faster one.`
506 - }
507 - resetAction={
508 - dedicated ? (
509 - <SettingResetButton
510 - label="cleanup model"
511 - onClick={() => updateSettings({ speechPostProcessingModelSelection: null })}
512 - />
513 - ) : null
514 - }
509 + description="Model for transcript cleanup, such as a cheaper or faster one. When disabled, use the text generation model configured for this environment."
510 control={
511 connectedEnvironments.length === 0 ? (
512 <span className="text-sm text-muted-foreground">Connect an environment first.</span>
518 - ) : !hasProvider || !instanceEntry ? (
519 - <span className="text-sm text-muted-foreground">No providers available.</span>
513 ) : (
521 - <div className="flex min-w-0 flex-wrap items-center justify-end gap-1.5">
522 - <ProviderModelPicker
523 - environmentId={environment?.environmentId ?? null}
524 - activeInstanceId={selection.instanceId}
525 - model={selection.model}
526 - lockedProvider={null}
527 - instanceEntries={instanceEntries}
528 - modelOptionsByInstance={modelOptionsByInstance}
529 - triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
530 - getModelDisabledReason={modelDisabledReason}
531 - onInstanceModelChange={(instanceId, model) =>
532 - setModel(createModelSelection(instanceId, model))
533 - }
534 - />
535 - <TraitsPicker
536 - provider={instanceEntry.driverKind}
537 - models={instanceEntry.models}
538 - model={selection.model}
539 - modelOptions={selection.options ?? []}
540 - allowPromptInjectedEffort={false}
541 - triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
542 - onModelOptionsChange={(options) =>
543 - setModel(createModelSelection(selection.instanceId, selection.model, options))
514 + <div className="flex min-w-0 flex-wrap items-center justify-end gap-2">
515 + {dedicated && (!hasProvider || !instanceEntry) ? (
516 + <span className="text-sm text-muted-foreground">
517 + No text generation providers available.
518 + </span>
519 + ) : null}
520 + {dedicated && hasProvider && instanceEntry ? (
521 + <>
522 + <ProviderModelPicker
523 + environmentId={environment?.environmentId ?? null}
524 + activeInstanceId={selection.instanceId}
525 + model={selection.model}
526 + lockedProvider={null}
527 + instanceEntries={instanceEntries}
528 + modelOptionsByInstance={modelOptionsByInstance}
529 + triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
530 + getModelDisabledReason={modelDisabledReason}
531 + onInstanceModelChange={(instanceId, model) =>
532 + setModel(createModelSelection(instanceId, model))
533 + }
534 + />
535 + <TraitsPicker
536 + provider={instanceEntry.driverKind}
537 + models={instanceEntry.models}
538 + model={selection.model}
539 + modelOptions={selection.options ?? []}
540 + allowPromptInjectedEffort={false}
541 + triggerClassName={SETTINGS_PICKER_TRIGGER_CLASSNAME}
542 + onModelOptionsChange={(options) =>
543 + setModel(createModelSelection(selection.instanceId, selection.model, options))
544 + }
545 + />
546 + </>
547 + ) : null}
548 + <Switch
549 + checked={dedicated}
550 + disabled={!dedicated && !hasProvider}
551 + onCheckedChange={(checked) =>
552 + updateSettings({
553 + speechPostProcessingModelSelection: checked
554 + ? createModelSelection(
555 + settings.textGenerationModelSelection.instanceId,
556 + settings.textGenerationModelSelection.model,
557 + settings.textGenerationModelSelection.options,
558 + )
559 + : null,
560 + })
561 }
562 + aria-label="Use a separate cleanup model"
563 />
564 </div>
565 )
@@ -1525,11 +1543,11 @@ export function VoiceSettingsPanel() {
1543
1544 <SettingsSection id={searchableSetting("speech-post-processing").id} title="Cleanup">
1545 <SettingsRow
1528 - title="Clean up transcripts with a provider"
1529 - description="Sends the transcript and nearby draft text to the text generation provider on the draft’s environment to fix punctuation, numbers, and spoken corrections. Sends text only; off by default."
1546 + title="Clean up transcripts"
1547 + description="Fixes punctuation, numbers, and spoken corrections with the cleanup model on the draft’s environment. Sends the transcript and nearby draft text, never audio."
1548 control={
1549 <Switch
1532 - aria-label="Clean up transcripts with a provider"
1550 + aria-label="Clean up transcripts"
1551 checked={cleanupEnabled}
1552 onCheckedChange={chooseTranscriptCleanup}
1553 />
apps/web/src/components/settings/settingsSearch.ts
+17 -2
@@ -69,6 +69,7 @@ export interface SettingsSearchItem {
69 readonly managedTunnelOnly?: boolean;
70 readonly peerLinksOnly?: boolean;
71 readonly fastWorktreeCheckoutOnly?: boolean;
72 + readonly textGeneratorsOnly?: boolean;
73 readonly secondary?: boolean;
74 readonly requiresThreadAutoSettlement?: boolean;
75 }
@@ -84,6 +85,8 @@ export interface SettingsSearchAvailability {
85 readonly managedTunnelActive?: boolean;
86 readonly hasPeerLinkHost?: boolean;
87 readonly hasFastWorktreeCheckoutEnvironment?: boolean;
88 + /** An environment without a provider allow-list, which hides text generators. */
89 + readonly hasTextGeneratorsEnvironment?: boolean;
90 }
91
92 export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
@@ -582,7 +585,7 @@ export const SETTINGS_SEARCH_ITEMS = [
585 },
586 {
587 id: "speech-post-processing",
585 - title: "Clean up transcripts with a provider",
588 + title: "Clean up transcripts",
589 to: "/settings/voice",
590 searchTerms: ["speech transcription polish clean provider prompt post-processing"],
591 },
@@ -941,6 +944,16 @@ export const SETTINGS_SEARCH_ITEMS = [
944 ],
945 providerSettingsOnly: true,
946 },
947 + {
948 + id: "text-generators",
949 + title: "Text generators",
950 + to: "/settings/providers",
951 + searchTerms: [
952 + "model api api key openai openrouter anthropic ollama lm studio custom endpoint base url thread titles commit messages",
953 + ],
954 + providerSettingsOnly: true,
955 + textGeneratorsOnly: true,
956 + },
957 {
958 id: "provider-health-check-interval",
959 title: "Health check interval",
@@ -1451,7 +1464,9 @@ export function filterAvailableSettingsSearchItems(
1464 (!item.requiresThreadAutoSettlement || availability.hasThreadAutoSettlement) &&
1465 (!item.managedTunnelOnly || availability.managedTunnelActive === true) &&
1466 (!item.peerLinksOnly || availability.hasPeerLinkHost === true) &&
1454 - (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true),
1467 + (!item.fastWorktreeCheckoutOnly ||
1468 + availability.hasFastWorktreeCheckoutEnvironment === true) &&
1469 + (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true),
1470 );
1471 }
1472
apps/web/src/components/settings/useAvailableSettingsSearchItems.ts
+7
@@ -35,6 +35,12 @@ export function useAvailableSettingsSearchItems() {
35 environment.connection.phase === "connected" &&
36 environment.serverConfig?.environment.capabilities.fastWorktreeCheckout === true,
37 ) === true;
38 + const hasTextGeneratorsEnvironment =
39 + environments.some(
40 + (environment) =>
41 + environment.serverConfig !== null &&
42 + environment.serverConfig.managedPolicy?.limits?.providers?.allowedDrivers === undefined,
43 + ) === true;
44 const hasThreadAutoSettlement =
45 getThreadAutoSettlementSearchAvailability(environments).eligibleEnvironmentIds.length > 0;
46 const primaryEnvironmentId = usePrimaryEnvironmentId();
@@ -65,5 +71,6 @@ export function useAvailableSettingsSearchItems() {
71 managedTunnelActive,
72 hasPeerLinkHost,
73 hasFastWorktreeCheckoutEnvironment,
74 + hasTextGeneratorsEnvironment,
75 });
76 }
apps/web/src/components/settings/useScopedModelAvailability.ts
+20 -2
@@ -1,4 +1,8 @@
1 -import type { ProviderInstanceId, UnifiedSettings } from "@t3tools/contracts";
1 +import {
2 + type ProviderInstanceId,
3 + textGeneratorForSelection,
4 + type UnifiedSettings,
5 +} from "@t3tools/contracts";
6
7 import { mergeEnvironmentSettings } from "../../hooks/useSettings";
8 import { getCustomModelOptionsByInstance } from "../../modelSelection";
@@ -19,10 +23,24 @@ export function useScopedModelDisabledReason(
23 const providersByEnvironment = useEnvironmentProviders();
24 return (instanceId: ProviderInstanceId, model: string): string | null => {
25 const sourceEntry = entries.find((entry) => entry.instanceId === instanceId);
26 + const shownGenerator = textGeneratorForSelection(settings, instanceId);
27 for (const candidate of targets) {
28 const environment = environments.find(
29 (entry) => entry.environmentId === candidate.environmentId,
30 );
31 + const unavailable = `This model is unavailable on ${environment?.label ?? "a selected environment"}. Select that environment to choose its model separately.`;
32 + const generator = textGeneratorForSelection(candidate.settings, instanceId);
33 + if (shownGenerator !== undefined || generator !== undefined) {
34 + // Only the shown environment's model list is loaded; elsewhere it must reach the same API.
35 + if (
36 + !generator?.enabled ||
37 + generator.kind !== shownGenerator?.kind ||
38 + generator.baseUrl !== shownGenerator.baseUrl
39 + ) {
40 + return unavailable;
41 + }
42 + continue;
43 + }
44 const providers = providersByEnvironment.get(candidate.environmentId);
45 if (!environment?.serverConfig || !providers) continue;
46 const entry = applyProviderInstanceSettings(
@@ -40,7 +58,7 @@ export function useScopedModelDisabledReason(
58 entry.driverKind !== sourceEntry?.driverKind ||
59 !options?.some((option) => option.slug === model && !option.isUnavailable)
60 ) {
43 - return `This model is unavailable on ${environment?.label ?? "a selected environment"}. Select that environment to choose its model separately.`;
61 + return unavailable;
62 }
63 }
64 return null;
apps/web/src/hooks/useSettings.ts
+10 -2
@@ -603,7 +603,7 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
603 const sharedSettingsSyncTargetIds = useSharedSettingsSyncTargetIds(true);
604 const updateSettings = (
605 patch: UnifiedSettingsPatch,
606 - options?: { readonly onFailed?: () => void },
606 + options?: { readonly onFailed?: () => void; readonly onSaved?: () => void },
607 ) => {
608 const { serverPatch, clientPatch } = splitPatch(patch);
609
@@ -636,7 +636,9 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
636 void persistServerSettings(
637 { environmentId, input: { patch: localPatch } },
638 options?.onFailed,
639 - );
639 + ).then((result) => {
640 + if (result._tag === "Success") options?.onSaved?.();
641 + });
642 } else {
643 warnUnsaved();
644 }
@@ -704,6 +706,12 @@ function useUpdateSettingsTarget(environmentId: EnvironmentId | null) {
706 `Could not save on ${label}: ${error instanceof Error ? error.message : "The save failed. Try reconnecting and saving again."}`,
707 ];
708 });
709 + if (
710 + deniedLabels.length === 0 &&
711 + outcomes.every(({ result }) => result._tag === "Success")
712 + ) {
713 + options?.onSaved?.();
714 + }
715 if (failures.length === 0) return;
716 const saved = outcomes
717 .filter(({ result }) => result._tag === "Success")
apps/web/src/textGenerators.test.ts new
+40
@@ -0,0 +1,40 @@
1 +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
2 +import { describe, expect, it } from "vite-plus/test";
3 +
4 +import { nextTextGeneratorId, textGeneratorBrand } from "./textGenerators";
5 +
6 +describe("nextTextGeneratorId", () => {
7 + it("skips ids that would make a selection name another target", () => {
8 + const settings = {
9 + providerInstances: {
10 + [ProviderInstanceId.make("openai")]: { driver: ProviderDriverKind.make("codex") },
11 + },
12 + textGenerators: {
13 + [ProviderInstanceId.make("openai-2")]: {
14 + kind: "openaiCompatible" as const,
15 + baseUrl: "https://api.openai.com/v1",
16 + apiKey: "",
17 + enabled: true,
18 + },
19 + },
20 + };
21 + const providers = [{ instanceId: ProviderInstanceId.make("openai-3") }];
22 +
23 + expect(nextTextGeneratorId("openai", settings, providers)).toBe("openai-4");
24 + // A driver's default instance id is taken even before it has a snapshot or config.
25 + expect(nextTextGeneratorId("cursor", settings, [])).toBe("cursor-2");
26 + expect(nextTextGeneratorId("openrouter", settings, providers)).toBe("openrouter");
27 + });
28 +});
29 +
30 +describe("textGeneratorBrand", () => {
31 + it.each([
32 + ["anthropic", "https://proxy.example/v1", "anthropic"],
33 + ["openaiCompatible", "https://openrouter.ai/api/v1", "openrouter"],
34 + ["openaiCompatible", "https://api.openai.com/v1", "openai"],
35 + ["openaiCompatible", "http://localhost:11434/v1", "ollama"],
36 + ["openaiCompatible", "http://localhost:1234/v1", "openaiCompatible"],
37 + ] as const)("%s at %s shows the %s icon", (kind, baseUrl, brand) => {
38 + expect(textGeneratorBrand({ kind, baseUrl })).toBe(brand);
39 + });
40 +});
apps/web/src/textGenerators.ts new
+336
@@ -0,0 +1,336 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { providerClients } from "@t3tools/client-runtime/provider-clients";
3 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
4 +import {
5 + type EnvironmentId,
6 + type ModelSelection,
7 + type ProjectId,
8 + ProviderDriverKind,
9 + ProviderInstanceId,
10 + type ServerProvider,
11 + type ServerProviderModel,
12 + type ServerSettings,
13 + type TextGeneratorConfig,
14 + type TextGeneratorKind,
15 + type TextGeneratorModel,
16 +} from "@t3tools/contracts";
17 +import * as Effect from "effect/Effect";
18 +import * as Option from "effect/Option";
19 +import { AsyncResult, Atom } from "effect/reactivity";
20 +
21 +import {
22 + deriveProviderInstanceEntries,
23 + type ProviderInstanceEntry,
24 + providerInstanceEntriesFor,
25 +} from "./providerInstances";
26 +import { appAtomRegistry } from "./rpc/atomRegistry";
27 +import { formatEnvironmentQueryError } from "./state/query";
28 +import { serverEnvironment } from "./state/server";
29 +
30 +export interface TextGeneratorPreset {
31 + readonly id: "openai" | "openrouter" | "anthropic" | "custom";
32 + readonly label: string;
33 + readonly kind: TextGeneratorKind;
34 + /** Empty for a custom server, whose URL the user enters. */
35 + readonly baseUrl: string;
36 +}
37 +
38 +export const TEXT_GENERATOR_PRESETS: ReadonlyArray<TextGeneratorPreset> = [
39 + { id: "openai", label: "OpenAI", kind: "openaiCompatible", baseUrl: "https://api.openai.com/v1" },
40 + {
41 + id: "openrouter",
42 + label: "OpenRouter",
43 + kind: "openaiCompatible",
44 + baseUrl: "https://openrouter.ai/api/v1",
45 + },
46 + {
47 + id: "anthropic",
48 + label: "Anthropic",
49 + kind: "anthropic",
50 + baseUrl: "https://api.anthropic.com/v1",
51 + },
52 + { id: "custom", label: "Custom (OpenAI-compatible)", kind: "openaiCompatible", baseUrl: "" },
53 +];
54 +
55 +export function textGeneratorDisplayName(config: TextGeneratorConfig): string {
56 + if (config.label) return config.label;
57 + const preset = TEXT_GENERATOR_PRESETS.find(
58 + (candidate) => candidate.baseUrl === config.baseUrl && candidate.kind === config.kind,
59 + );
60 + if (preset) return preset.label;
61 + try {
62 + return new URL(config.baseUrl).host;
63 + } catch {
64 + return config.baseUrl;
65 + }
66 +}
67 +
68 +/**
69 + * The service a text generator reaches, which picks its picker icon. It stands in for the driver
70 + * kind in picker entries only, so generators of one service share an icon and get instance badges.
71 + */
72 +export function textGeneratorBrand(config: Pick<TextGeneratorConfig, "kind" | "baseUrl">) {
73 + if (config.kind === "anthropic") return ProviderDriverKind.make("anthropic");
74 + let url: URL | null = null;
75 + try {
76 + url = new URL(config.baseUrl);
77 + } catch {}
78 + const host = url?.hostname ?? "";
79 + if (host === "openrouter.ai" || host.endsWith(".openrouter.ai")) {
80 + return ProviderDriverKind.make("openrouter");
81 + }
82 + if (host === "api.openai.com") return ProviderDriverKind.make("openai");
83 + if (url?.port === "11434" || host.includes("ollama")) return ProviderDriverKind.make("ollama");
84 + return ProviderDriverKind.make("openaiCompatible");
85 +}
86 +
87 +/**
88 + * A new text generator id. Selections name a text generator by the same id as a provider
89 + * instance, so it must not match a configured instance, a driver's default instance, or
90 + * another text generator.
91 + */
92 +export function nextTextGeneratorId(
93 + base: string,
94 + settings: Pick<ServerSettings, "providerInstances" | "textGenerators">,
95 + providers: ReadonlyArray<Pick<ServerProvider, "instanceId">>,
96 +): ProviderInstanceId {
97 + const taken = new Set<string>([
98 + ...Object.keys(settings.providerInstances),
99 + ...Object.keys(settings.textGenerators),
100 + ...providers.map((provider) => provider.instanceId),
101 + ...providerClients.definitions.map((definition) => definition.driverKind),
102 + ]);
103 + let id = base;
104 + for (let suffix = 2; taken.has(id); suffix += 1) {
105 + id = `${base}-${suffix}`;
106 + }
107 + return ProviderInstanceId.make(id);
108 +}
109 +
110 +type ModelsKey = readonly [
111 + environmentId: EnvironmentId,
112 + id: ProviderInstanceId,
113 + // The connection settings, so editing them asks again instead of reusing a stale list.
114 + kind: TextGeneratorKind,
115 + baseUrl: string,
116 + apiKey: TextGeneratorConfig["apiKey"],
117 +];
118 +
119 +const refreshCountAtom = Atom.family((key: string) =>
120 + Atom.make(0).pipe(Atom.keepAlive, Atom.withLabel(`text-generator-refresh:${key}`)),
121 +);
122 +
123 +const textGeneratorModelsAtom = Atom.family((key: string) => {
124 + const [environmentId, id] = JSON.parse(key) as ModelsKey;
125 + return Atom.make((get) => {
126 + // Read again after a refresh; the server's cache already holds the new list by then.
127 + get(refreshCountAtom(`${environmentId}:${id}`));
128 + return Effect.promise(() =>
129 + runAtomCommand(
130 + get.registry,
131 + serverEnvironment.listTextGeneratorModels,
132 + { environmentId, input: { id } },
133 + { reportFailure: false },
134 + ),
135 + ).pipe(
136 + Effect.flatMap((result) =>
137 + result._tag === "Success"
138 + ? Effect.succeed(result.value.models)
139 + : Effect.fail(formatEnvironmentQueryError(result.cause)),
140 + ),
141 + );
142 + }).pipe(Atom.setIdleTTL(5 * 60_000), Atom.withLabel(`text-generator-models:${key}`));
143 +});
144 +
145 +const textGeneratorCatalogAtom = Atom.family((keys: string) =>
146 + Atom.make((get) =>
147 + (JSON.parse(keys) as ReadonlyArray<string>).map((key) => get(textGeneratorModelsAtom(key))),
148 + ).pipe(Atom.withLabel(`text-generator-catalog:${keys}`)),
149 +);
150 +
151 +/**
152 + * Has open pickers ask the server again. Needed after a saved key changes: clients only see the
153 + * redaction marker, so the cache key does not change with it.
154 + */
155 +export function rereadTextGeneratorModels(environmentId: EnvironmentId, id: ProviderInstanceId) {
156 + const atom = refreshCountAtom(`${environmentId}:${id}`);
157 + appAtomRegistry.set(atom, appAtomRegistry.get(atom) + 1);
158 +}
159 +
160 +/**
161 + * Asks the API for its model list again, skipping the server's cache, then has open pickers
162 + * read it. Resolves to the model count, or the error to show.
163 + */
164 +export async function refreshTextGeneratorModels(
165 + environmentId: EnvironmentId,
166 + id: ProviderInstanceId,
167 +): Promise<{ readonly count: number } | { readonly error: string }> {
168 + const result = await runAtomCommand(
169 + appAtomRegistry,
170 + serverEnvironment.listTextGeneratorModels,
171 + { environmentId, input: { id, refresh: true } },
172 + { reportFailure: false },
173 + );
174 + rereadTextGeneratorModels(environmentId, id);
175 + return result._tag === "Success"
176 + ? { count: result.value.models.length }
177 + : { error: formatEnvironmentQueryError(result.cause) };
178 +}
179 +
180 +/** Lists the models unsaved settings reach, to check them before saving. */
181 +export async function checkTextGeneratorConfig(
182 + environmentId: EnvironmentId,
183 + id: ProviderInstanceId,
184 + config: TextGeneratorConfig,
185 +): Promise<{ readonly models: ReadonlyArray<TextGeneratorModel> } | { readonly error: string }> {
186 + const result = await runAtomCommand(
187 + appAtomRegistry,
188 + serverEnvironment.listTextGeneratorModels,
189 + { environmentId, input: { id, config } },
190 + { reportFailure: false },
191 + );
192 + return result._tag === "Success"
193 + ? { models: result.value.models }
194 + : { error: formatEnvironmentQueryError(result.cause) };
195 +}
196 +
197 +/**
198 + * Has a saved generator's model answer a tiny prompt. Some APIs list models without checking the
199 + * key, so only this proves the key, endpoint, and model together. Resolves to the error, if any.
200 + */
201 +export async function testTextGeneratorModel(
202 + environmentId: EnvironmentId,
203 + id: ProviderInstanceId,
204 + model: string,
205 +): Promise<string | null> {
206 + const result = await runAtomCommand(
207 + appAtomRegistry,
208 + serverEnvironment.listTextGeneratorModels,
209 + { environmentId, input: { id, test: true, model } },
210 + { reportFailure: false },
211 + );
212 + return result._tag === "Success" ? null : formatEnvironmentQueryError(result.cause);
213 +}
214 +
215 +/** A saved text generator's model list, shared with the pickers. */
216 +export function useTextGeneratorModels(
217 + environmentId: EnvironmentId,
218 + id: ProviderInstanceId,
219 + config: TextGeneratorConfig,
220 +): AsyncResult.AsyncResult<ReadonlyArray<TextGeneratorModel>, string> {
221 + return useAtomValue(
222 + textGeneratorModelsAtom(
223 + JSON.stringify([
224 + environmentId,
225 + id,
226 + config.kind,
227 + config.baseUrl,
228 + config.apiKey,
229 + ] satisfies ModelsKey),
230 + ),
231 + );
232 +}
233 +
234 +function toProviderModel(model: TextGeneratorModel): ServerProviderModel {
235 + return { slug: model.id, name: model.name, isCustom: false, capabilities: null };
236 +}
237 +
238 +/** Picker stand-in for a text generator. It never leaves the settings pickers. */
239 +function textGeneratorSnapshot(
240 + id: ProviderInstanceId,
241 + config: TextGeneratorConfig,
242 + result: AsyncResult.AsyncResult<ReadonlyArray<TextGeneratorModel>, string>,
243 + selectedModels: ReadonlyArray<string>,
244 +): ServerProvider {
245 + const discovered = AsyncResult.isSuccess(result) ? result.value.map(toProviderModel) : [];
246 + const missing = [...new Set(selectedModels)]
247 + .filter((slug) => !discovered.some((model) => model.slug === slug))
248 + .map((slug): ServerProviderModel => ({
249 + slug,
250 + name: slug,
251 + isCustom: false,
252 + capabilities: null,
253 + }));
254 + const failure = Option.getOrUndefined(AsyncResult.error(result));
255 + return {
256 + instanceId: id,
257 + driver: textGeneratorBrand(config),
258 + displayName: textGeneratorDisplayName(config),
259 + supportsTextGeneration: true,
260 + enabled: config.enabled,
261 + installed: true,
262 + version: null,
263 + status: failure === undefined ? "ready" : "error",
264 + ...(failure === undefined ? {} : { message: failure }),
265 + auth: { status: "unknown" },
266 + checkedAt: new Date(0).toISOString(),
267 + models: [...discovered, ...missing],
268 + slashCommands: [],
269 + skills: [],
270 + };
271 +}
272 +
273 +/**
274 + * The environment's text generation providers plus its enabled text generators, for the pickers
275 + * that may write text. Text generators replace a provider instance with the same id, as the
276 + * server does. Selections listed in `selections` keep their model while the list loads.
277 + */
278 +export function useTextGenerationTargets(input: {
279 + readonly environmentId: EnvironmentId | null;
280 + readonly settings: Pick<
281 + ServerSettings,
282 + "providerInstances" | "projectSettingsOverrides" | "textGenerators"
283 + >;
284 + readonly providers: ReadonlyArray<ServerProvider>;
285 + readonly projectId: ProjectId | null;
286 + readonly selections: ReadonlyArray<ModelSelection | null | undefined>;
287 +}): {
288 + readonly providers: ReadonlyArray<ServerProvider>;
289 + readonly entries: ReadonlyArray<ProviderInstanceEntry>;
290 +} {
291 + const { environmentId, settings } = input;
292 + const generators =
293 + environmentId === null
294 + ? []
295 + : (
296 + Object.entries(settings.textGenerators) as Array<
297 + [ProviderInstanceId, TextGeneratorConfig]
298 + >
299 + )
300 + .filter(([, config]) => config.enabled)
301 + .map(([id, config]) => ({
302 + id,
303 + config,
304 + key: JSON.stringify([
305 + environmentId,
306 + id,
307 + config.kind,
308 + config.baseUrl,
309 + config.apiKey,
310 + ] satisfies ModelsKey),
311 + }));
312 + const results = useAtomValue(
313 + textGeneratorCatalogAtom(JSON.stringify(generators.map((generator) => generator.key))),
314 + );
315 + const generatorProviders = generators.map(({ id, config }, index) =>
316 + textGeneratorSnapshot(
317 + id,
318 + config,
319 + results[index] ?? AsyncResult.initial(),
320 + input.selections.flatMap((selection) =>
321 + selection?.instanceId === id && selection.model ? [selection.model] : [],
322 + ),
323 + ),
324 + );
325 + const providers = input.providers.filter(
326 + (provider) => !Object.hasOwn(settings.textGenerators, provider.instanceId),
327 + );
328 + return {
329 + providers: [...providers, ...generatorProviders],
330 + // Project provider overrides do not apply to text generators, so their entries skip them.
331 + entries: [
332 + ...providerInstanceEntriesFor(providers, settings, input.projectId),
333 + ...deriveProviderInstanceEntries(generatorProviders),
334 + ],
335 + };
336 +}
docs/README.md
+1
@@ -12,6 +12,7 @@
12 - [Appearance and themes](./user/appearance.md)
13 - [Keyboard shortcuts](./user/keybindings.md)
14 - [Voice input](./user/voice-input.md)
15 +- [Text generation models](./user/text-generation.md)
16 - [SnapShots](./user/snap-shot.md)
17 - [Visual replies](./user/html-renders.md)
18 - [Import browser sessions](./user/browser-import.md)
docs/internals/glossary.md
+2
@@ -36,6 +36,8 @@ Terms whose meaning matters across T3 Code. Architecture and lifecycle constrain
36 | Provider | The agent runtime T3 Code controls, such as Codex or Claude Code. |
37 | Driver | The integration for a provider kind. |
38 | Provider instance | One configured provider, with its own settings and lifecycle. Multiple instances can use the same driver. |
39 +| Text generation | App-owned one-shot writing, such as thread titles, commit messages, and transcript cleanup. |
40 +| Text generator | A model API used only for text generation. Its id fills a model selection; agent surfaces never list it. |
41 | Adapter | The boundary translating a provider's native protocol into T3 Code operations and events. |
42 | Session | The provider runtime attached to a thread. A session can be stopped and resumed without deleting the thread. |
43 | Runtime mode | The thread's permission policy. See [permission modes](../user/permission-modes.md). |
docs/internals/voice-input.md
+2 -2
@@ -35,8 +35,8 @@ test captures separately for local playback and sends nothing. The transport
35 refuses redirects so credentials and audio cannot follow one to another host.
36
37 Transcript cleanup requires its own grant, off by default.
38 -It sends text, never audio, to the text generation provider of the draft's
39 -own environment, because that is where the provider credentials live.
38 +It sends text, never audio, to the text generation model of the draft's
39 +own environment, because that is where its credentials live.
40
41 A cloud destination binds both the forwarding environment and the named provider.
42 It uses a separate, batch-only endpoint: changing a server key cannot upgrade
docs/user/text-generation.md new
+42
@@ -0,0 +1,42 @@
1 +# Text generation models
2 +
3 +T3 Code writes some text for you: thread titles, commit messages, pull request titles and
4 +descriptions, branch names, and voice transcript cleanup. Pick the model for this in
5 +**Settings → Threads → Text generation model**. **Settings → Source control** and
6 +**Settings → Voice** can each pick a different one.
7 +
8 +By default, a coding agent such as Codex or Claude writes this text, starting a session for each
9 +request. A **text generator** — a model API that only writes text — is usually faster and cheaper.
10 +
11 +## Add a text generator
12 +
13 +Go to **Settings → Providers → Text generators** and choose **Add generator**:
14 +
15 +- **OpenAI** or **Anthropic** — enter an API key.
16 +- **OpenRouter** — enter an OpenRouter key to use any model it serves.
17 +- **Custom (OpenAI-compatible)** — enter the base URL of any other endpoint, such as Ollama at
18 + `http://localhost:11434/v1` or LM Studio. Local endpoints usually need no key. The environment's
19 + server makes the requests, so on a remote environment `localhost` means that machine, not yours.
20 +
21 +Give it a name if you add more than one from the same service. Your key is stored on the
22 +environment, like other [secrets](./secrets.md), and can come from a secret provider instead of
23 +being typed in.
24 +
25 +T3 Code lists the service's models to check the connection, then shows the model picker for each
26 +text task so you can switch any of them to the new generator, or keep what they use. **Test** next
27 +to a picker has the chosen model answer a tiny prompt, which proves the key works; some services
28 +list their models without checking it. **Show models** in the generator's menu lists its models
29 +and refreshes the list after the service adds some.
30 +
31 +Each request sends the API what the task needs, such as the staged diff for a commit message.
32 +
33 +Turning a generator off or removing it sends its work back to the environment's text generation
34 +model.
35 +
36 +## What text generators can't do
37 +
38 +Review guides read the checkout over many steps, so they always use a coding agent. If your source
39 +control writer model is a text generator, review guides use Codex or Claude instead, and fail if
40 +neither is set up. To choose which, pick one in **Settings → Source control → Review guide model**.
41 +
42 +A [managed policy](./managed-policy.md) that limits providers also turns off text generators.
docs/user/voice-input.md
+6 -5
@@ -109,20 +109,21 @@ are down, and **Toggle** always needs a second press. Change the chord itself in
109 Language and these preferences travel with each recording to the chosen
110 environment; nothing else about the project is sent.
111
112 -## Clean up transcripts with a provider
112 +## Clean up transcripts
113
114 **Transcript cleanup** is a separate choice and is off by default. When on, the
115 finished transcript and up to 1,024 characters each from before, inside, and
116 -after your selection are sent to the
117 -text generation provider configured on the draft's environment, which fixes
118 -punctuation, numbers, and spoken corrections such as "make it 42, sorry, 24".
119 -Depending on the provider, that can involve an external service. Audio is never
116 +after your selection are sent to the cleanup model on the draft's environment,
117 +which fixes punctuation, numbers, and spoken corrections such as "make it 42,
118 +sorry, 24". Depending on the model, that can involve an external service. Audio is never
119 sent to it. Use the built-in instructions or write your own, press **Skip**
120 while cleanup runs to insert the raw transcript, and if cleanup fails the raw
121 transcript is inserted.
122
123 Cleanup uses the environment's text generation model unless you pick a
124 **Cleanup model** for that environment, for example a cheaper or faster one.
125 +It can be a text generator instead of a coding agent; see
126 +[text generation models](./text-generation.md).
127
128 If cleanup misses the way you correct yourself, set a **Correction cue**: the
129 word or phrase you say to flag a correction, such as "scratch that". Cleanup
packages/client-runtime/src/state/server.ts
+4
@@ -1614,6 +1614,10 @@ export function createServerEnvironmentAtoms<R, E>(
1614 label: "environment-data:server:check-otlp-endpoint",
1615 tag: WS_METHODS.serverCheckOtlpEndpoint,
1616 }),
1617 + listTextGeneratorModels: createEnvironmentRpcCommand(runtime, {
1618 + label: "environment-data:server:list-text-generator-models",
1619 + tag: WS_METHODS.serverListTextGeneratorModels,
1620 + }),
1621 retryResourceTelemetry: createEnvironmentRpcCommand(runtime, {
1622 label: "environment-data:server:retry-resource-telemetry",
1623 tag: WS_METHODS.serverRetryResourceTelemetry,
packages/contracts/src/clientRpcPermissions.ts
+2
@@ -25,6 +25,8 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
25 // Restarts the server, as an update does.
26 [WS_METHODS.serverReclaimDatabaseSpace]: AuthEnvironmentMaintainScope,
27 [WS_METHODS.serverCheckOtlpEndpoint]: AuthSettingsWriteScope,
28 + // Listing models spends the stored API key, so only those who can choose a model may.
29 + [WS_METHODS.serverListTextGeneratorModels]: AuthSettingsWriteScope,
30 [WS_METHODS.serverRefreshProviders]: AuthOrchestrationReadScope,
31 [WS_METHODS.pullRequestsRunAction]: AuthSourceControlWriteScope,
32 [WS_METHODS.pullRequestsUpdate]: AuthSourceControlWriteScope,
packages/contracts/src/rpc.ts
+11
@@ -362,6 +362,9 @@ import {
362 ServerSettings,
363 ServerSettingsError,
364 ServerSettingsPatch,
365 + ListTextGeneratorModelsInput,
366 + ListTextGeneratorModelsResult,
367 + TextGeneratorError,
368 } from "./settings.ts";
369 import {
370 ScheduledTaskDeleteInput,
@@ -538,6 +541,7 @@ export const WS_METHODS = {
541 serverGetResourceTelemetryHistory: "server.getResourceTelemetryHistory",
542 serverRetryResourceTelemetry: "server.retryResourceTelemetry",
543 serverCheckOtlpEndpoint: "server.checkOtlpEndpoint",
544 + serverListTextGeneratorModels: "server.listTextGeneratorModels",
545 serverPrepareTriage: "server.prepareTriage",
546 serverSignalProcess: "server.signalProcess",
547 serverReportClientActivity: "server.reportClientActivity",
@@ -973,6 +977,12 @@ const WsServerCheckOtlpEndpointRpc = Rpc.make(WS_METHODS.serverCheckOtlpEndpoint
977 error: EnvironmentAuthorizationError,
978 });
979
980 +const WsServerListTextGeneratorModelsRpc = Rpc.make(WS_METHODS.serverListTextGeneratorModels, {
981 + payload: ListTextGeneratorModelsInput,
982 + success: ListTextGeneratorModelsResult,
983 + error: Schema.Union([TextGeneratorError, EnvironmentAuthorizationError]),
984 +});
985 +
986 const WsServerPrepareTriageRpc = Rpc.make(WS_METHODS.serverPrepareTriage, {
987 payload: ServerPrepareTriageInput,
988 success: ServerPrepareTriageResult,
@@ -2104,6 +2114,7 @@ export const WsRpcGroup = RpcGroup.make(
2114 WsServerGetResourceTelemetryHistoryRpc,
2115 WsServerRetryResourceTelemetryRpc,
2116 WsServerCheckOtlpEndpointRpc,
2117 + WsServerListTextGeneratorModelsRpc,
2118 WsServerPrepareTriageRpc,
2119 WsServerGetUsageSummaryRpc,
2120 WsServerRefreshUsageRatesRpc,
packages/contracts/src/settings.ts
+98
@@ -915,6 +915,75 @@ export const UsageLimitSourceConfig = Schema.Struct({
915 });
916 export type UsageLimitSourceConfig = typeof UsageLimitSourceConfig.Type;
917
918 +export const TextGeneratorKind = Schema.Literals(["openaiCompatible", "anthropic"]);
919 +export type TextGeneratorKind = typeof TextGeneratorKind.Type;
920 +
921 +const TextGeneratorBaseUrl = TrimmedNonEmptyString.check(
922 + Schema.isMaxLength(2048),
923 + Schema.makeFilter((value) => {
924 + try {
925 + const url = new URL(value);
926 + return (
927 + (url.protocol === "http:" || url.protocol === "https:") &&
928 + !url.username &&
929 + !url.password &&
930 + !url.search &&
931 + !url.hash
932 + );
933 + } catch {
934 + return false;
935 + }
936 + }),
937 +);
938 +
939 +/** A model API that only generates text. Its key shares the id namespace with provider instances. */
940 +export const TextGeneratorConfig = Schema.Struct({
941 + kind: TextGeneratorKind,
942 + label: Schema.optional(TrimmedNonEmptyString),
943 + baseUrl: TextGeneratorBaseUrl,
944 + apiKey: SettingsSecretValue.pipe(Schema.withDecodingDefault(Effect.succeed("")), secretSetting),
945 + enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
946 +});
947 +export type TextGeneratorConfig = typeof TextGeneratorConfig.Type;
948 +
949 +export const TextGeneratorModel = Schema.Struct({
950 + id: TrimmedNonEmptyString,
951 + name: TrimmedNonEmptyString,
952 +});
953 +export type TextGeneratorModel = typeof TextGeneratorModel.Type;
954 +
955 +export const ListTextGeneratorModelsInput = Schema.Struct({
956 + id: ProviderInstanceId,
957 + /**
958 + * Unsaved settings to check before saving, such as from the add dialog. A redacted key keeps
959 + * the one saved under `id`.
960 + */
961 + config: Schema.optional(TextGeneratorConfig),
962 + /** Skip the server's cached list and ask the API again. */
963 + refresh: Schema.optional(Schema.Boolean),
964 + /** Also have a model answer a tiny prompt, which proves the key, endpoint, and model. */
965 + test: Schema.optional(Schema.Boolean),
966 + /** With `test`, the model to try; a cheap listed one when omitted. */
967 + model: Schema.optional(TrimmedNonEmptyString),
968 +});
969 +export type ListTextGeneratorModelsInput = typeof ListTextGeneratorModelsInput.Type;
970 +
971 +export const ListTextGeneratorModelsResult = Schema.Struct({
972 + models: Schema.Array(TextGeneratorModel),
973 + /** The model that answered, when `test` was set. */
974 + testedModel: Schema.optional(TrimmedNonEmptyString),
975 +});
976 +export type ListTextGeneratorModelsResult = typeof ListTextGeneratorModelsResult.Type;
977 +
978 +export class TextGeneratorError extends Schema.TaggedError<TextGeneratorError>()(
979 + "TextGeneratorError",
980 + { detail: Schema.String },
981 +) {
982 + override get message(): string {
983 + return this.detail;
984 + }
985 +}
986 +
987 export const SecretProviderKind = SecretProviderSlug.pipe(Schema.brand("SecretProviderKind"));
988 export type SecretProviderKind = typeof SecretProviderKind.Type;
989
@@ -1464,6 +1533,9 @@ export const ServerSettings = Schema.Struct({
1533 usageLimitSources: Schema.Record(UsageLimitSourceId, UsageLimitSourceConfig).pipe(
1534 Schema.withDecodingDefault(Effect.succeed({})),
1535 ),
1536 + textGenerators: Schema.Record(ProviderInstanceId, TextGeneratorConfig).pipe(
1537 + Schema.withDecodingDefault(Effect.succeed({})),
1538 + ),
1539 secretProviders: Schema.Record(SecretProviderId, SecretProviderConfig).pipe(
1540 Schema.withDecodingDefault(Effect.succeed({})),
1541 ),
@@ -1536,6 +1608,27 @@ export const resolveProjectProviderInstanceEnabled = (
1608 : isUnconfiguredDefaultInstanceEnabled(instanceId);
1609 };
1610
1611 +/** The text generator a selection names, if any; it takes precedence over a provider instance. */
1612 +export const textGeneratorForSelection = (
1613 + settings: Pick<ServerSettings, "textGenerators">,
1614 + instanceId: ProviderInstanceId,
1615 +): TextGeneratorConfig | undefined =>
1616 + Object.hasOwn(settings.textGenerators, instanceId)
1617 + ? settings.textGenerators[instanceId]
1618 + : undefined;
1619 +
1620 +/** Whether a text generation selection can run: an enabled text generator or provider instance. */
1621 +export const resolveTextGenerationSelectionEnabled = (
1622 + settings: Pick<
1623 + ServerSettings,
1624 + "providerInstances" | "projectSettingsOverrides" | "textGenerators"
1625 + >,
1626 + projectId: ProjectId | null,
1627 + instanceId: ProviderInstanceId,
1628 +): boolean =>
1629 + textGeneratorForSelection(settings, instanceId)?.enabled ??
1630 + resolveProjectProviderInstanceEnabled(settings, projectId, instanceId);
1631 +
1632 const decodeClaudeSettings = Schema.decodeUnknownOption(ClaudeSettings);
1633
1634 type IdleCompactionSettings = Pick<ServerSettings, "compactIdleThreads" | "idleCompaction">;
@@ -1820,6 +1913,10 @@ export const ServerSettingsPatch = Schema.Struct({
1913 usageLimitSources: Schema.optionalKey(
1914 Schema.Record(UsageLimitSourceId, Schema.NullOr(UsageLimitSourceConfig)),
1915 ),
1916 + // Merge per entry like usageLimitSources; null removes an entry.
1917 + textGenerators: Schema.optionalKey(
1918 + Schema.Record(ProviderInstanceId, Schema.NullOr(TextGeneratorConfig)),
1919 + ),
1920 secretProviders: Schema.optionalKey(
1921 Schema.Record(SecretProviderId, Schema.NullOr(SecretProviderConfigWrite)),
1922 ),
@@ -1845,6 +1942,7 @@ export function requiredScopesForServerSettingsPatch(
1942 key === "providers" ||
1943 key === "providerInstances" ||
1944 key === "usageLimitSources" ||
1945 + key === "textGenerators" ||
1946 key === "secretProviders"
1947 ) {
1948 changesProviders = true;
packages/shared/src/projectSettings.ts
+7 -6
@@ -7,6 +7,7 @@ import {
7 type ProjectScopedServerSettingKey,
8 type ProjectSettingsOverrides,
9 resolveProjectProviderInstanceEnabled,
10 + resolveTextGenerationSelectionEnabled,
11 type ResolvedServerSettings,
12 type ServerSettings,
13 type T3ProjectFile,
@@ -139,11 +140,11 @@ function resolveProjectOverrides(
140 (key === "textGenerationModelSelection" || key === "defaultModelSelection") &&
141 value !== undefined &&
142 value !== null &&
142 - !resolveProjectProviderInstanceEnabled(
143 - settings,
144 - projectId,
145 - (value as ModelSelection).instanceId,
146 - )
143 + !(
144 + key === "textGenerationModelSelection"
145 + ? resolveTextGenerationSelectionEnabled
146 + : resolveProjectProviderInstanceEnabled
147 + )(settings, projectId, (value as ModelSelection).instanceId)
148 ) {
149 continue;
150 }
@@ -151,7 +152,7 @@ function resolveProjectOverrides(
152 sources[key] = "project";
153 }
154 const textGeneration = effective.textGenerationModelSelection as ModelSelection;
154 - if (!resolveProjectProviderInstanceEnabled(settings, projectId, textGeneration.instanceId)) {
155 + if (!resolveTextGenerationSelectionEnabled(settings, projectId, textGeneration.instanceId)) {
156 const fallback = fallbackTextGenerationModelSelection(
157 settings.providerInstances,
158 (instanceId) => resolveProjectProviderInstanceEnabled(settings, projectId, instanceId),
packages/shared/src/serverSettings.test.ts
+40
@@ -23,6 +23,7 @@ import {
23 resolveModelPreferences,
24 isModelSelectionProviderEnabled,
25 parsePersistedServerObservabilitySettings,
26 + resolveReviewGuideModelSelection,
27 resolveSourceControlWriterModelSelection,
28 resolveSpeechPostProcessingModelSelection,
29 } from "./serverSettings.ts";
@@ -405,6 +406,45 @@ describe("serverSettings helpers", () => {
406 expect(settings.sourceControlWriterModelSelection).toBe(sourceControlWriterModelSelection);
407 });
408
409 + it("routes every text task but review guides to a text generator, until it is turned off", () => {
410 + const generatorId = ProviderInstanceId.make("openrouter");
411 + const selection = createModelSelection(generatorId, "openai/gpt-5-mini");
412 + const settings = (enabled: boolean) => ({
413 + ...DEFAULT_SERVER_SETTINGS,
414 + textGenerators: {
415 + [generatorId]: {
416 + kind: "openaiCompatible" as const,
417 + baseUrl: "https://openrouter.ai/api/v1",
418 + apiKey: "",
419 + enabled,
420 + },
421 + },
422 + sourceControlWriterModelSelection: selection,
423 + reviewGuideModelSelection: selection,
424 + speechPostProcessingModelSelection: selection,
425 + });
426 + // A text generator has no provider snapshot; an empty list must not read as unusable.
427 + const on = settings(true);
428 + expect(resolveSourceControlWriterModelSelection(on, [], null)).toBe(selection);
429 + expect(resolveSpeechPostProcessingModelSelection(on, [])).toBe(selection);
430 + expect(resolveReviewGuideModelSelection(on, [], null)).toBe(selection);
431 + expect(
432 + resolveReviewGuideModelSelection(
433 + { ...on, sourceControlWriterModelSelection: null },
434 + [],
435 + null,
436 + ),
437 + ).toBe(on.textGenerationModelSelection);
438 +
439 + const off = settings(false);
440 + expect(resolveSourceControlWriterModelSelection(off, [], null)).toBe(
441 + off.textGenerationModelSelection,
442 + );
443 + expect(resolveSpeechPostProcessingModelSelection(off, [])).toBe(
444 + off.textGenerationModelSelection,
445 + );
446 + });
447 +
448 it("falls back from a writer provider a project turned off, keeping it for other projects", () => {
449 const instanceId = ProviderInstanceId.make("codex_writer");
450 const projectId = ProjectId.make("project-a");
packages/shared/src/serverSettings.ts
+38 -37
@@ -10,6 +10,8 @@ import {
10 isUnconfiguredDefaultInstanceEnabled,
11 resolveProjectProviderInstanceEnabled,
12 resolveProviderInstanceEnabled,
13 + resolveTextGenerationSelectionEnabled,
14 + textGeneratorForSelection,
15 isProviderTextGenerationCapable,
16 type ModelSelection,
17 type ProjectId,
@@ -47,6 +49,8 @@ export function isModelSelectionProviderEnabled(
49 settings: ServerSettings,
50 selection: ModelSelection,
51 ): boolean {
52 + const generator = textGeneratorForSelection(settings, selection.instanceId);
53 + if (generator !== undefined) return generator.enabled;
54 const instanceConfig = settings.providerInstances[selection.instanceId];
55 if (instanceConfig !== undefined) {
56 return resolveProviderInstanceEnabled(instanceConfig);
@@ -109,26 +113,32 @@ export function defaultTextGenerationModel(driver: ProviderDriverKind): string {
113 );
114 }
115
116 +/** A text generator, or a provider whose snapshot can generate text; no snapshots trusts settings. */
117 +function isTextGenerationTargetUsable(
118 + settings: ServerSettings,
119 + providers: ReadonlyArray<ServerProvider> | undefined,
120 + instanceId: ProviderInstanceId,
121 +): boolean {
122 + if (providers === undefined || textGeneratorForSelection(settings, instanceId) !== undefined) {
123 + return true;
124 + }
125 + const provider = providers.find((candidate) => candidate.instanceId === instanceId);
126 + return (
127 + provider?.enabled === true &&
128 + isProviderAvailable(provider) &&
129 + isProviderTextGenerationCapable(provider)
130 + );
131 +}
132 +
133 export function resolveSourceControlWriterModelSelection(
134 settings: ServerSettings,
135 providers: ReadonlyArray<ServerProvider> | undefined,
136 projectId: ProjectId | null,
137 ): ModelSelection {
138 const selection = settings.sourceControlWriterModelSelection;
118 - if (
119 - !selection ||
120 - !resolveProjectProviderInstanceEnabled(settings, projectId, selection.instanceId)
121 - ) {
122 - return settings.textGenerationModelSelection;
123 - }
124 - if (providers === undefined) {
125 - return selection;
126 - }
127 -
128 - const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
129 - return provider?.enabled === true &&
130 - isProviderAvailable(provider) &&
131 - isProviderTextGenerationCapable(provider)
139 + return selection &&
140 + resolveTextGenerationSelectionEnabled(settings, projectId, selection.instanceId) &&
141 + isTextGenerationTargetUsable(settings, providers, selection.instanceId)
142 ? selection
143 : settings.textGenerationModelSelection;
144 }
@@ -139,21 +149,13 @@ export function resolveReviewGuideModelSelection(
149 projectId: ProjectId | null,
150 ): ModelSelection {
151 const selection = settings.reviewGuideModelSelection;
142 - if (
143 - selection &&
144 - resolveProjectProviderInstanceEnabled(settings, projectId, selection.instanceId)
145 - ) {
146 - const provider = providers?.find((candidate) => candidate.instanceId === selection.instanceId);
147 - if (
148 - providers === undefined ||
149 - (provider?.enabled === true &&
150 - isProviderAvailable(provider) &&
151 - isProviderTextGenerationCapable(provider))
152 - ) {
153 - return selection;
154 - }
155 - }
156 - return resolveSourceControlWriterModelSelection(settings, providers, projectId);
152 + // Text generators cannot investigate a checkout, so they never write review guides.
153 + return selection &&
154 + textGeneratorForSelection(settings, selection.instanceId) === undefined &&
155 + resolveProjectProviderInstanceEnabled(settings, projectId, selection.instanceId) &&
156 + isTextGenerationTargetUsable(settings, providers, selection.instanceId)
157 + ? selection
158 + : resolveSourceControlWriterModelSelection(settings, providers, projectId);
159 }
160
161 /** Transcript cleanup follows the text generation model unless its own usable model is set. */
@@ -162,14 +164,9 @@ export function resolveSpeechPostProcessingModelSelection(
164 providers?: ReadonlyArray<ServerProvider>,
165 ): ModelSelection {
166 const selection = settings.speechPostProcessingModelSelection;
165 - if (!selection || !isModelSelectionProviderEnabled(settings, selection)) {
166 - return settings.textGenerationModelSelection;
167 - }
168 - if (providers === undefined) return selection;
169 - const provider = providers.find((candidate) => candidate.instanceId === selection.instanceId);
170 - return provider?.enabled === true &&
171 - isProviderAvailable(provider) &&
172 - isProviderTextGenerationCapable(provider)
167 + return selection &&
168 + isModelSelectionProviderEnabled(settings, selection) &&
169 + isTextGenerationTargetUsable(settings, providers, selection.instanceId)
170 ? selection
171 : settings.textGenerationModelSelection;
172 }
@@ -402,6 +399,7 @@ export function applyServerSettingsPatch(
399 worktreeCleanup: worktreeCleanupPatch,
400 // Merged per entry below; its `null` removals must not reach deepMerge.
401 usageLimitSources: usageLimitSourcesPatch,
402 + textGenerators: textGeneratorsPatch,
403 secretProviders: secretProvidersPatch,
404 sourceControlHosts: sourceControlHostsPatch,
405 usagePriceOverrides: usagePriceOverridesPatch,
@@ -619,6 +617,9 @@ export function applyServerSettingsPatch(
617 ),
618 }
619 : {}),
620 + ...(textGeneratorsPatch !== undefined
621 + ? { textGenerators: mergeSettingsEntries(current.textGenerators, textGeneratorsPatch) }
622 + : {}),
623 ...(secretProvidersPatch !== undefined
624 ? { secretProviders: mergeSettingsEntries(current.secretProviders, secretProvidersPatch) }
625 : {}),