Open History to see the last commit
1import { useCallback, useSyncExternalStore } from "react";
2import { Option, Schema } from "effect";
3import { MODEL_OPTIONS, normalizeModelSlug } from "@t3tools/contracts";
4
5const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
6const MAX_CUSTOM_MODEL_COUNT = 32;
7export const MAX_CUSTOM_MODEL_LENGTH = 256;
8const BUILT_IN_MODEL_SLUGS = new Set<string>(MODEL_OPTIONS.map((option) => option.slug));
9
10const AppSettingsSchema = Schema.Struct({
11 codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
12 Schema.withConstructorDefault(() => Option.some("")),
13 ),
14 codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
15 Schema.withConstructorDefault(() => Option.some("")),
16 ),
17 confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
18 enableAssistantStreaming: Schema.Boolean.pipe(
19 Schema.withConstructorDefault(() => Option.some(false)),
20 ),
21 customCodexModels: Schema.Array(Schema.String).pipe(
22 Schema.withConstructorDefault(() => Option.some([])),
23 ),
24});
25export type AppSettings = typeof AppSettingsSchema.Type;
26export interface AppModelOption {
27 slug: string;
28 name: string;
29 isCustom: boolean;
30}
31
32const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
33
34let listeners: Array<() => void> = [];
35let cachedRawSettings: string | null | undefined;
36let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
37
38export function normalizeCustomModelSlugs(
39 models: Iterable<string | null | undefined>,
40): AppSettings["customCodexModels"] {
41 const normalizedModels: string[] = [];
42 const seen = new Set<string>();
43
44 for (const candidate of models) {
45 const normalized = normalizeModelSlug(candidate);
46 if (
47 !normalized ||
48 normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
49 BUILT_IN_MODEL_SLUGS.has(normalized) ||
50 seen.has(normalized)
51 ) {
52 continue;
53 }
54
55 seen.add(normalized);
56 normalizedModels.push(normalized);
57 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
58 break;
59 }
60 }
61
62 return normalizedModels;
63}
64
65function normalizeAppSettings(settings: AppSettings): AppSettings {
66 return {
67 ...settings,
68 customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels),
69 };
70}
71
72export function getAppModelOptions(
73 customModels: readonly string[],
74 selectedModel?: string | null,
75): AppModelOption[] {
76 const options: AppModelOption[] = MODEL_OPTIONS.map(({ slug, name }) => ({
77 slug,
78 name,
79 isCustom: false,
80 }));
81 const seen = new Set(options.map((option) => option.slug));
82
83 for (const slug of normalizeCustomModelSlugs(customModels)) {
84 if (seen.has(slug)) {
85 continue;
86 }
87
88 seen.add(slug);
89 options.push({
90 slug,
91 name: slug,
92 isCustom: true,
93 });
94 }
95
96 const normalizedSelectedModel = normalizeModelSlug(selectedModel);
97 if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
98 options.push({
99 slug: normalizedSelectedModel,
100 name: normalizedSelectedModel,
101 isCustom: true,
102 });
103 }
104
105 return options;
106}
107
108function emitChange(): void {
109 for (const listener of listeners) {
110 listener();
111 }
112}
113
114function parsePersistedSettings(value: string | null): AppSettings {
115 if (!value) {
116 return DEFAULT_APP_SETTINGS;
117 }
118
119 try {
120 return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
121 } catch {
122 return DEFAULT_APP_SETTINGS;
123 }
124}
125
126export function getAppSettingsSnapshot(): AppSettings {
127 if (typeof window === "undefined") {
128 return DEFAULT_APP_SETTINGS;
129 }
130
131 const raw = window.localStorage.getItem(APP_SETTINGS_STORAGE_KEY);
132 if (raw === cachedRawSettings) {
133 return cachedSnapshot;
134 }
135
136 cachedRawSettings = raw;
137 cachedSnapshot = parsePersistedSettings(raw);
138 return cachedSnapshot;
139}
140
141function persistSettings(next: AppSettings): void {
142 if (typeof window === "undefined") return;
143
144 const raw = JSON.stringify(next);
145 try {
146 if (raw !== cachedRawSettings) {
147 window.localStorage.setItem(APP_SETTINGS_STORAGE_KEY, raw);
148 }
149 } catch {
150 // Best-effort persistence only.
151 }
152
153 cachedRawSettings = raw;
154 cachedSnapshot = next;
155}
156
157function subscribe(listener: () => void): () => void {
158 listeners.push(listener);
159
160 const onStorage = (event: StorageEvent) => {
161 if (event.key === APP_SETTINGS_STORAGE_KEY) {
162 emitChange();
163 }
164 };
165
166 window.addEventListener("storage", onStorage);
167 return () => {
168 listeners = listeners.filter((entry) => entry !== listener);
169 window.removeEventListener("storage", onStorage);
170 };
171}
172
173export function useAppSettings() {
174 const settings = useSyncExternalStore(
175 subscribe,
176 getAppSettingsSnapshot,
177 () => DEFAULT_APP_SETTINGS,
178 );
179
180 const updateSettings = useCallback((patch: Partial<AppSettings>) => {
181 const next = normalizeAppSettings(
182 Schema.decodeSync(AppSettingsSchema)({
183 ...getAppSettingsSnapshot(),
184 ...patch,
185 }),
186 );
187 persistSettings(next);
188 emitChange();
189 }, []);
190
191 const resetSettings = useCallback(() => {
192 persistSettings(DEFAULT_APP_SETTINGS);
193 emitChange();
194 }, []);
195
196 return {
197 settings,
198 updateSettings,
199 resetSettings,
200 defaults: DEFAULT_APP_SETTINGS,
201 } as const;
202}