Open History to see the last commit
1import { useCallback } from "react";
2import { Option, Schema } from "effect";
3import {
4 TrimmedNonEmptyString,
5 type ProviderKind,
6 type ProviderStartOptions,
7} from "@t3tools/contracts";
8import {
9 getDefaultModel,
10 getModelOptions,
11 normalizeModelSlug,
12 resolveSelectableModel,
13} from "@t3tools/shared/model";
14import { useLocalStorage } from "./hooks/useLocalStorage";
15import { EnvMode } from "./components/BranchToolbar.logic";
16
17const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
18const MAX_CUSTOM_MODEL_COUNT = 32;
19export const MAX_CUSTOM_MODEL_LENGTH = 256;
20
21export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
22export type TimestampFormat = typeof TimestampFormat.Type;
23export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
24type CustomModelSettingsKey = "customCodexModels" | "customClaudeModels";
25export type ProviderCustomModelConfig = {
26 provider: ProviderKind;
27 settingsKey: CustomModelSettingsKey;
28 defaultSettingsKey: CustomModelSettingsKey;
29 title: string;
30 description: string;
31 placeholder: string;
32 example: string;
33};
34
35const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
36 codex: new Set(getModelOptions("codex").map((option) => option.slug)),
37 claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
38 cursor: new Set(getModelOptions("cursor").map((option) => option.slug)),
39 opencode: new Set(getModelOptions("opencode").map((option) => option.slug)),
40};
41
42const withDefaults =
43 <
44 S extends Schema.Top & Schema.WithoutConstructorDefault,
45 D extends S["~type.make.in"] & S["Encoded"],
46 >(
47 fallback: () => D,
48 ) =>
49 (schema: S) =>
50 schema.pipe(
51 Schema.withConstructorDefault(() => Option.some(fallback())),
52 Schema.withDecodingDefault(() => fallback()),
53 );
54
55export const AppSettingsSchema = Schema.Struct({
56 codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
57 codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
58 claudeBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
59 defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
60 confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
61 enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
62 timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
63 customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
64 customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
65 textGenerationModel: Schema.optional(TrimmedNonEmptyString),
66});
67export type AppSettings = typeof AppSettingsSchema.Type;
68export interface AppModelOption {
69 slug: string;
70 name: string;
71 isCustom: boolean;
72}
73
74const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
75const PROVIDER_CUSTOM_MODEL_CONFIG: Partial<Record<ProviderKind, ProviderCustomModelConfig>> = {
76 codex: {
77 provider: "codex",
78 settingsKey: "customCodexModels",
79 defaultSettingsKey: "customCodexModels",
80 title: "Codex",
81 description: "Save additional Codex model slugs for the picker and `/model` command.",
82 placeholder: "your-codex-model-slug",
83 example: "gpt-6.7-codex-ultra-preview",
84 },
85 claudeAgent: {
86 provider: "claudeAgent",
87 settingsKey: "customClaudeModels",
88 defaultSettingsKey: "customClaudeModels",
89 title: "Claude",
90 description: "Save additional Claude model slugs for the picker and `/model` command.",
91 placeholder: "your-claude-model-slug",
92 example: "claude-sonnet-5-0",
93 },
94};
95export const MODEL_PROVIDER_SETTINGS = Object.values(PROVIDER_CUSTOM_MODEL_CONFIG);
96
97export function normalizeCustomModelSlugs(
98 models: Iterable<string | null | undefined>,
99 provider: ProviderKind = "codex",
100): string[] {
101 const normalizedModels: string[] = [];
102 const seen = new Set<string>();
103 const builtInModelSlugs = BUILT_IN_MODEL_SLUGS_BY_PROVIDER[provider];
104
105 for (const candidate of models) {
106 const normalized = normalizeModelSlug(candidate, provider);
107 if (
108 !normalized ||
109 normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
110 builtInModelSlugs.has(normalized) ||
111 seen.has(normalized)
112 ) {
113 continue;
114 }
115
116 seen.add(normalized);
117 normalizedModels.push(normalized);
118 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
119 break;
120 }
121 }
122
123 return normalizedModels;
124}
125
126function normalizeAppSettings(settings: AppSettings): AppSettings {
127 return {
128 ...settings,
129 customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
130 customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
131 };
132}
133
134export function getCustomModelsForProvider(
135 settings: Pick<AppSettings, CustomModelSettingsKey>,
136 provider: ProviderKind,
137): readonly string[] {
138 const config = PROVIDER_CUSTOM_MODEL_CONFIG[provider];
139 if (!config) {
140 return [];
141 }
142 return settings[config.settingsKey];
143}
144
145export function getDefaultCustomModelsForProvider(
146 defaults: Pick<AppSettings, CustomModelSettingsKey>,
147 provider: ProviderKind,
148): readonly string[] {
149 const config = PROVIDER_CUSTOM_MODEL_CONFIG[provider];
150 if (!config) {
151 return [];
152 }
153 return defaults[config.defaultSettingsKey];
154}
155
156export function patchCustomModels(
157 provider: ProviderKind,
158 models: string[],
159): Partial<Pick<AppSettings, CustomModelSettingsKey>> {
160 const config = PROVIDER_CUSTOM_MODEL_CONFIG[provider];
161 if (!config) {
162 return {};
163 }
164 return {
165 [config.settingsKey]: models,
166 };
167}
168
169export function getCustomModelsByProvider(
170 settings: Pick<AppSettings, CustomModelSettingsKey>,
171): Record<ProviderKind, readonly string[]> {
172 return {
173 codex: getCustomModelsForProvider(settings, "codex"),
174 claudeAgent: getCustomModelsForProvider(settings, "claudeAgent"),
175 cursor: [],
176 opencode: [],
177 };
178}
179
180export function getAppModelOptions(
181 provider: ProviderKind,
182 customModels: readonly string[],
183 selectedModel?: string | null,
184): AppModelOption[] {
185 const options: AppModelOption[] = getModelOptions(provider).map(({ slug, name }) => ({
186 slug,
187 name,
188 isCustom: false,
189 }));
190 const seen = new Set(options.map((option) => option.slug));
191 const trimmedSelectedModel = selectedModel?.trim().toLowerCase();
192
193 for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
194 if (seen.has(slug)) {
195 continue;
196 }
197
198 seen.add(slug);
199 options.push({
200 slug,
201 name: slug,
202 isCustom: true,
203 });
204 }
205
206 const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
207 const selectedModelMatchesExistingName =
208 typeof trimmedSelectedModel === "string" &&
209 options.some((option) => option.name.toLowerCase() === trimmedSelectedModel);
210 if (
211 normalizedSelectedModel &&
212 !seen.has(normalizedSelectedModel) &&
213 !selectedModelMatchesExistingName
214 ) {
215 options.push({
216 slug: normalizedSelectedModel,
217 name: normalizedSelectedModel,
218 isCustom: true,
219 });
220 }
221
222 return options;
223}
224
225export function resolveAppModelSelection(
226 provider: ProviderKind,
227 customModels: Partial<Record<ProviderKind, readonly string[]>>,
228 selectedModel: string | null | undefined,
229): string {
230 const customModelsForProvider = customModels[provider] ?? [];
231 const options = getAppModelOptions(provider, customModelsForProvider, selectedModel);
232 return resolveSelectableModel(provider, selectedModel, options) ?? getDefaultModel(provider);
233}
234
235export function getCustomModelOptionsByProvider(
236 settings: Pick<AppSettings, CustomModelSettingsKey>,
237 discoveredModels?: Partial<Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>>,
238): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
239 const customModelsByProvider = getCustomModelsByProvider(settings);
240
241 // Merge discovered models (from provider CLI) as additional options.
242 // Discovered models are placed after built-in but before user custom models.
243 const mergeDiscovered = (
244 provider: ProviderKind,
245 customModels: readonly string[],
246 ): ReadonlyArray<{ slug: string; name: string }> => {
247 const builtInAndCustom = getAppModelOptions(provider, customModels);
248 const discovered = discoveredModels?.[provider] ?? [];
249 if (discovered.length === 0) return builtInAndCustom;
250
251 // Filter out discovered models that are already in built-in or custom
252 const existingSlugs = new Set(builtInAndCustom.map((m) => m.slug));
253 const newDiscovered = discovered.filter((m) => !existingSlugs.has(m.slug));
254 if (newDiscovered.length === 0) return builtInAndCustom;
255
256 // Insert discovered models after built-in, before custom
257 const builtIn = builtInAndCustom.filter(
258 (m) => !("isCustom" in m && (m as AppModelOption).isCustom),
259 );
260 const custom = builtInAndCustom.filter(
261 (m) => "isCustom" in m && (m as AppModelOption).isCustom,
262 );
263 return [...builtIn, ...newDiscovered, ...custom];
264 };
265
266 return {
267 codex: mergeDiscovered("codex", customModelsByProvider.codex),
268 claudeAgent: mergeDiscovered("claudeAgent", customModelsByProvider.claudeAgent),
269 cursor: mergeDiscovered("cursor", customModelsByProvider.cursor ?? []),
270 opencode: mergeDiscovered("opencode", customModelsByProvider.opencode ?? []),
271 };
272}
273
274export function getProviderStartOptions(
275 settings: Pick<AppSettings, "claudeBinaryPath" | "codexBinaryPath" | "codexHomePath">,
276): ProviderStartOptions | undefined {
277 const providerOptions: ProviderStartOptions = {
278 ...(settings.codexBinaryPath || settings.codexHomePath
279 ? {
280 codex: {
281 ...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
282 ...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
283 },
284 }
285 : {}),
286 ...(settings.claudeBinaryPath
287 ? {
288 claudeAgent: {
289 binaryPath: settings.claudeBinaryPath,
290 },
291 }
292 : {}),
293 };
294
295 return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
296}
297
298export function useAppSettings() {
299 const [settings, setSettings] = useLocalStorage(
300 APP_SETTINGS_STORAGE_KEY,
301 DEFAULT_APP_SETTINGS,
302 AppSettingsSchema,
303 );
304
305 const updateSettings = useCallback(
306 (patch: Partial<AppSettings>) => {
307 setSettings((prev) => normalizeAppSettings({ ...prev, ...patch }));
308 },
309 [setSettings],
310 );
311
312 const resetSettings = useCallback(() => {
313 setSettings(DEFAULT_APP_SETTINGS);
314 }, [setSettings]);
315
316 return {
317 settings,
318 updateSettings,
319 resetSettings,
320 defaults: DEFAULT_APP_SETTINGS,
321 } as const;
322}