Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

appSettings.ts

248 lines7.9 KB

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