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

SettingsPanels.logic.ts

333 lines11.4 KB

1import type {
2 BackgroundActivityProfile,
3 BackgroundActivitySettings,
4 ProviderDriverKind,
5 ProviderInstanceConfig,
6 PreviewViewportSetting,
7 ProviderInstanceId,
8 ServerSettings,
9 SidebarProjectGroupingMode,
10 UnifiedSettings,
11} from "@t3tools/contracts";
12import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
13import {
14 getBackgroundActivityBaseProfile,
15 normalizeBackgroundActivitySettings,
16 normalizeServerBackgroundActivitySettings,
17 resolveServerBackgroundActivitySettings,
18} from "@t3tools/shared/backgroundActivitySettings";
19import * as Duration from "effect/Duration";
20import * as Equal from "effect/Equal";
21​
22export function isProjectGroupingEnabled(mode: SidebarProjectGroupingMode): boolean {
23 return mode !== "separate";
25​
26export function projectGroupingModeFromToggle(
27 enabled: boolean,
28 lastEnabledMode: SidebarProjectGroupingMode = "repository",
29): SidebarProjectGroupingMode {
30 if (!enabled) return "separate";
31 return lastEnabledMode === "repository_path" ? "repository_path" : "repository";
33​
34const LAST_ENABLED_PROJECT_GROUPING_MODE_KEY = "t3code:last-enabled-project-grouping-mode";
35​
36export function readLastEnabledProjectGroupingMode(): SidebarProjectGroupingMode {
37 try {
38 return localStorage.getItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY) === "repository_path"
39 ? "repository_path"
40 : "repository";
41 } catch {
42 return "repository";
43 }
45​
46export function rememberEnabledProjectGroupingMode(mode: SidebarProjectGroupingMode): void {
47 if (mode === "separate") return;
48 try {
49 localStorage.setItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY, mode);
50 } catch {
51 // Storage can be unavailable in restricted browser contexts.
52 }
54​
55export function hasChangedBackgroundActivitySettings(
56 settings: Pick<
57 UnifiedSettings,
58 | "backgroundActivity"
59 | "backgroundActivityProfile"
60 | "automaticGitFetchInterval"
61 | "providerHealthRefreshInterval"
62 >,
63): boolean {
64 return (
65 !Equal.equals(settings.backgroundActivity, DEFAULT_UNIFIED_SETTINGS.backgroundActivity) ||
66 settings.backgroundActivityProfile !== DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile ||
67 !Equal.equals(
68 settings.automaticGitFetchInterval,
69 DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
70 ) ||
71 !Equal.equals(
72 settings.providerHealthRefreshInterval,
73 DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval,
74 )
75 );
77​
78type TypographySettings = Pick<
79 UnifiedSettings,
80 | "fontFamilySans"
81 | "fontFamilyComposer"
82 | "fontFamilyCode"
83 | "fontFamilyTerminal"
84 | "fontSizeInterface"
85 | "fontSizePrompt"
86 | "fontSizeCode"
87 | "fontSizeTerminal"
88>;
89​
90/** Labels the font rows whose family or size differs from the defaults. */
91export function getChangedTypographySettingLabels(settings: TypographySettings): string[] {
92 return [
93 ...(settings.fontFamilySans !== DEFAULT_UNIFIED_SETTINGS.fontFamilySans ||
94 settings.fontSizeInterface !== DEFAULT_UNIFIED_SETTINGS.fontSizeInterface
95 ? ["Interface font"]
96 : []),
97 ...(settings.fontFamilyComposer !== DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer ||
98 settings.fontSizePrompt !== DEFAULT_UNIFIED_SETTINGS.fontSizePrompt
99 ? ["Prompt font"]
100 : []),
101 ...(settings.fontFamilyCode !== DEFAULT_UNIFIED_SETTINGS.fontFamilyCode ||
102 settings.fontSizeCode !== DEFAULT_UNIFIED_SETTINGS.fontSizeCode
103 ? ["Code font"]
104 : []),
105 ...(settings.fontFamilyTerminal !== DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal ||
106 settings.fontSizeTerminal !== DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal
107 ? ["Terminal font"]
108 : []),
109 ];
111​
112export type BrowserDefaultSettings = Pick<
113 UnifiedSettings,
114 | "browserDefaultViewport"
115 | "browserDefaultZoomFactor"
116 | "browserDefaultAppearance"
117 | "browserAutoShowFloatingPreview"
118>;
119​
120/**
121 * True when two viewport settings describe the same viewport.
122 *
123 * The setting is a tagged union rather than a scalar, so identity comparison
124 * reports every stored viewport as changed — including one that matches the
125 * default.
126 */
127export function isSamePreviewViewport(
128 left: PreviewViewportSetting,
129 right: PreviewViewportSetting,
130): boolean {
131 if (left._tag !== right._tag) return false;
132 if (left._tag === "fill" || right._tag === "fill") return true;
133 if (left.width !== right.width || left.height !== right.height) return false;
134 return left._tag === "preset" && right._tag === "preset"
135 ? left.presetId === right.presetId
136 : true;
138​
139/** Labels the browser-default rows that differ from the defaults. */
140export function getChangedBrowserSettingLabels(settings: BrowserDefaultSettings): string[] {
141 return [
142 ...(isSamePreviewViewport(
143 settings.browserDefaultViewport,
144 DEFAULT_UNIFIED_SETTINGS.browserDefaultViewport,
145 )
146 ? []
147 : ["Browser viewport"]),
148 ...(settings.browserDefaultZoomFactor !== DEFAULT_UNIFIED_SETTINGS.browserDefaultZoomFactor
149 ? ["Browser zoom"]
150 : []),
151 ...(settings.browserDefaultAppearance !== DEFAULT_UNIFIED_SETTINGS.browserDefaultAppearance
152 ? ["Browser appearance"]
153 : []),
154 ...(settings.browserAutoShowFloatingPreview !==
155 DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview
156 ? ["Floating preview"]
157 : []),
158 ];
160​
161export function resolveBackgroundActivityProfileOption(
162 settings: ServerSettings,
163): BackgroundActivityProfile | "advanced" {
164 const resolved = resolveServerBackgroundActivitySettings(settings);
165 const normalized = normalizeBackgroundActivitySettings({
166 schemaVersion: 1,
167 profile: "custom",
168 baseProfile: resolved.profile,
169 overrides: {
170 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
171 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
172 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
173 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
174 idleClientTtl: resolved.idleClientTtl,
175 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
176 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
177 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
178 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
179 },
180 });
181 return normalized.profile === "custom" ? "advanced" : normalized.profile;
183​
184export function backgroundActivitySharedPolicySettings(
185 settings: ServerSettings,
186 profile: BackgroundActivityProfile,
187): BackgroundActivitySettings {
188 const normalized = normalizeServerBackgroundActivitySettings(settings);
189 return {
190 schemaVersion: 1,
191 profile: "custom",
192 baseProfile: profile,
193 overrides: normalized.profile === "custom" ? normalized.overrides : {},
194 };
196​
197function collapseOtelSignalsUrl(input: {
198 readonly tracesUrl: string;
199 readonly metricsUrl: string;
200}): string | null {
201 const tracesSuffix = "/traces";
202 const metricsSuffix = "/metrics";
203 if (!input.tracesUrl.endsWith(tracesSuffix) || !input.metricsUrl.endsWith(metricsSuffix)) {
204 return null;
205 }
206​
207 const tracesBase = input.tracesUrl.slice(0, -tracesSuffix.length);
208 const metricsBase = input.metricsUrl.slice(0, -metricsSuffix.length);
209 if (tracesBase !== metricsBase) {
210 return null;
211 }
212​
213 return `${tracesBase}/{traces,metrics}`;
215​
216export function formatDiagnosticsDescription(input: {
217 readonly localTracingEnabled: boolean;
218 readonly otlpTracesEnabled: boolean;
219 readonly otlpTracesUrl?: string | undefined;
220 readonly otlpMetricsEnabled: boolean;
221 readonly otlpMetricsUrl?: string | undefined;
222}): string {
223 const mode = input.localTracingEnabled ? "Local trace file" : "Terminal logs only";
224 const tracesUrl = input.otlpTracesEnabled ? input.otlpTracesUrl : undefined;
225 const metricsUrl = input.otlpMetricsEnabled ? input.otlpMetricsUrl : undefined;
226​
227 if (tracesUrl && metricsUrl) {
228 const collapsedUrl = collapseOtelSignalsUrl({ tracesUrl, metricsUrl });
229 return collapsedUrl
230 ? `${mode}. Exporting OTEL to ${collapsedUrl}.`
231 : `${mode}. Exporting OTEL traces to ${tracesUrl} and metrics to ${metricsUrl}.`;
232 }
233​
234 if (tracesUrl) {
235 return `${mode}. Exporting OTEL traces to ${tracesUrl}.`;
236 }
237​
238 if (metricsUrl) {
239 return `${mode}. Exporting OTEL metrics to ${metricsUrl}.`;
240 }
241​
242 return `${mode}.`;
244​
245export function buildProviderInstanceUpdatePatch(input: {
246 readonly settings: Pick<ServerSettings, "providers" | "providerInstances">;
247 readonly instanceId: ProviderInstanceId;
248 readonly instance: ProviderInstanceConfig;
249 readonly driver: ProviderDriverKind;
250 readonly isDefault: boolean;
251 readonly textGenerationModelSelection?:
252 | ServerSettings["textGenerationModelSelection"]
253 | undefined;
254}): Partial<UnifiedSettings> {
255 type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
256 const legacyProviderDefaults = DEFAULT_UNIFIED_SETTINGS.providers as Record<
257 string,
258 LegacyProviderSettings | undefined
259 >;
260 const legacyProviderDefault = input.isDefault ? legacyProviderDefaults[input.driver] : undefined;
261 return {
262 ...(legacyProviderDefault !== undefined
263 ? {
264 providers: {
265 ...input.settings.providers,
266 [input.driver]: legacyProviderDefault,
267 } as ServerSettings["providers"],
268 }
269 : {}),
270 providerInstances: {
271 ...input.settings.providerInstances,
272 [input.instanceId]: input.instance,
273 },
274 ...(input.textGenerationModelSelection !== undefined
275 ? { textGenerationModelSelection: input.textGenerationModelSelection }
276 : {}),
277 };
279​
280// ── Background-activity interval helpers ─────────────────────────────
281// Shared by the General panel's interval rows and the Providers panel's
282// health-check row.
283​
284export const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
285​
286type BackgroundActivityOverridePatch = Partial<{
287 [K in keyof BackgroundActivitySettings["overrides"]]:
288 | BackgroundActivitySettings["overrides"][K]
289 | undefined;
290}>;
291​
292export function durationToSeconds(duration: Duration.Duration): number {
293 return Math.round(Duration.toMillis(duration) / 1_000);
295​
296export function normalizeIntervalSeconds(value: number | null, minimum = 0): number {
297 if (value === null || !Number.isFinite(value)) {
298 return minimum;
299 }
300 return Math.max(minimum, Math.round(value));
302​
303export function backgroundActivityOverrideSettings(
304 current: BackgroundActivitySettings,
305 resolved: ReturnType<typeof resolveServerBackgroundActivitySettings>,
306 overrides: BackgroundActivityOverridePatch,
307) {
308 const nextOverrides: BackgroundActivityOverridePatch = {
309 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
310 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
311 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
312 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
313 idleClientTtl: resolved.idleClientTtl,
314 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
315 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
316 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
317 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
318 ...overrides,
319 };
320 for (const [key, value] of Object.entries(nextOverrides)) {
321 if (value === undefined) {
322 delete nextOverrides[key as keyof typeof nextOverrides];
323 }
324 }
325 return {
326 backgroundActivity: {
327 schemaVersion: 1 as const,
328 profile: "custom" as const,
329 baseProfile: getBackgroundActivityBaseProfile(current),
330 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
331 },
332 };