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

appSettings.ts

237 lines6.6 KB

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