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

settings.ts

513 lines20.2 KB

1import * as Effect from "effect/Effect";
2import * as Duration from "effect/Duration";
3import * as Schema from "effect/Schema";
4import * as SchemaTransformation from "effect/SchemaTransformation";
5import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas.ts";
6import { DEFAULT_GIT_TEXT_GENERATION_MODEL, ProviderOptionSelections } from "./model.ts";
7import { ModelSelection } from "./orchestration.ts";
8import { ProviderInstanceConfig, ProviderInstanceId } from "./providerInstance.ts";
9​
10// ── Client Settings (local-only) ───────────────────────────────
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​
16export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
17export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
18export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
19​
20export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
21export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
22export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
23​
24export const SidebarProjectGroupingMode = Schema.Literals([
25 "repository",
26 "repository_path",
27 "separate",
28]);
29export type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type;
30export const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = "repository";
31export const MIN_SIDEBAR_THREAD_PREVIEW_COUNT = 1;
32export const MAX_SIDEBAR_THREAD_PREVIEW_COUNT = 15;
33export const SidebarThreadPreviewCount = Schema.Int.check(
34 Schema.isBetween({
35 minimum: MIN_SIDEBAR_THREAD_PREVIEW_COUNT,
36 maximum: MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
37 }),
38);
39export type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type;
40export const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6;
41​
42export const ClientSettingsSchema = Schema.Struct({
43 autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
44 confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
45 confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
46 dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(
47 Schema.withDecodingDefault(Effect.succeed([])),
48 ),
49 diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
50 diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
51 // Model favorites. Historically keyed by provider kind, now
52 // widened to `ProviderInstanceId` so users can favorite a specific model
53 // on a custom provider instance (e.g. "Codex Personal · gpt-5") without
54 // the UI collapsing it into the same bucket as the default Codex. The
55 // widening is backward-compatible by construction: prior provider-kind
56 // strings satisfy the `ProviderInstanceId` slug schema, so previously
57 // persisted favorites decode unchanged and continue to point at the
58 // default instance for their kind (because `defaultInstanceIdForDriver(kind)`
59 // uses the same slug). The field name is kept as `provider` for storage
60 // stability; new call sites should treat the value as an instance id.
61 favorites: Schema.Array(
62 Schema.Struct({
63 provider: ProviderInstanceId,
64 model: TrimmedNonEmptyString,
65 }),
66 ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
67 providerModelPreferences: Schema.Record(
68 ProviderInstanceId,
69 Schema.Struct({
70 hiddenModels: Schema.Array(Schema.String).pipe(
71 Schema.withDecodingDefault(Effect.succeed([])),
72 ),
73 modelOrder: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
74 }),
75 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
76 sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
77 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
78 ),
79 sidebarProjectGroupingOverrides: Schema.Record(
80 TrimmedNonEmptyString,
81 SidebarProjectGroupingMode,
82 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
83 sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
84 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
85 ),
86 sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
87 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
88 ),
89 sidebarThreadPreviewCount: SidebarThreadPreviewCount.pipe(
90 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT)),
91 ),
92 timestampFormat: TimestampFormat.pipe(
93 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),
94 ),
95});
96export type ClientSettings = typeof ClientSettingsSchema.Type;
97​
98export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});
99​
100// ── Server Settings (server-authoritative) ────────────────────
101​
102export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
103export type ThreadEnvMode = typeof ThreadEnvMode.Type;
104​
105const makeBinaryPathSetting = (fallback: string) =>
106 TrimmedString.pipe(
107 Schema.decodeTo(
108 Schema.String,
109 SchemaTransformation.transformOrFail({
110 decode: (value) => Effect.succeed(value || fallback),
111 encode: (value) => Effect.succeed(value),
112 }),
113 ),
114 Schema.withDecodingDefault(Effect.succeed(fallback)),
115 );
116​
117export type ProviderSettingsFormControl = "text" | "password" | "textarea" | "switch";
118​
119export interface ProviderSettingsFormAnnotation {
120 readonly control?: ProviderSettingsFormControl | undefined;
121 readonly placeholder?: string | undefined;
122 readonly hidden?: boolean | undefined;
123 readonly clearWhenEmpty?: "omit" | "persist" | undefined;
125​
126export interface ProviderSettingsFormSchemaAnnotation {
127 readonly order?: readonly string[] | undefined;
129​
130declare module "effect/Schema" {
131 namespace Annotations {
132 interface Annotations {
133 readonly providerSettingsForm?: ProviderSettingsFormAnnotation | undefined;
134 readonly providerSettingsFormSchema?: ProviderSettingsFormSchemaAnnotation | undefined;
135 }
136 }
138​
139export type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<
140 keyof Fields,
141 string
142>[];
143​
144export function makeProviderSettingsSchema<const Fields extends Schema.Struct.Fields>(
145 fields: Fields,
146 options?: {
147 readonly order?: ProviderSettingsOrder<Fields> | undefined;
148 },
149): Schema.Struct<Fields> {
150 return Schema.Struct(fields).pipe(
151 Schema.annotate({
152 providerSettingsFormSchema:
153 options?.order === undefined ? undefined : { order: options.order },
154 }),
155 );
157​
158export const CodexSettings = makeProviderSettingsSchema(
159 {
160 enabled: Schema.Boolean.pipe(
161 Schema.withDecodingDefault(Effect.succeed(true)),
162 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
163 ),
164 binaryPath: makeBinaryPathSetting("codex").pipe(
165 Schema.annotateKey({
166 title: "Binary path",
167 description: "Path to the Codex binary used by this instance.",
168 providerSettingsForm: { placeholder: "codex", clearWhenEmpty: "omit" },
169 }),
170 ),
171 homePath: TrimmedString.pipe(
172 Schema.withDecodingDefault(Effect.succeed("")),
173 Schema.annotateKey({
174 title: "CODEX_HOME path",
175 description: "Custom Codex home and config directory.",
176 providerSettingsForm: {
177 placeholder: "~/.codex",
178 clearWhenEmpty: "omit",
179 },
180 }),
181 ),
182 shadowHomePath: TrimmedString.pipe(
183 Schema.withDecodingDefault(Effect.succeed("")),
184 Schema.annotateKey({
185 title: "Shadow home path",
186 description:
187 "Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
188 providerSettingsForm: {
189 placeholder: "~/.codex-t3/personal",
190 clearWhenEmpty: "omit",
191 },
192 }),
193 ),
194 customModels: Schema.Array(Schema.String).pipe(
195 Schema.withDecodingDefault(Effect.succeed([])),
196 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
197 ),
198 },
199 {
200 order: ["binaryPath", "homePath", "shadowHomePath"],
201 },
202);
203export type CodexSettings = typeof CodexSettings.Type;
204​
205export const ClaudeSettings = makeProviderSettingsSchema(
206 {
207 enabled: Schema.Boolean.pipe(
208 Schema.withDecodingDefault(Effect.succeed(true)),
209 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
210 ),
211 binaryPath: makeBinaryPathSetting("claude").pipe(
212 Schema.annotateKey({
213 title: "Binary path",
214 description: "Path to the Claude binary used by this instance.",
215 providerSettingsForm: { placeholder: "claude", clearWhenEmpty: "omit" },
216 }),
217 ),
218 homePath: TrimmedString.pipe(
219 Schema.withDecodingDefault(Effect.succeed("")),
220 Schema.annotateKey({
221 title: "Claude HOME path",
222 description:
223 "Custom HOME used when running this Claude instance. Keeps .claude.json and .claude separate.",
224 providerSettingsForm: { placeholder: "~", clearWhenEmpty: "omit" },
225 }),
226 ),
227 customModels: Schema.Array(Schema.String).pipe(
228 Schema.withDecodingDefault(Effect.succeed([])),
229 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
230 ),
231 launchArgs: Schema.String.pipe(
232 Schema.withDecodingDefault(Effect.succeed("")),
233 Schema.annotateKey({
234 title: "Launch arguments",
235 description: "Additional CLI arguments passed on session start.",
236 providerSettingsForm: {
237 placeholder: "e.g. --chrome",
238 clearWhenEmpty: "omit",
239 },
240 }),
241 ),
242 },
243 {
244 order: ["binaryPath", "homePath", "launchArgs"],
245 },
246);
247export type ClaudeSettings = typeof ClaudeSettings.Type;
248​
249export const CursorSettings = makeProviderSettingsSchema(
250 {
251 enabled: Schema.Boolean.pipe(
252 Schema.withDecodingDefault(Effect.succeed(false)),
253 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
254 ),
255 binaryPath: makeBinaryPathSetting("agent").pipe(
256 Schema.annotateKey({
257 title: "Binary path",
258 description: "Path to the Cursor agent binary.",
259 providerSettingsForm: { placeholder: "agent", clearWhenEmpty: "omit" },
260 }),
261 ),
262 apiEndpoint: TrimmedString.pipe(
263 Schema.withDecodingDefault(Effect.succeed("")),
264 Schema.annotateKey({
265 title: "API endpoint",
266 description: "Override the Cursor API endpoint for this instance.",
267 providerSettingsForm: {
268 placeholder: "https://...",
269 clearWhenEmpty: "omit",
270 },
271 }),
272 ),
273 customModels: Schema.Array(Schema.String).pipe(
274 Schema.withDecodingDefault(Effect.succeed([])),
275 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
276 ),
277 },
278 {
279 order: ["binaryPath", "apiEndpoint"],
280 },
281);
282export type CursorSettings = typeof CursorSettings.Type;
283​
284export const OpenCodeSettings = makeProviderSettingsSchema(
285 {
286 enabled: Schema.Boolean.pipe(
287 Schema.withDecodingDefault(Effect.succeed(true)),
288 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
289 ),
290 binaryPath: makeBinaryPathSetting("opencode").pipe(
291 Schema.annotateKey({
292 title: "Binary path",
293 description: "Path to the OpenCode binary.",
294 providerSettingsForm: {
295 placeholder: "opencode",
296 clearWhenEmpty: "omit",
297 },
298 }),
299 ),
300 serverUrl: TrimmedString.pipe(
301 Schema.withDecodingDefault(Effect.succeed("")),
302 Schema.annotateKey({
303 title: "Server URL",
304 description: "Leave blank to let T3 Code spawn the server when needed.",
305 providerSettingsForm: {
306 placeholder: "http://127.0.0.1:4096",
307 clearWhenEmpty: "omit",
308 },
309 }),
310 ),
311 serverPassword: TrimmedString.pipe(
312 Schema.withDecodingDefault(Effect.succeed("")),
313 Schema.annotateKey({
314 title: "Server password",
315 description: "Stored in plain text on disk.",
316 providerSettingsForm: {
317 control: "password",
318 placeholder: "Optional",
319 clearWhenEmpty: "omit",
320 },
321 }),
322 ),
323 customModels: Schema.Array(Schema.String).pipe(
324 Schema.withDecodingDefault(Effect.succeed([])),
325 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
326 ),
327 },
328 {
329 order: ["binaryPath", "serverUrl", "serverPassword"],
330 },
331);
332export type OpenCodeSettings = typeof OpenCodeSettings.Type;
333​
334export const ObservabilitySettings = Schema.Struct({
335 otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
336 otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
337});
338export type ObservabilitySettings = typeof ObservabilitySettings.Type;
339​
340export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
341​
342export const ServerSettings = Schema.Struct({
343 enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
344 automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
345 Schema.withDecodingDefault(
346 Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
347 ),
348 ),
349 defaultThreadEnvMode: ThreadEnvMode.pipe(
350 Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
351 ),
352 addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
353 textGenerationModelSelection: ModelSelection.pipe(
354 Schema.withDecodingDefault(
355 Effect.succeed({
356 instanceId: ProviderInstanceId.make("codex"),
357 model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
358 }),
359 ),
360 ),
361​
362 // Legacy single-instance-per-driver settings. Continues to be the source
363 // of truth until `providerInstances` (below) lands per-driver migration
364 // shims and the server starts hydrating instances from it. Driver-specific
365 // schemas live here for the duration of the migration; once each driver
366 // owns its config in its own package, this struct shrinks to nothing and
367 // is removed entirely.
368 providers: Schema.Struct({
369 codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
370 claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
371 cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
372 opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
373 }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
374 // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
375 // are `ProviderInstanceConfig` envelopes. The driver-specific config blob
376 // is `Schema.Unknown` at this layer so envelopes with unknown drivers
377 // (forks, downgrades, in-flight PR branches) round-trip without loss.
378 // See providerInstance.ts for the forward/backward compatibility invariant.
379 providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
380 Schema.withDecodingDefault(Effect.succeed({})),
381 ),
382 observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
383});
384export type ServerSettings = typeof ServerSettings.Type;
385​
386export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});
387​
388export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
389 "ServerSettingsError",
390 {
391 settingsPath: Schema.String,
392 detail: Schema.String,
393 cause: Schema.optional(Schema.Defect),
394 },
395) {
396 override get message(): string {
397 return `Server settings error at ${this.settingsPath}: ${this.detail}`;
398 }
400​
401// ── Unified type ─────────────────────────────────────────────────────
402​
403export type UnifiedSettings = ServerSettings & ClientSettings;
404export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {
405 ...DEFAULT_SERVER_SETTINGS,
406 ...DEFAULT_CLIENT_SETTINGS,
407};
408​
409// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────
410​
411const ModelSelectionPatch = Schema.Struct({
412 instanceId: Schema.optionalKey(ProviderInstanceId),
413 model: Schema.optionalKey(TrimmedNonEmptyString),
414 options: Schema.optionalKey(ProviderOptionSelections),
415});
416​
417const CodexSettingsPatch = Schema.Struct({
418 enabled: Schema.optionalKey(Schema.Boolean),
419 binaryPath: Schema.optionalKey(TrimmedString),
420 homePath: Schema.optionalKey(TrimmedString),
421 shadowHomePath: Schema.optionalKey(TrimmedString),
422 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
423});
424​
425const ClaudeSettingsPatch = Schema.Struct({
426 enabled: Schema.optionalKey(Schema.Boolean),
427 binaryPath: Schema.optionalKey(TrimmedString),
428 homePath: Schema.optionalKey(TrimmedString),
429 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
430 launchArgs: Schema.optionalKey(TrimmedString),
431});
432​
433const CursorSettingsPatch = Schema.Struct({
434 enabled: Schema.optionalKey(Schema.Boolean),
435 binaryPath: Schema.optionalKey(TrimmedString),
436 apiEndpoint: Schema.optionalKey(TrimmedString),
437 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
438});
439​
440const OpenCodeSettingsPatch = Schema.Struct({
441 enabled: Schema.optionalKey(Schema.Boolean),
442 binaryPath: Schema.optionalKey(TrimmedString),
443 serverUrl: Schema.optionalKey(TrimmedString),
444 serverPassword: Schema.optionalKey(TrimmedString),
445 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
446});
447​
448export const ServerSettingsPatch = Schema.Struct({
449 // Server settings
450 enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
451 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
452 defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
453 addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
454 textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
455 observability: Schema.optionalKey(
456 Schema.Struct({
457 otlpTracesUrl: Schema.optionalKey(TrimmedString),
458 otlpMetricsUrl: Schema.optionalKey(TrimmedString),
459 }),
460 ),
461 providers: Schema.optionalKey(
462 Schema.Struct({
463 codex: Schema.optionalKey(CodexSettingsPatch),
464 claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
465 cursor: Schema.optionalKey(CursorSettingsPatch),
466 opencode: Schema.optionalKey(OpenCodeSettingsPatch),
467 }),
468 ),
469 // Whole-map replacement for the new instance config. Patching individual
470 // entries is intentionally out of scope: the map is small, and partial
471 // patches risk leaving driver-specific config in a half-merged state.
472 // The web UI sends a fully-formed map every time it edits this field.
473 providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),
474});
475export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
476​
477export const ClientSettingsPatch = Schema.Struct({
478 autoOpenPlanSidebar: Schema.optionalKey(Schema.Boolean),
479 confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
480 confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
481 diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
482 diffWordWrap: Schema.optionalKey(Schema.Boolean),
483 favorites: Schema.optionalKey(
484 Schema.Array(
485 Schema.Struct({
486 provider: ProviderInstanceId,
487 model: TrimmedNonEmptyString,
488 }),
489 ),
490 ),
491 providerModelPreferences: Schema.optionalKey(
492 Schema.Record(
493 ProviderInstanceId,
494 Schema.Struct({
495 hiddenModels: Schema.Array(Schema.String).pipe(
496 Schema.withDecodingDefault(Effect.succeed([])),
497 ),
498 modelOrder: Schema.Array(Schema.String).pipe(
499 Schema.withDecodingDefault(Effect.succeed([])),
500 ),
501 }),
502 ),
503 ),
504 sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
505 sidebarProjectGroupingOverrides: Schema.optionalKey(
506 Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
507 ),
508 sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),
509 sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),
510 sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),
511 timestampFormat: Schema.optionalKey(TimestampFormat),
512});
513export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;