Open History to see the last commit
1import { useCallback } from "react";
2import { Option, Schema } from "effect";
3import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
4import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
5import { useLocalStorage } from "./hooks/useLocalStorage";
6import { EnvMode } from "./components/BranchToolbar.logic";
7
8const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
9const MAX_CUSTOM_MODEL_COUNT = 32;
10export const MAX_CUSTOM_MODEL_LENGTH = 256;
11
12export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
13export type TimestampFormat = typeof TimestampFormat.Type;
14export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
15
16const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
17 codex: new Set(getModelOptions("codex").map((option) => option.slug)),
18 claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
19};
20
21const withDefaults =
22 <
23 S extends Schema.Top & Schema.WithoutConstructorDefault,
24 D extends S["~type.make.in"] & S["Encoded"],
25 >(
26 fallback: () => D,
27 ) =>
28 (schema: S) =>
29 schema.pipe(
30 Schema.withConstructorDefault(() => Option.some(fallback())),
31 Schema.withDecodingDefault(() => fallback()),
32 );
33
34export const AppSettingsSchema = Schema.Struct({
35 codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
36 codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
37 defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
38 confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
39 enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
40 timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
41 customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
42 customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
43 textGenerationModel: Schema.optional(TrimmedNonEmptyString),
44});
45export type AppSettings = typeof AppSettingsSchema.Type;
46export interface AppModelOption {
47 slug: string;
48 name: string;
49 isCustom: boolean;
50}
51
52const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
53
54export function normalizeCustomModelSlugs(
55 models: Iterable<string | null | undefined>,
56 provider: ProviderKind = "codex",
57): string[] {
58 const normalizedModels: string[] = [];
59 const seen = new Set<string>();
60 const builtInModelSlugs = BUILT_IN_MODEL_SLUGS_BY_PROVIDER[provider];
61
62 for (const candidate of models) {
63 const normalized = normalizeModelSlug(candidate, provider);
64 if (
65 !normalized ||
66 normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
67 builtInModelSlugs.has(normalized) ||
68 seen.has(normalized)
69 ) {
70 continue;
71 }
72
73 seen.add(normalized);
74 normalizedModels.push(normalized);
75 if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
76 break;
77 }
78 }
79
80 return normalizedModels;
81}
82
83function normalizeAppSettings(settings: AppSettings): AppSettings {
84 return {
85 ...settings,
86 customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
87 customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
88 };
89}
90export function getAppModelOptions(
91 provider: ProviderKind,
92 customModels: readonly string[],
93 selectedModel?: string | null,
94): AppModelOption[] {
95 const options: AppModelOption[] = getModelOptions(provider).map(({ slug, name }) => ({
96 slug,
97 name,
98 isCustom: false,
99 }));
100 const seen = new Set(options.map((option) => option.slug));
101
102 for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
103 if (seen.has(slug)) {
104 continue;
105 }
106
107 seen.add(slug);
108 options.push({
109 slug,
110 name: slug,
111 isCustom: true,
112 });
113 }
114
115 const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
116 if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
117 options.push({
118 slug: normalizedSelectedModel,
119 name: normalizedSelectedModel,
120 isCustom: true,
121 });
122 }
123
124 return options;
125}
126
127export function resolveAppModelSelection(
128 provider: ProviderKind,
129 customModels: readonly string[],
130 selectedModel: string | null | undefined,
131): string {
132 const options = getAppModelOptions(provider, customModels, selectedModel);
133 const trimmedSelectedModel = selectedModel?.trim();
134 if (trimmedSelectedModel) {
135 const direct = options.find((option) => option.slug === trimmedSelectedModel);
136 if (direct) {
137 return direct.slug;
138 }
139
140 const byName = options.find(
141 (option) => option.name.toLowerCase() === trimmedSelectedModel.toLowerCase(),
142 );
143 if (byName) {
144 return byName.slug;
145 }
146 }
147
148 const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
149 if (!normalizedSelectedModel) {
150 return getDefaultModel(provider);
151 }
152
153 return (
154 options.find((option) => option.slug === normalizedSelectedModel)?.slug ??
155 getDefaultModel(provider)
156 );
157}
158
159export function useAppSettings() {
160 const [settings, setSettings] = useLocalStorage(
161 APP_SETTINGS_STORAGE_KEY,
162 DEFAULT_APP_SETTINGS,
163 AppSettingsSchema,
164 );
165
166 const updateSettings = useCallback(
167 (patch: Partial<AppSettings>) => {
168 setSettings((prev) => normalizeAppSettings({ ...prev, ...patch }));
169 },
170 [setSettings],
171 );
172
173 const resetSettings = useCallback(() => {
174 setSettings(DEFAULT_APP_SETTINGS);
175 }, [setSettings]);
176
177 return {
178 settings,
179 updateSettings,
180 resetSettings,
181 defaults: DEFAULT_APP_SETTINGS,
182 } as const;
183}