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