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