Open History to see the last commit
1import { useCallback, useSyncExternalStore } from "react";
2import { Option, Schema } from "effect";
3import { type ProviderKind, type ProviderServiceTier } from "@t3tools/contracts";
4import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
5
6const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
7const MAX_CUSTOM_MODEL_COUNT = 32;
8export const MAX_CUSTOM_MODEL_LENGTH = 256;
9export const APP_SERVICE_TIER_OPTIONS = [
10 {
11 value: "auto",
12 label: "Automatic",
13 description: "Use Codex defaults without forcing a service tier.",
14 },
15 {
16 value: "fast",
17 label: "Fast",
18 description: "Request the fast service tier when the model supports it.",
19 },
20 {
21 value: "flex",
22 label: "Flex",
23 description: "Request the flex service tier when the model supports it.",
24 },
25] as const;
26export type AppServiceTier = (typeof APP_SERVICE_TIER_OPTIONS)[number]["value"];
27const AppServiceTierSchema = Schema.Literals(["auto", "fast", "flex"]);
28const MODELS_WITH_FAST_SUPPORT = new Set(["gpt-5.4"]);
29const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
30 codex: new Set(getModelOptions("codex").map((option) => option.slug)),
31};
32
33const AppSettingsSchema = Schema.Struct({
34 codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
35 Schema.withConstructorDefault(() => Option.some("")),
36 ),
37 codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
38 Schema.withConstructorDefault(() => Option.some("")),
39 ),
40 confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
41 enableAssistantStreaming: Schema.Boolean.pipe(
42 Schema.withConstructorDefault(() => Option.some(false)),
43 ),
44 codexServiceTier: AppServiceTierSchema.pipe(Schema.withConstructorDefault(() => Option.some("auto"))),
45 customCodexModels: Schema.Array(Schema.String).pipe(
46 Schema.withConstructorDefault(() => Option.some([])),
47 ),
48});
49export type AppSettings = typeof AppSettingsSchema.Type;
50export interface AppModelOption {
51 slug: string;
52 name: string;
53 isCustom: boolean;
54}
55
56export function resolveAppServiceTier(serviceTier: AppServiceTier): ProviderServiceTier | null {
57 return serviceTier === "auto" ? null : serviceTier;
58}
59
60export function shouldShowFastTierIcon(
61 model: string | null | undefined,
62 serviceTier: AppServiceTier,
63): boolean {
64 const normalizedModel = normalizeModelSlug(model);
65 return (
66 resolveAppServiceTier(serviceTier) === "fast" &&
67 normalizedModel !== null &&
68 MODELS_WITH_FAST_SUPPORT.has(normalizedModel)
69 );
70}
71
72const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
73
74let listeners: Array<() => void> = [];
75let cachedRawSettings: string | null | undefined;
76let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
77
78export function normalizeCustomModelSlugs(
79 models: Iterable<string | null | undefined>,
80 provider: ProviderKind = "codex",
81): string[] {
82 const normalizedModels: string[] = [];
83 const seen = new Set<string>();
84 const builtInModelSlugs = BUILT_IN_MODEL_SLUGS_BY_PROVIDER[provider];
85
86 for (const candidate of models) {
87 const normalized = normalizeModelSlug(candidate, provider);
88 if (
89 !normalized ||
90 normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
91 builtInModelSlugs.has(normalized) ||
92 seen.has(normalized)
93 ) {
94 continue;
95 }
96
97 seen.add(normalized);
98 normalizedModels.push(normalized);
99 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
100 break;
101 }
102 }
103
104 return normalizedModels;
105}
106
107function normalizeAppSettings(settings: AppSettings): AppSettings {
108 return {
109 ...settings,
110 customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
111 };
112}
113
114export function getAppModelOptions(
115 provider: ProviderKind,
116 customModels: readonly string[],
117 selectedModel?: string | null,
118): AppModelOption[] {
119 const options: AppModelOption[] = getModelOptions(provider).map(({ slug, name }) => ({
120 slug,
121 name,
122 isCustom: false,
123 }));
124 const seen = new Set(options.map((option) => option.slug));
125
126 for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
127 if (seen.has(slug)) {
128 continue;
129 }
130
131 seen.add(slug);
132 options.push({
133 slug,
134 name: slug,
135 isCustom: true,
136 });
137 }
138
139 const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
140 if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
141 options.push({
142 slug: normalizedSelectedModel,
143 name: normalizedSelectedModel,
144 isCustom: true,
145 });
146 }
147
148 return options;
149}
150
151export function resolveAppModelSelection(
152 provider: ProviderKind,
153 customModels: readonly string[],
154 selectedModel: string | null | undefined,
155): string {
156 const options = getAppModelOptions(provider, customModels, selectedModel);
157 const trimmedSelectedModel = selectedModel?.trim();
158 if (trimmedSelectedModel) {
159 const direct = options.find((option) => option.slug === trimmedSelectedModel);
160 if (direct) {
161 return direct.slug;
162 }
163
164 const byName = options.find(
165 (option) => option.name.toLowerCase() === trimmedSelectedModel.toLowerCase(),
166 );
167 if (byName) {
168 return byName.slug;
169 }
170 }
171
172 const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
173 if (!normalizedSelectedModel) {
174 return getDefaultModel(provider);
175 }
176
177 return (
178 options.find((option) => option.slug === normalizedSelectedModel)?.slug ??
179 getDefaultModel(provider)
180 );
181}
182
183export function getSlashModelOptions(
184 provider: ProviderKind,
185 customModels: readonly string[],
186 query: string,
187 selectedModel?: string | null,
188): AppModelOption[] {
189 const normalizedQuery = query.trim().toLowerCase();
190 const options = getAppModelOptions(provider, customModels, selectedModel);
191 if (!normalizedQuery) {
192 return options;
193 }
194
195 return options.filter((option) => {
196 const searchSlug = option.slug.toLowerCase();
197 const searchName = option.name.toLowerCase();
198 return searchSlug.includes(normalizedQuery) || searchName.includes(normalizedQuery);
199 });
200}
201
202function emitChange(): void {
203 for (const listener of listeners) {
204 listener();
205 }
206}
207
208function parsePersistedSettings(value: string | null): AppSettings {
209 if (!value) {
210 return DEFAULT_APP_SETTINGS;
211 }
212
213 try {
214 return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
215 } catch {
216 return DEFAULT_APP_SETTINGS;
217 }
218}
219
220export function getAppSettingsSnapshot(): AppSettings {
221 if (typeof window === "undefined") {
222 return DEFAULT_APP_SETTINGS;
223 }
224
225 const raw = window.localStorage.getItem(APP_SETTINGS_STORAGE_KEY);
226 if (raw === cachedRawSettings) {
227 return cachedSnapshot;
228 }
229
230 cachedRawSettings = raw;
231 cachedSnapshot = parsePersistedSettings(raw);
232 return cachedSnapshot;
233}
234
235function persistSettings(next: AppSettings): void {
236 if (typeof window === "undefined") return;
237
238 const raw = JSON.stringify(next);
239 try {
240 if (raw !== cachedRawSettings) {
241 window.localStorage.setItem(APP_SETTINGS_STORAGE_KEY, raw);
242 }
243 } catch {
244 // Best-effort persistence only.
245 }
246
247 cachedRawSettings = raw;
248 cachedSnapshot = next;
249}
250
251function subscribe(listener: () => void): () => void {
252 listeners.push(listener);
253
254 const onStorage = (event: StorageEvent) => {
255 if (event.key === APP_SETTINGS_STORAGE_KEY) {
256 emitChange();
257 }
258 };
259
260 window.addEventListener("storage", onStorage);
261 return () => {
262 listeners = listeners.filter((entry) => entry !== listener);
263 window.removeEventListener("storage", onStorage);
264 };
265}
266
267export function useAppSettings() {
268 const settings = useSyncExternalStore(
269 subscribe,
270 getAppSettingsSnapshot,
271 () => DEFAULT_APP_SETTINGS,
272 );
273
274 const updateSettings = useCallback((patch: Partial<AppSettings>) => {
275 const next = normalizeAppSettings(
276 Schema.decodeSync(AppSettingsSchema)({
277 ...getAppSettingsSnapshot(),
278 ...patch,
279 }),
280 );
281 persistSettings(next);
282 emitChange();
283 }, []);
284
285 const resetSettings = useCallback(() => {
286 persistSettings(DEFAULT_APP_SETTINGS);
287 emitChange();
288 }, []);
289
290 return {
291 settings,
292 updateSettings,
293 resetSettings,
294 defaults: DEFAULT_APP_SETTINGS,
295 } as const;
296}