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

settings.ts

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