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

settings.ts

917 lines38.3 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 { ThreadEnvMode } from "./environment.ts";
7import {
8 DEFAULT_TEXT_GENERATION_MODEL,
9 DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
10 ProviderOptionSelections,
11} from "./model.ts";
12import { ModelSelection } from "./orchestration.ts";
13import {
14 DEFAULT_PREVIEW_APPEARANCE,
15 DEFAULT_PREVIEW_ZOOM_FACTOR,
16 FILL_PREVIEW_VIEWPORT,
17 PreviewAppearancePreference,
18 PreviewViewportSetting,
19 PreviewZoomFactor,
20} from "./preview.ts";
21import {
22 ProviderInstanceConfig,
23 ProviderInstanceId,
24 type ProviderDriverKind,
25} from "./providerInstance.ts";
26​
27// ── Client Settings (local-only) ───────────────────────────────
28​
29export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
30export type TimestampFormat = typeof TimestampFormat.Type;
31export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
32​
33export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
34export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
35export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
36​
37export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
38export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
39export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
40​
41export const SidebarProjectGroupingMode = Schema.Literals([
42 "repository",
43 "repository_path",
44 "separate",
45]);
46export type SidebarProjectGroupingMode = typeof SidebarProjectGroupingMode.Type;
47export const DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE: SidebarProjectGroupingMode = "repository";
48export const MIN_SIDEBAR_THREAD_PREVIEW_COUNT = 1;
49export const MAX_SIDEBAR_THREAD_PREVIEW_COUNT = 15;
50export const SidebarThreadPreviewCount = Schema.Int.check(
51 Schema.isBetween({
52 minimum: MIN_SIDEBAR_THREAD_PREVIEW_COUNT,
53 maximum: MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
54 }),
55);
56export type SidebarThreadPreviewCount = typeof SidebarThreadPreviewCount.Type;
57export const DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT: SidebarThreadPreviewCount = 6;
58export const MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 1;
59export const MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS = 90;
60export const SidebarAutoSettleAfterDays = Schema.Number.check(
61 Schema.isBetween({
62 minimum: MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
63 maximum: MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
64 }),
65);
66export type SidebarAutoSettleAfterDays = typeof SidebarAutoSettleAfterDays.Type;
67export const DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS: SidebarAutoSettleAfterDays = 3;
68export const MIN_GLASS_OPACITY = 40;
69export const MAX_GLASS_OPACITY = 100;
70export const GlassOpacity = Schema.Int.check(
71 Schema.isBetween({
72 minimum: MIN_GLASS_OPACITY,
73 maximum: MAX_GLASS_OPACITY,
74 }),
75);
76export type GlassOpacity = typeof GlassOpacity.Type;
77export const DEFAULT_GLASS_OPACITY: GlassOpacity = 80;
78/**
79 * Font size preferences, in CSS pixels. The ranges are deliberately narrow:
80 * the interface size scales every rem-based dimension in the app, so the
81 * bounds keep layouts intact rather than offering unusable extremes.
82 */
83export const MIN_INTERFACE_FONT_SIZE = 12;
84export const MAX_INTERFACE_FONT_SIZE = 20;
85export const InterfaceFontSize = Schema.Int.check(
86 Schema.isBetween({ minimum: MIN_INTERFACE_FONT_SIZE, maximum: MAX_INTERFACE_FONT_SIZE }),
87);
88export type InterfaceFontSize = typeof InterfaceFontSize.Type;
89export const DEFAULT_INTERFACE_FONT_SIZE: InterfaceFontSize = 16;
90​
91export const MIN_PROMPT_FONT_SIZE = 12;
92export const MAX_PROMPT_FONT_SIZE = 20;
93export const PromptFontSize = Schema.Int.check(
94 Schema.isBetween({ minimum: MIN_PROMPT_FONT_SIZE, maximum: MAX_PROMPT_FONT_SIZE }),
95);
96export type PromptFontSize = typeof PromptFontSize.Type;
97export const DEFAULT_PROMPT_FONT_SIZE: PromptFontSize = 14;
98​
99export const MIN_CODE_FONT_SIZE = 10;
100export const MAX_CODE_FONT_SIZE = 18;
101export const CodeFontSize = Schema.Int.check(
102 Schema.isBetween({ minimum: MIN_CODE_FONT_SIZE, maximum: MAX_CODE_FONT_SIZE }),
103);
104export type CodeFontSize = typeof CodeFontSize.Type;
105export const DEFAULT_CODE_FONT_SIZE: CodeFontSize = 13;
106​
107export const MIN_TERMINAL_FONT_SIZE = 8;
108export const MAX_TERMINAL_FONT_SIZE = 20;
109export const TerminalFontSize = Schema.Int.check(
110 Schema.isBetween({ minimum: MIN_TERMINAL_FONT_SIZE, maximum: MAX_TERMINAL_FONT_SIZE }),
111);
112export type TerminalFontSize = typeof TerminalFontSize.Type;
113export const DEFAULT_TERMINAL_FONT_SIZE: TerminalFontSize = 12;
114​
115export const EnvironmentIdentificationMode = Schema.Literals(["artwork", "pill", "none"]);
116export type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type;
117export const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = "artwork";
118​
119/**
120 * A user-chosen font family (a single name or a comma-separated list). Empty
121 * means "use the app default"; clients compose their own fallback stacks.
122 */
123export const FontFamilyPreference = Schema.String.check(Schema.isMaxLength(200));
124export type FontFamilyPreference = typeof FontFamilyPreference.Type;
125​
126/**
127 * Defaults for the in-app preview browser, applied whenever a tab is opened
128 * without an explicit viewport/zoom/appearance — by the user opening a browser
129 * tab, or by an agent calling `preview_open` with no size. Client-local
130 * because the Chromium guest they configure is desktop-local.
131 */
132export const DEFAULT_BROWSER_VIEWPORT: PreviewViewportSetting = FILL_PREVIEW_VIEWPORT;
133export const DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW = true;
134​
135export const ClientSettingsSchema = Schema.Struct({
136 browserDefaultViewport: PreviewViewportSetting.pipe(
137 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_VIEWPORT)),
138 ),
139 browserDefaultZoomFactor: PreviewZoomFactor.pipe(
140 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PREVIEW_ZOOM_FACTOR)),
141 ),
142 browserDefaultAppearance: PreviewAppearancePreference.pipe(
143 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PREVIEW_APPEARANCE)),
144 ),
145 /**
146 * Whether an agent opening a preview pops the floating mini player into
147 * view. Only applies when the agent didn't ask either way — an explicit
148 * `open`/`show` on `preview_open` still wins, since that is the agent
149 * deliberately showing or hiding its work.
150 */
151 browserAutoShowFloatingPreview: Schema.Boolean.pipe(
152 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW)),
153 ),
154 // Desktop-only: require holding the quit shortcut (Cmd/Ctrl+Q) before the
155 // app quits; a quick tap only shows a hint. Browser clients ignore it.
156 confirmQuit: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
157 confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
158 confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
159 dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(
160 Schema.withDecodingDefault(Effect.succeed([])),
161 ),
162 diffIgnoreWhitespace: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
163 environmentIdentificationMode: EnvironmentIdentificationMode.pipe(
164 Schema.withDecodingDefault(Effect.succeed(DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE)),
165 ),
166 glassOpacity: GlassOpacity.pipe(
167 Schema.withDecodingDefault(Effect.succeed(DEFAULT_GLASS_OPACITY)),
168 ),
169 fontSizeInterface: InterfaceFontSize.pipe(
170 Schema.withDecodingDefault(Effect.succeed(DEFAULT_INTERFACE_FONT_SIZE)),
171 ),
172 fontSizePrompt: PromptFontSize.pipe(
173 Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROMPT_FONT_SIZE)),
174 ),
175 fontSizeCode: CodeFontSize.pipe(
176 Schema.withDecodingDefault(Effect.succeed(DEFAULT_CODE_FONT_SIZE)),
177 ),
178 fontSizeTerminal: TerminalFontSize.pipe(
179 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TERMINAL_FONT_SIZE)),
180 ),
181 fontFamilyCode: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
182 fontFamilyComposer: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
183 fontFamilySans: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
184 fontFamilyTerminal: FontFamilyPreference.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
185 // Grayscale `-webkit-font-smoothing: antialiased` (thinner strokes);
186 // disabling restores the platform's heavier default. No effect off macOS.
187 fontSmoothing: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
188 // Model favorites. Historically keyed by provider kind, now
189 // widened to `ProviderInstanceId` so users can favorite a specific model
190 // on a custom provider instance (e.g. "Codex Personal · gpt-5") without
191 // the UI collapsing it into the same bucket as the default Codex. The
192 // widening is backward-compatible by construction: prior provider-kind
193 // strings satisfy the `ProviderInstanceId` slug schema, so previously
194 // persisted favorites decode unchanged and continue to point at the
195 // default instance for their kind (because `defaultInstanceIdForDriver(kind)`
196 // uses the same slug). The field name is kept as `provider` for storage
197 // stability; new call sites should treat the value as an instance id.
198 favorites: Schema.Array(
199 Schema.Struct({
200 provider: ProviderInstanceId,
201 model: TrimmedNonEmptyString,
202 }),
203 ).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
204 providerModelPreferences: Schema.Record(
205 ProviderInstanceId,
206 Schema.Struct({
207 hiddenModels: Schema.Array(Schema.String).pipe(
208 Schema.withDecodingDefault(Effect.succeed([])),
209 ),
210 modelOrder: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
211 }),
212 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
213 // Legacy plan mode. The composer's Build/Plan toggle was removed from the
214 // default UI; this beta flag restores it (plus the /plan and /default slash
215 // commands) for users who still rely on the old workflow.
216 planModeEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
217 // Legacy sidebar (the original per-project tree). Deliberately a fresh key
218 // (was `sidebarV2Enabled` + `sidebarV2ConfiguredByUser`): decoding drops the
219 // old keys, so everyone, including prior beta opt-outs, resets to the new
220 // default sidebar.
221 legacySidebarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
222 sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
223 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
224 ),
225 sidebarAutoSettleOnMerge: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
226 sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe(
227 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)),
228 ),
229 sidebarProjectGroupingOverrides: Schema.Record(
230 TrimmedNonEmptyString,
231 SidebarProjectGroupingMode,
232 ).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
233 sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
234 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER)),
235 ),
236 sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
237 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_SORT_ORDER)),
238 ),
239 sidebarThreadPreviewCount: SidebarThreadPreviewCount.pipe(
240 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_THREAD_PREVIEW_COUNT)),
241 ),
242 timestampFormat: TimestampFormat.pipe(
243 Schema.withDecodingDefault(Effect.succeed(DEFAULT_TIMESTAMP_FORMAT)),
244 ),
245 wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
246});
247export type ClientSettings = typeof ClientSettingsSchema.Type;
248​
249export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});
250​
251// ── Server Settings (server-authoritative) ────────────────────
252​
253// Moved to environment.ts so orchestration contracts can use it without an
254// import cycle; re-exported here for compatibility with deep imports.
255export { ThreadEnvMode } from "./environment.ts";
256​
257const makeBinaryPathSetting = (fallback: string) =>
258 TrimmedString.pipe(
259 Schema.decodeTo(
260 Schema.String,
261 SchemaTransformation.transformOrFail({
262 decode: (value) => Effect.succeed(value || fallback),
263 encode: (value) => Effect.succeed(value),
264 }),
265 ),
266 Schema.withDecodingDefault(Effect.succeed(fallback)),
267 );
268​
269export type ProviderSettingsFormControl = "text" | "password" | "textarea" | "switch";
270​
271export interface ProviderSettingsFormAnnotation {
272 readonly control?: ProviderSettingsFormControl | undefined;
273 readonly placeholder?: string | undefined;
274 readonly hidden?: boolean | undefined;
275 readonly clearWhenEmpty?: "omit" | "persist" | undefined;
277​
278export interface ProviderSettingsFormSchemaAnnotation {
279 readonly order?: readonly string[] | undefined;
281​
282declare module "effect/Schema" {
283 namespace Annotations {
284 interface Annotations {
285 readonly providerSettingsForm?: ProviderSettingsFormAnnotation | undefined;
286 readonly providerSettingsFormSchema?: ProviderSettingsFormSchemaAnnotation | undefined;
287 }
288 }
290​
291export type ProviderSettingsOrder<Fields extends Schema.Struct.Fields> = readonly Extract<
292 keyof Fields,
293 string
294>[];
295​
296export function makeProviderSettingsSchema<const Fields extends Schema.Struct.Fields>(
297 fields: Fields,
298 options?: {
299 readonly order?: ProviderSettingsOrder<Fields> | undefined;
300 },
301): Schema.Struct<Fields> {
302 return Schema.Struct(fields).pipe(
303 Schema.annotate({
304 providerSettingsFormSchema:
305 options?.order === undefined ? undefined : { order: options.order },
306 }),
307 );
309​
310export const CodexSettings = makeProviderSettingsSchema(
311 {
312 enabled: Schema.Boolean.pipe(
313 Schema.withDecodingDefault(Effect.succeed(true)),
314 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
315 ),
316 binaryPath: makeBinaryPathSetting("codex").pipe(
317 Schema.annotateKey({
318 title: "Binary path",
319 description: "Path to the Codex binary used by this instance.",
320 providerSettingsForm: { placeholder: "codex", clearWhenEmpty: "omit" },
321 }),
322 ),
323 homePath: TrimmedString.pipe(
324 Schema.withDecodingDefault(Effect.succeed("")),
325 Schema.annotateKey({
326 title: "CODEX_HOME path",
327 description: "Custom Codex home and config directory.",
328 providerSettingsForm: {
329 placeholder: "~/.codex",
330 clearWhenEmpty: "omit",
331 },
332 }),
333 ),
334 shadowHomePath: TrimmedString.pipe(
335 Schema.withDecodingDefault(Effect.succeed("")),
336 Schema.annotateKey({
337 title: "Shadow home path",
338 description:
339 "Account-specific Codex home. Keeps auth.json separate while sharing state from CODEX_HOME.",
340 providerSettingsForm: {
341 placeholder: "~/.codex-t3/personal",
342 clearWhenEmpty: "omit",
343 },
344 }),
345 ),
346 launchArgs: TrimmedString.pipe(
347 Schema.withDecodingDefault(Effect.succeed("")),
348 Schema.annotateKey({
349 title: "Launch arguments",
350 description: "Additional CLI arguments passed to codex app-server on session start.",
351 }),
352 ),
353 customModels: Schema.Array(Schema.String).pipe(
354 Schema.withDecodingDefault(Effect.succeed([])),
355 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
356 ),
357 },
358 {
359 order: ["binaryPath", "homePath", "shadowHomePath", "launchArgs"],
360 },
361);
362export type CodexSettings = typeof CodexSettings.Type;
363​
364export const ClaudeSettings = makeProviderSettingsSchema(
365 {
366 enabled: Schema.Boolean.pipe(
367 Schema.withDecodingDefault(Effect.succeed(true)),
368 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
369 ),
370 binaryPath: makeBinaryPathSetting("claude").pipe(
371 Schema.annotateKey({
372 title: "Binary path",
373 description: "Path to the Claude binary used by this instance.",
374 providerSettingsForm: { placeholder: "claude", clearWhenEmpty: "omit" },
375 }),
376 ),
377 homePath: TrimmedString.pipe(
378 Schema.withDecodingDefault(Effect.succeed("")),
379 Schema.annotateKey({
380 title: "CLAUDE_CONFIG_DIR path",
381 description:
382 "Custom Claude home and config directory. Keeps .claude.json and .claude separate.",
383 providerSettingsForm: { placeholder: "~/.claude", clearWhenEmpty: "omit" },
384 }),
385 ),
386 customModels: Schema.Array(Schema.String).pipe(
387 Schema.withDecodingDefault(Effect.succeed([])),
388 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
389 ),
390 launchArgs: Schema.String.pipe(
391 Schema.withDecodingDefault(Effect.succeed("")),
392 Schema.annotateKey({
393 title: "Launch arguments",
394 description: "Additional CLI arguments passed on session start.",
395 providerSettingsForm: {
396 placeholder: "e.g. --chrome",
397 clearWhenEmpty: "omit",
398 },
399 }),
400 ),
401 },
402 {
403 order: ["binaryPath", "homePath", "launchArgs"],
404 },
405);
406export type ClaudeSettings = typeof ClaudeSettings.Type;
407​
408export const CursorSettings = makeProviderSettingsSchema(
409 {
410 // Enabled by default alongside Codex and Claude Agent.
411 enabled: Schema.Boolean.pipe(
412 Schema.withDecodingDefault(Effect.succeed(true)),
413 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
414 ),
415 binaryPath: makeBinaryPathSetting("cursor-agent").pipe(
416 Schema.annotateKey({
417 title: "Binary path",
418 description: "Path to the Cursor agent binary.",
419 providerSettingsForm: { placeholder: "cursor-agent", clearWhenEmpty: "omit" },
420 }),
421 ),
422 apiEndpoint: TrimmedString.pipe(
423 Schema.withDecodingDefault(Effect.succeed("")),
424 Schema.annotateKey({
425 title: "API endpoint",
426 description: "Override the Cursor API endpoint for this instance.",
427 providerSettingsForm: {
428 placeholder: "https://...",
429 clearWhenEmpty: "omit",
430 },
431 }),
432 ),
433 customModels: Schema.Array(Schema.String).pipe(
434 Schema.withDecodingDefault(Effect.succeed([])),
435 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
436 ),
437 },
438 {
439 order: ["binaryPath", "apiEndpoint"],
440 },
441);
442export type CursorSettings = typeof CursorSettings.Type;
443​
444export const GrokSettings = makeProviderSettingsSchema(
445 {
446 // Off by default (like Cursor and OpenCode): the binding is not yet
447 // stable enough to probe on every install. Users opt in from Settings.
448 enabled: Schema.Boolean.pipe(
449 Schema.withDecodingDefault(Effect.succeed(false)),
450 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
451 ),
452 binaryPath: makeBinaryPathSetting("grok").pipe(
453 Schema.annotateKey({
454 title: "Binary path",
455 description: "Path to the Grok CLI binary.",
456 providerSettingsForm: { placeholder: "grok", clearWhenEmpty: "omit" },
457 }),
458 ),
459 customModels: Schema.Array(Schema.String).pipe(
460 Schema.withDecodingDefault(Effect.succeed([])),
461 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
462 ),
463 },
464 {
465 order: ["binaryPath"],
466 },
467);
468export type GrokSettings = typeof GrokSettings.Type;
469​
470export const OpenCodeSettings = makeProviderSettingsSchema(
471 {
472 // Off by default (like Cursor and Grok): the binding is not yet stable
473 // enough to probe on every install. Users opt in from Settings.
474 enabled: Schema.Boolean.pipe(
475 Schema.withDecodingDefault(Effect.succeed(false)),
476 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
477 ),
478 binaryPath: makeBinaryPathSetting("opencode").pipe(
479 Schema.annotateKey({
480 title: "Binary path",
481 description: "Path to the OpenCode binary.",
482 providerSettingsForm: {
483 placeholder: "opencode",
484 clearWhenEmpty: "omit",
485 },
486 }),
487 ),
488 serverUrl: TrimmedString.pipe(
489 Schema.withDecodingDefault(Effect.succeed("")),
490 Schema.annotateKey({
491 title: "Server URL",
492 description: "Leave blank to let T3 Code spawn the server when needed.",
493 providerSettingsForm: {
494 placeholder: "http://127.0.0.1:4096",
495 clearWhenEmpty: "omit",
496 },
497 }),
498 ),
499 serverPassword: TrimmedString.pipe(
500 Schema.withDecodingDefault(Effect.succeed("")),
501 Schema.annotateKey({
502 title: "Server password",
503 description: "Stored in plain text on disk.",
504 providerSettingsForm: {
505 control: "password",
506 placeholder: "Optional",
507 clearWhenEmpty: "omit",
508 },
509 }),
510 ),
511 customModels: Schema.Array(Schema.String).pipe(
512 Schema.withDecodingDefault(Effect.succeed([])),
513 Schema.annotateKey({ providerSettingsForm: { hidden: true } }),
514 ),
515 },
516 {
517 order: ["binaryPath", "serverUrl", "serverPassword"],
518 },
519);
520export type OpenCodeSettings = typeof OpenCodeSettings.Type;
521​
522export const ObservabilitySettings = Schema.Struct({
523 otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
524 otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
525});
526export type ObservabilitySettings = typeof ObservabilitySettings.Type;
527​
528export const SourceControlWritingStyleMode = Schema.Literals([
529 "repo_conventions",
530 "conventional_commits",
531 "custom",
532]);
533export type SourceControlWritingStyleMode = typeof SourceControlWritingStyleMode.Type;
534​
535export const SourceControlWritingStyleSettings = Schema.Struct({
536 mode: SourceControlWritingStyleMode.pipe(
537 Schema.withDecodingDefault(Effect.succeed("repo_conventions" as const)),
538 ),
539 customInstructions: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
540 followChangeRequestTemplates: Schema.Boolean.pipe(
541 Schema.withDecodingDefault(Effect.succeed(true)),
542 ),
543});
544export type SourceControlWritingStyleSettings = typeof SourceControlWritingStyleSettings.Type;
545​
546export const DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL = Duration.seconds(30);
547export const DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL = Duration.minutes(5);
548​
549export const BackgroundActivityProfile = Schema.Literals([
550 "balanced",
551 "performance",
552 "battery-saver",
553]);
554export type BackgroundActivityProfile = typeof BackgroundActivityProfile.Type;
555export const DEFAULT_BACKGROUND_ACTIVITY_PROFILE: BackgroundActivityProfile = "balanced";
556​
557export const BackgroundActivityProfileSelection = Schema.Literals([
558 "balanced",
559 "performance",
560 "battery-saver",
561 "custom",
562]);
563export type BackgroundActivityProfileSelection = typeof BackgroundActivityProfileSelection.Type;
564​
565export const BackgroundActivityOverrides = Schema.Struct({
566 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
567 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
568 hostPowerMonitorActiveInterval: Schema.optionalKey(Schema.DurationFromMillis),
569 hostPowerMonitorIdleInterval: Schema.optionalKey(Schema.DurationFromMillis),
570 idleClientTtl: Schema.optionalKey(Schema.DurationFromMillis),
571 pauseWhenHostLocked: Schema.optionalKey(Schema.Boolean),
572 pauseWhenHostLowPower: Schema.optionalKey(Schema.Boolean),
573 pauseWhenClientLowPower: Schema.optionalKey(Schema.Boolean),
574 pauseWhenOnBattery: Schema.optionalKey(Schema.Boolean),
575});
576export type BackgroundActivityOverrides = typeof BackgroundActivityOverrides.Type;
577​
578export const BackgroundActivitySettings = Schema.Struct({
579 schemaVersion: Schema.Literal(1).pipe(Schema.withDecodingDefault(Effect.succeed(1 as const))),
580 profile: BackgroundActivityProfileSelection.pipe(
581 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
582 ),
583 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
584 overrides: BackgroundActivityOverrides.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
585}).pipe(Schema.withDecodingDefault(Effect.succeed({})));
586export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
587​
588export const ServerSettings = Schema.Struct({
589 // Legacy token-by-token assistant output. Deliberately a fresh key (was
590 // `enableAssistantStreaming`): decoding drops the old key, so everyone,
591 // including prior opt-ins, resets to the buffered default.
592 enableLegacyTokenStreaming: Schema.Boolean.pipe(
593 Schema.withDecodingDefault(Effect.succeed(false)),
594 ),
595 enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
596 /**
597 * Whether agents may drive the in-app preview browser. Turning this off
598 * withholds the MCP credential, so the `t3-code` server (and with it every
599 * `preview_*` tool) is never attached to a provider session, and the prompt
600 * text describing those tools is dropped along with them. The user's own
601 * browser panel is unaffected — this gates agent access only.
602 *
603 * Server-authoritative rather than client-local: tool injection and prompt
604 * construction both happen on the server, and the answer must not differ
605 * between a desktop window and a phone attached to the same server.
606 */
607 enableAgentBrowserAccess: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
608 backgroundActivity: BackgroundActivitySettings,
609 // Legacy flat fields retained for old settings files and old clients. New
610 // consumers should resolve `backgroundActivity` instead.
611 automaticGitFetchInterval: Schema.DurationFromMillis.pipe(
612 Schema.withDecodingDefault(
613 Effect.succeed(Duration.toMillis(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL)),
614 ),
615 ),
616 providerHealthRefreshInterval: Schema.DurationFromMillis.pipe(
617 Schema.withDecodingDefault(
618 Effect.succeed(Duration.toMillis(DEFAULT_PROVIDER_HEALTH_REFRESH_INTERVAL)),
619 ),
620 ),
621 backgroundActivityProfile: BackgroundActivityProfile.pipe(
622 Schema.withDecodingDefault(Effect.succeed(DEFAULT_BACKGROUND_ACTIVITY_PROFILE)),
623 ),
624 defaultThreadEnvMode: ThreadEnvMode.pipe(
625 Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
626 ),
627 newWorktreesStartFromOrigin: Schema.Boolean.pipe(
628 Schema.withDecodingDefault(Effect.succeed(true)),
629 ),
630 addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
631 textGenerationModelSelection: ModelSelection.pipe(
632 Schema.withDecodingDefault(
633 Effect.succeed({
634 instanceId: ProviderInstanceId.make("codex"),
635 model: DEFAULT_TEXT_GENERATION_MODEL,
636 options: [
637 {
638 id: "reasoningEffort",
639 value: DEFAULT_TEXT_GENERATION_REASONING_EFFORT,
640 },
641 ],
642 }),
643 ),
644 ),
645 sourceControlWritingStyle: SourceControlWritingStyleSettings.pipe(
646 Schema.withDecodingDefault(Effect.succeed({})),
647 ),
648 sourceControlWriterModelSelection: Schema.NullOr(ModelSelection).pipe(
649 Schema.withDecodingDefault(Effect.succeed(null)),
650 ),
651​
652 // Legacy single-instance-per-driver settings. Continues to be the source
653 // of truth until `providerInstances` (below) lands per-driver migration
654 // shims and the server starts hydrating instances from it. Driver-specific
655 // schemas live here for the duration of the migration; once each driver
656 // owns its config in its own package, this struct shrinks to nothing and
657 // is removed entirely.
658 providers: Schema.Struct({
659 codex: CodexSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
660 claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
661 cursor: CursorSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
662 grok: GrokSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
663 opencode: OpenCodeSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
664 }).pipe(Schema.withDecodingDefault(Effect.succeed({}))),
665 // New driver-agnostic instance map. Keyed by `ProviderInstanceId`; values
666 // are `ProviderInstanceConfig` envelopes. The driver-specific config blob
667 // is `Schema.Unknown` at this layer so envelopes with unknown drivers
668 // (forks, downgrades, in-flight PR branches) round-trip without loss.
669 // See providerInstance.ts for the forward/backward compatibility invariant.
670 providerInstances: Schema.Record(ProviderInstanceId, ProviderInstanceConfig).pipe(
671 Schema.withDecodingDefault(Effect.succeed({})),
672 ),
673 observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),
674});
675export type ServerSettings = typeof ServerSettings.Type;
676​
677export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});
678​
679/**
680 * Read the legacy `enabled` flag embedded in a provider instance config
681 * blob. The envelope-level `ProviderInstanceConfig.enabled` is the single
682 * flag going forward; this reader exists for legacy `providers.<kind>`
683 * blobs and old settings files that still carry the flag in-config.
684 */
685export const providerInstanceConfigEnabledFlag = (config: unknown): boolean | undefined => {
686 if (config === null || typeof config !== "object" || Array.isArray(config)) {
687 return undefined;
688 }
689 const enabled = (config as { readonly enabled?: unknown }).enabled;
690 return typeof enabled === "boolean" ? enabled : undefined;
691};
692​
693/**
694 * Default enabled state for a built-in driver when neither the envelope nor
695 * the config blob carries a flag. Derived from the driver's settings schema
696 * through `DEFAULT_SERVER_SETTINGS`, so the schema's decoding default stays
697 * the single source of truth. Unknown (fork) drivers default to enabled.
698 */
699export const defaultEnabledForDriver = (driver: ProviderDriverKind): boolean => {
700 const legacyDefaults = DEFAULT_SERVER_SETTINGS.providers as Record<
701 string,
702 { readonly enabled?: boolean } | undefined
703 >;
704 return legacyDefaults[driver]?.enabled ?? true;
705};
706​
707/**
708 * Resolve whether a configured provider instance is enabled. An explicit
709 * false on either the envelope or the in-config flag wins (most
710 * restrictive), so a user's disable is never silently undone by the other
711 * flag. Otherwise: envelope, then config, then the driver's default.
712 */
713export const resolveProviderInstanceEnabled = (
714 instance: Pick<ProviderInstanceConfig, "driver" | "enabled" | "config">,
715): boolean => {
716 const configEnabled = providerInstanceConfigEnabledFlag(instance.config);
717 if (instance.enabled === false || configEnabled === false) {
718 return false;
719 }
720 return instance.enabled ?? configEnabled ?? defaultEnabledForDriver(instance.driver);
721};
722​
723export const ServerSettingsOperation = Schema.Literals([
724 "normalize",
725 "check-exists",
726 "read-file",
727 "read-secret",
728 "remove-secret",
729 "remove-stale-secret",
730 "write-secret",
731 "write-file",
732 "prepare-directory",
733]);
734export type ServerSettingsOperation = typeof ServerSettingsOperation.Type;
735​
736export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
737 "ServerSettingsError",
738 {
739 settingsPath: Schema.String,
740 operation: ServerSettingsOperation,
741 providerInstanceId: Schema.optional(Schema.String),
742 environmentVariable: Schema.optional(Schema.String),
743 cause: Schema.Defect(),
744 },
745) {
746 override get message(): string {
747 const provider =
748 this.providerInstanceId === undefined ? "" : ` for provider ${this.providerInstanceId}`;
749 const variable =
750 this.environmentVariable === undefined
751 ? ""
752 : ` and environment variable ${this.environmentVariable}`;
753 return `Server settings ${this.operation} failed${provider}${variable} at ${this.settingsPath}.`;
754 }
756​
757// ── Unified type ─────────────────────────────────────────────────────
758​
759export type UnifiedSettings = ServerSettings & ClientSettings;
760export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {
761 ...DEFAULT_SERVER_SETTINGS,
762 ...DEFAULT_CLIENT_SETTINGS,
763};
764​
765// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────
766​
767const ModelSelectionPatch = Schema.Struct({
768 instanceId: Schema.optionalKey(ProviderInstanceId),
769 model: Schema.optionalKey(TrimmedNonEmptyString),
770 options: Schema.optionalKey(ProviderOptionSelections),
771});
772​
773const CodexSettingsPatch = Schema.Struct({
774 enabled: Schema.optionalKey(Schema.Boolean),
775 binaryPath: Schema.optionalKey(TrimmedString),
776 homePath: Schema.optionalKey(TrimmedString),
777 shadowHomePath: Schema.optionalKey(TrimmedString),
778 launchArgs: Schema.optionalKey(TrimmedString),
779 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
780});
781​
782const ClaudeSettingsPatch = Schema.Struct({
783 enabled: Schema.optionalKey(Schema.Boolean),
784 binaryPath: Schema.optionalKey(TrimmedString),
785 homePath: Schema.optionalKey(TrimmedString),
786 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
787 launchArgs: Schema.optionalKey(TrimmedString),
788});
789​
790const CursorSettingsPatch = Schema.Struct({
791 enabled: Schema.optionalKey(Schema.Boolean),
792 binaryPath: Schema.optionalKey(TrimmedString),
793 apiEndpoint: Schema.optionalKey(TrimmedString),
794 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
795});
796​
797const GrokSettingsPatch = Schema.Struct({
798 enabled: Schema.optionalKey(Schema.Boolean),
799 binaryPath: Schema.optionalKey(TrimmedString),
800 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
801});
802​
803const OpenCodeSettingsPatch = Schema.Struct({
804 enabled: Schema.optionalKey(Schema.Boolean),
805 binaryPath: Schema.optionalKey(TrimmedString),
806 serverUrl: Schema.optionalKey(TrimmedString),
807 serverPassword: Schema.optionalKey(TrimmedString),
808 customModels: Schema.optionalKey(Schema.Array(Schema.String)),
809});
810​
811export const ServerSettingsPatch = Schema.Struct({
812 // Server settings
813 enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
814 enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
815 enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean),
816 backgroundActivity: Schema.optionalKey(
817 Schema.Struct({
818 schemaVersion: Schema.optionalKey(Schema.Literal(1)),
819 profile: Schema.optionalKey(BackgroundActivityProfileSelection),
820 baseProfile: Schema.optionalKey(BackgroundActivityProfile),
821 overrides: Schema.optionalKey(BackgroundActivityOverrides),
822 }),
823 ),
824 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
825 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
826 backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
827 defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
828 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
829 addProjectBaseDirectory: Schema.optionalKey(TrimmedString),
830 textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
831 sourceControlWritingStyle: Schema.optionalKey(
832 Schema.Struct({
833 mode: Schema.optionalKey(SourceControlWritingStyleMode),
834 customInstructions: Schema.optionalKey(TrimmedString),
835 followChangeRequestTemplates: Schema.optionalKey(Schema.Boolean),
836 }),
837 ),
838 sourceControlWriterModelSelection: Schema.optionalKey(Schema.NullOr(ModelSelection)),
839 observability: Schema.optionalKey(
840 Schema.Struct({
841 otlpTracesUrl: Schema.optionalKey(TrimmedString),
842 otlpMetricsUrl: Schema.optionalKey(TrimmedString),
843 }),
844 ),
845 providers: Schema.optionalKey(
846 Schema.Struct({
847 codex: Schema.optionalKey(CodexSettingsPatch),
848 claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
849 cursor: Schema.optionalKey(CursorSettingsPatch),
850 grok: Schema.optionalKey(GrokSettingsPatch),
851 opencode: Schema.optionalKey(OpenCodeSettingsPatch),
852 }),
853 ),
854 // Whole-map replacement for the new instance config. Patching individual
855 // entries is intentionally out of scope: the map is small, and partial
856 // patches risk leaving driver-specific config in a half-merged state.
857 // The web UI sends a fully-formed map every time it edits this field.
858 providerInstances: Schema.optionalKey(Schema.Record(ProviderInstanceId, ProviderInstanceConfig)),
859});
860export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
861​
862export const ClientSettingsPatch = Schema.Struct({
863 browserDefaultViewport: Schema.optionalKey(PreviewViewportSetting),
864 browserDefaultZoomFactor: Schema.optionalKey(PreviewZoomFactor),
865 browserDefaultAppearance: Schema.optionalKey(PreviewAppearancePreference),
866 browserAutoShowFloatingPreview: Schema.optionalKey(Schema.Boolean),
867 confirmQuit: Schema.optionalKey(Schema.Boolean),
868 confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
869 confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
870 diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
871 environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
872 glassOpacity: Schema.optionalKey(GlassOpacity),
873 fontSizeInterface: Schema.optionalKey(InterfaceFontSize),
874 fontSizePrompt: Schema.optionalKey(PromptFontSize),
875 fontSizeCode: Schema.optionalKey(CodeFontSize),
876 fontSizeTerminal: Schema.optionalKey(TerminalFontSize),
877 fontFamilyCode: Schema.optionalKey(FontFamilyPreference),
878 fontFamilyComposer: Schema.optionalKey(FontFamilyPreference),
879 fontFamilySans: Schema.optionalKey(FontFamilyPreference),
880 fontFamilyTerminal: Schema.optionalKey(FontFamilyPreference),
881 fontSmoothing: Schema.optionalKey(Schema.Boolean),
882 favorites: Schema.optionalKey(
883 Schema.Array(
884 Schema.Struct({
885 provider: ProviderInstanceId,
886 model: TrimmedNonEmptyString,
887 }),
888 ),
889 ),
890 providerModelPreferences: Schema.optionalKey(
891 Schema.Record(
892 ProviderInstanceId,
893 Schema.Struct({
894 hiddenModels: Schema.Array(Schema.String).pipe(
895 Schema.withDecodingDefault(Effect.succeed([])),
896 ),
897 modelOrder: Schema.Array(Schema.String).pipe(
898 Schema.withDecodingDefault(Effect.succeed([])),
899 ),
900 }),
901 ),
902 ),
903 planModeEnabled: Schema.optionalKey(Schema.Boolean),
904 legacySidebarEnabled: Schema.optionalKey(Schema.Boolean),
905 sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
906 sidebarAutoSettleOnMerge: Schema.optionalKey(Schema.Boolean),
907 sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode),
908 sidebarProjectGroupingOverrides: Schema.optionalKey(
909 Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode),
910 ),
911 sidebarProjectSortOrder: Schema.optionalKey(SidebarProjectSortOrder),
912 sidebarThreadSortOrder: Schema.optionalKey(SidebarThreadSortOrder),
913 sidebarThreadPreviewCount: Schema.optionalKey(SidebarThreadPreviewCount),
914 timestampFormat: Schema.optionalKey(TimestampFormat),
915 wordWrap: Schema.optionalKey(Schema.Boolean),
916});
917export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;