-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathappSettings.ts
More file actions
391 lines (357 loc) · 14.4 KB
/
appSettings.ts
File metadata and controls
391 lines (357 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
import { useCallback, useEffect } from "react";
import { Option, Schema } from "effect";
import {
TrimmedNonEmptyString,
type ProviderKind,
type ProviderStartOptions,
} from "@okcode/contracts";
import {
getDefaultModel,
getModelOptions,
normalizeModelSlug,
resolveSelectableModel,
} from "@okcode/shared/model";
import { APP_LOCALE_PREFERENCES } from "./i18n/types";
import { useLocalStorage } from "./hooks/useLocalStorage";
import { EnvMode } from "./components/BranchToolbar.logic";
const APP_SETTINGS_STORAGE_KEY = "okcode:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
const BACKGROUND_IMAGE_KEY = "okcode:background-image";
const BACKGROUND_OPACITY_KEY = "okcode:background-opacity";
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
export type TimestampFormat = typeof TimestampFormat.Type;
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
export const AppLocale = Schema.Literals(APP_LOCALE_PREFERENCES);
export type AppLocale = typeof AppLocale.Type;
export const DEFAULT_APP_LOCALE: AppLocale = "system";
export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
export const PrReviewRequestChangesTone = Schema.Literals(["warning", "brand", "neutral"]);
export type PrReviewRequestChangesTone = typeof PrReviewRequestChangesTone.Type;
export const DEFAULT_PR_REVIEW_REQUEST_CHANGES_TONE: PrReviewRequestChangesTone = "warning";
type CustomModelSettingsKey = "customCodexModels" | "customClaudeModels" | "customOpenClawModels";
export type ProviderCustomModelConfig = {
provider: ProviderKind;
settingsKey: CustomModelSettingsKey;
defaultSettingsKey: CustomModelSettingsKey;
title: string;
description: string;
placeholder: string;
example: string;
};
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
openclaw: new Set(getModelOptions("openclaw").map((option) => option.slug)),
};
const withDefaults =
<
S extends Schema.Top & Schema.WithoutConstructorDefault,
D extends S["~type.make.in"] & S["Encoded"],
>(
fallback: () => D,
) =>
(schema: S) =>
schema.pipe(
Schema.withConstructorDefault(() => Option.some(fallback())),
Schema.withDecodingDefault(() => fallback()),
);
export const AppSettingsSchema = Schema.Struct({
claudeBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
backgroundImageUrl: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
backgroundImageOpacity: Schema.Number.pipe(withDefaults(() => 0.15)),
defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "worktree" as const satisfies EnvMode)),
autoUpdateWorktreeBaseBranch: Schema.Boolean.pipe(withDefaults(() => false)),
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
autoDeleteMergedThreads: Schema.Boolean.pipe(withDefaults(() => false)),
autoDeleteMergedThreadsDelayMinutes: Schema.Number.pipe(withDefaults(() => 5)),
rebaseBeforeCommit: Schema.Boolean.pipe(withDefaults(() => false)),
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
showAuthFailuresAsErrors: Schema.Boolean.pipe(withDefaults(() => true)),
showNotificationDetails: Schema.Boolean.pipe(withDefaults(() => false)),
includeDiagnosticsTipsInCopy: Schema.Boolean.pipe(withDefaults(() => false)),
locale: AppLocale.pipe(withDefaults(() => DEFAULT_APP_LOCALE)),
openLinksExternally: Schema.Boolean.pipe(withDefaults(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
withDefaults(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
),
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
withDefaults(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
),
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
sidebarOpacity: Schema.Number.pipe(withDefaults(() => 1)),
sidebarHideFiles: Schema.Boolean.pipe(withDefaults(() => false)),
sidebarAccentProjectNames: Schema.Boolean.pipe(withDefaults(() => true)),
sidebarAccentColorOverride: Schema.optional(Schema.String.check(Schema.isMaxLength(64))),
sidebarAccentBgColorOverride: Schema.optional(Schema.String.check(Schema.isMaxLength(64))),
prReviewRequestChangesTone: PrReviewRequestChangesTone.pipe(
withDefaults(() => DEFAULT_PR_REVIEW_REQUEST_CHANGES_TONE),
),
showReasoningContent: Schema.Boolean.pipe(withDefaults(() => false)),
showStitchBorder: Schema.Boolean.pipe(withDefaults(() => true)),
codeViewerAutosave: Schema.Boolean.pipe(withDefaults(() => false)),
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
customOpenClawModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
openclawGatewayUrl: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
openclawPassword: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
textGenerationModel: Schema.optional(TrimmedNonEmptyString),
});
export type AppSettings = typeof AppSettingsSchema.Type;
export interface AppModelOption {
slug: string;
name: string;
isCustom: boolean;
}
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConfig> = {
codex: {
provider: "codex",
settingsKey: "customCodexModels",
defaultSettingsKey: "customCodexModels",
title: "Codex",
description: "Save additional Codex model slugs for the picker and `/model` command.",
placeholder: "your-codex-model-slug",
example: "gpt-6.7-codex-ultra-preview",
},
claudeAgent: {
provider: "claudeAgent",
settingsKey: "customClaudeModels",
defaultSettingsKey: "customClaudeModels",
title: "Claude Code",
description: "Save additional Claude model slugs for the picker and `/model` command.",
placeholder: "your-claude-model-slug",
example: "claude-sonnet-5-0",
},
openclaw: {
provider: "openclaw",
settingsKey: "customOpenClawModels",
defaultSettingsKey: "customOpenClawModels",
title: "OpenClaw",
description: "Save additional OpenClaw model slugs for the picker and `/model` command.",
placeholder: "your-openclaw-model-slug",
example: "openclaw/my-custom-model",
},
};
export const MODEL_PROVIDER_SETTINGS = Object.values(PROVIDER_CUSTOM_MODEL_CONFIG);
export function normalizeCustomModelSlugs(
models: Iterable<string | null | undefined>,
provider: ProviderKind = "codex",
): string[] {
const normalizedModels: string[] = [];
const seen = new Set<string>();
const builtInModelSlugs = BUILT_IN_MODEL_SLUGS_BY_PROVIDER[provider];
for (const candidate of models) {
const normalized = normalizeModelSlug(candidate, provider);
if (
!normalized ||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
builtInModelSlugs.has(normalized) ||
seen.has(normalized)
) {
continue;
}
seen.add(normalized);
normalizedModels.push(normalized);
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
break;
}
}
return normalizedModels;
}
function clampOpacity(value: number): number {
return Math.max(0.3, Math.min(1, value));
}
function clampBackgroundOpacity(value: number): number {
return Math.max(0.05, Math.min(1, value));
}
function normalizeAppSettings(settings: AppSettings): AppSettings {
return {
...settings,
backgroundImageUrl: settings.backgroundImageUrl.trim(),
backgroundImageOpacity: clampBackgroundOpacity(settings.backgroundImageOpacity),
sidebarOpacity: clampOpacity(settings.sidebarOpacity),
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
customOpenClawModels: normalizeCustomModelSlugs(settings.customOpenClawModels, "openclaw"),
};
}
export function getCustomModelsForProvider(
settings: Pick<AppSettings, CustomModelSettingsKey>,
provider: ProviderKind,
): readonly string[] {
return settings[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey];
}
export function getDefaultCustomModelsForProvider(
defaults: Pick<AppSettings, CustomModelSettingsKey>,
provider: ProviderKind,
): readonly string[] {
return defaults[PROVIDER_CUSTOM_MODEL_CONFIG[provider].defaultSettingsKey];
}
export function patchCustomModels(
provider: ProviderKind,
models: string[],
): Partial<Pick<AppSettings, CustomModelSettingsKey>> {
return {
[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey]: models,
};
}
export function getCustomModelsByProvider(
settings: Pick<AppSettings, CustomModelSettingsKey>,
): Record<ProviderKind, readonly string[]> {
return {
codex: getCustomModelsForProvider(settings, "codex"),
claudeAgent: getCustomModelsForProvider(settings, "claudeAgent"),
openclaw: getCustomModelsForProvider(settings, "openclaw"),
};
}
export function getAppModelOptions(
provider: ProviderKind,
customModels: readonly string[],
selectedModel?: string | null,
): AppModelOption[] {
const options: AppModelOption[] = getModelOptions(provider).map(({ slug, name }) => ({
slug,
name,
isCustom: false,
}));
const seen = new Set(options.map((option) => option.slug));
const trimmedSelectedModel = selectedModel?.trim().toLowerCase();
for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
if (seen.has(slug)) {
continue;
}
seen.add(slug);
options.push({
slug,
name: slug,
isCustom: true,
});
}
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
const selectedModelMatchesExistingName =
typeof trimmedSelectedModel === "string" &&
options.some((option) => option.name.toLowerCase() === trimmedSelectedModel);
if (
normalizedSelectedModel &&
!seen.has(normalizedSelectedModel) &&
!selectedModelMatchesExistingName
) {
options.push({
slug: normalizedSelectedModel,
name: normalizedSelectedModel,
isCustom: true,
});
}
return options;
}
export function resolveAppModelSelection(
provider: ProviderKind,
customModels: Record<ProviderKind, readonly string[]>,
selectedModel: string | null | undefined,
): string {
const customModelsForProvider = customModels[provider];
const options = getAppModelOptions(provider, customModelsForProvider, selectedModel);
return resolveSelectableModel(provider, selectedModel, options) ?? getDefaultModel(provider);
}
export function getCustomModelOptionsByProvider(
settings: Pick<AppSettings, CustomModelSettingsKey>,
): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
const customModelsByProvider = getCustomModelsByProvider(settings);
return {
codex: getAppModelOptions("codex", customModelsByProvider.codex),
claudeAgent: getAppModelOptions("claudeAgent", customModelsByProvider.claudeAgent),
openclaw: getAppModelOptions("openclaw", customModelsByProvider.openclaw),
};
}
export function getProviderStartOptions(
settings: Pick<
AppSettings,
| "claudeBinaryPath"
| "codexBinaryPath"
| "codexHomePath"
| "openclawGatewayUrl"
| "openclawPassword"
>,
): ProviderStartOptions | undefined {
const providerOptions: ProviderStartOptions = {
...(settings.codexBinaryPath || settings.codexHomePath
? {
codex: {
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
},
}
: {}),
...(settings.claudeBinaryPath
? {
claudeAgent: {
binaryPath: settings.claudeBinaryPath,
},
}
: {}),
...(settings.openclawGatewayUrl || settings.openclawPassword
? {
openclaw: {
...(settings.openclawGatewayUrl ? { gatewayUrl: settings.openclawGatewayUrl } : {}),
...(settings.openclawPassword ? { password: settings.openclawPassword } : {}),
},
}
: {}),
};
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
}
export function useAppSettings() {
const [settings, setSettings] = useLocalStorage(
APP_SETTINGS_STORAGE_KEY,
DEFAULT_APP_SETTINGS,
AppSettingsSchema,
);
const updateSettings = useCallback(
(patch: Partial<AppSettings>) => {
setSettings((prev) => normalizeAppSettings({ ...prev, ...patch }));
},
[setSettings],
);
useEffect(() => {
if (typeof window === "undefined" || settings.backgroundImageUrl.trim().length > 0) {
return;
}
const legacyBackgroundImageUrl =
window.localStorage.getItem(BACKGROUND_IMAGE_KEY)?.trim() ?? "";
if (legacyBackgroundImageUrl.length === 0) {
return;
}
const legacyBackgroundOpacityRaw = window.localStorage.getItem(BACKGROUND_OPACITY_KEY);
const legacyBackgroundOpacity =
legacyBackgroundOpacityRaw === null ? null : Number.parseFloat(legacyBackgroundOpacityRaw);
setSettings((prev) =>
normalizeAppSettings({
...prev,
backgroundImageUrl: legacyBackgroundImageUrl,
backgroundImageOpacity:
typeof legacyBackgroundOpacity === "number" && Number.isFinite(legacyBackgroundOpacity)
? legacyBackgroundOpacity
: prev.backgroundImageOpacity,
}),
);
window.localStorage.removeItem(BACKGROUND_IMAGE_KEY);
window.localStorage.removeItem(BACKGROUND_OPACITY_KEY);
}, [setSettings, settings.backgroundImageUrl]);
const resetSettings = useCallback(() => {
setSettings(DEFAULT_APP_SETTINGS);
}, [setSettings]);
return {
settings,
updateSettings,
resetSettings,
defaults: DEFAULT_APP_SETTINGS,
} as const;
}