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

SettingsPanels.logic.ts

337 lines11.5 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 | "browserRecordingFrameRate"
118 | "browserAutoShowFloatingPreview"
119>;
120​
121/**
122 * True when two viewport settings describe the same viewport.
123 *
124 * The setting is a tagged union rather than a scalar, so identity comparison
125 * reports every stored viewport as changed — including one that matches the
126 * default.
127 */
128export function isSamePreviewViewport(
129 left: PreviewViewportSetting,
130 right: PreviewViewportSetting,
131): boolean {
132 if (left._tag !== right._tag) return false;
133 if (left._tag === "fill" || right._tag === "fill") return true;
134 if (left.width !== right.width || left.height !== right.height) return false;
135 return left._tag === "preset" && right._tag === "preset"
136 ? left.presetId === right.presetId
137 : true;
139​
140/** Labels the browser-default rows that differ from the defaults. */
141export function getChangedBrowserSettingLabels(settings: BrowserDefaultSettings): string[] {
142 return [
143 ...(isSamePreviewViewport(
144 settings.browserDefaultViewport,
145 DEFAULT_UNIFIED_SETTINGS.browserDefaultViewport,
146 )
147 ? []
148 : ["Browser viewport"]),
149 ...(settings.browserDefaultZoomFactor !== DEFAULT_UNIFIED_SETTINGS.browserDefaultZoomFactor
150 ? ["Browser zoom"]
151 : []),
152 ...(settings.browserDefaultAppearance !== DEFAULT_UNIFIED_SETTINGS.browserDefaultAppearance
153 ? ["Browser appearance"]
154 : []),
155 ...(settings.browserRecordingFrameRate !== DEFAULT_UNIFIED_SETTINGS.browserRecordingFrameRate
156 ? ["Recording frame rate"]
157 : []),
158 ...(settings.browserAutoShowFloatingPreview !==
159 DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview
160 ? ["Floating preview"]
161 : []),
162 ];
164​
165export function resolveBackgroundActivityProfileOption(
166 settings: ServerSettings,
167): BackgroundActivityProfile | "advanced" {
168 const resolved = resolveServerBackgroundActivitySettings(settings);
169 const normalized = normalizeBackgroundActivitySettings({
170 schemaVersion: 1,
171 profile: "custom",
172 baseProfile: resolved.profile,
173 overrides: {
174 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
175 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
176 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
177 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
178 idleClientTtl: resolved.idleClientTtl,
179 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
180 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
181 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
182 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
183 },
184 });
185 return normalized.profile === "custom" ? "advanced" : normalized.profile;
187​
188export function backgroundActivitySharedPolicySettings(
189 settings: ServerSettings,
190 profile: BackgroundActivityProfile,
191): BackgroundActivitySettings {
192 const normalized = normalizeServerBackgroundActivitySettings(settings);
193 return {
194 schemaVersion: 1,
195 profile: "custom",
196 baseProfile: profile,
197 overrides: normalized.profile === "custom" ? normalized.overrides : {},
198 };
200​
201function collapseOtelSignalsUrl(input: {
202 readonly tracesUrl: string;
203 readonly metricsUrl: string;
204}): string | null {
205 const tracesSuffix = "/traces";
206 const metricsSuffix = "/metrics";
207 if (!input.tracesUrl.endsWith(tracesSuffix) || !input.metricsUrl.endsWith(metricsSuffix)) {
208 return null;
209 }
210​
211 const tracesBase = input.tracesUrl.slice(0, -tracesSuffix.length);
212 const metricsBase = input.metricsUrl.slice(0, -metricsSuffix.length);
213 if (tracesBase !== metricsBase) {
214 return null;
215 }
216​
217 return `${tracesBase}/{traces,metrics}`;
219​
220export function formatDiagnosticsDescription(input: {
221 readonly localTracingEnabled: boolean;
222 readonly otlpTracesEnabled: boolean;
223 readonly otlpTracesUrl?: string | undefined;
224 readonly otlpMetricsEnabled: boolean;
225 readonly otlpMetricsUrl?: string | undefined;
226}): string {
227 const mode = input.localTracingEnabled ? "Local trace file" : "Terminal logs only";
228 const tracesUrl = input.otlpTracesEnabled ? input.otlpTracesUrl : undefined;
229 const metricsUrl = input.otlpMetricsEnabled ? input.otlpMetricsUrl : undefined;
230​
231 if (tracesUrl && metricsUrl) {
232 const collapsedUrl = collapseOtelSignalsUrl({ tracesUrl, metricsUrl });
233 return collapsedUrl
234 ? `${mode}. Exporting OTEL to ${collapsedUrl}.`
235 : `${mode}. Exporting OTEL traces to ${tracesUrl} and metrics to ${metricsUrl}.`;
236 }
237​
238 if (tracesUrl) {
239 return `${mode}. Exporting OTEL traces to ${tracesUrl}.`;
240 }
241​
242 if (metricsUrl) {
243 return `${mode}. Exporting OTEL metrics to ${metricsUrl}.`;
244 }
245​
246 return `${mode}.`;
248​
249export function buildProviderInstanceUpdatePatch(input: {
250 readonly settings: Pick<ServerSettings, "providers" | "providerInstances">;
251 readonly instanceId: ProviderInstanceId;
252 readonly instance: ProviderInstanceConfig;
253 readonly driver: ProviderDriverKind;
254 readonly isDefault: boolean;
255 readonly textGenerationModelSelection?:
256 | ServerSettings["textGenerationModelSelection"]
257 | undefined;
258}): Partial<UnifiedSettings> {
259 type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
260 const legacyProviderDefaults = DEFAULT_UNIFIED_SETTINGS.providers as Record<
261 string,
262 LegacyProviderSettings | undefined
263 >;
264 const legacyProviderDefault = input.isDefault ? legacyProviderDefaults[input.driver] : undefined;
265 return {
266 ...(legacyProviderDefault !== undefined
267 ? {
268 providers: {
269 ...input.settings.providers,
270 [input.driver]: legacyProviderDefault,
271 } as ServerSettings["providers"],
272 }
273 : {}),
274 providerInstances: {
275 ...input.settings.providerInstances,
276 [input.instanceId]: input.instance,
277 },
278 ...(input.textGenerationModelSelection !== undefined
279 ? { textGenerationModelSelection: input.textGenerationModelSelection }
280 : {}),
281 };
283​
284// ── Background-activity interval helpers ─────────────────────────────
285// Shared by the General panel's interval rows and the Providers panel's
286// health-check row.
287​
288export const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
289​
290type BackgroundActivityOverridePatch = Partial<{
291 [K in keyof BackgroundActivitySettings["overrides"]]:
292 | BackgroundActivitySettings["overrides"][K]
293 | undefined;
294}>;
295​
296export function durationToSeconds(duration: Duration.Duration): number {
297 return Math.round(Duration.toMillis(duration) / 1_000);
299​
300export function normalizeIntervalSeconds(value: number | null, minimum = 0): number {
301 if (value === null || !Number.isFinite(value)) {
302 return minimum;
303 }
304 return Math.max(minimum, Math.round(value));
306​
307export function backgroundActivityOverrideSettings(
308 current: BackgroundActivitySettings,
309 resolved: ReturnType<typeof resolveServerBackgroundActivitySettings>,
310 overrides: BackgroundActivityOverridePatch,
311) {
312 const nextOverrides: BackgroundActivityOverridePatch = {
313 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
314 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
315 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
316 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
317 idleClientTtl: resolved.idleClientTtl,
318 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
319 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
320 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
321 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
322 ...overrides,
323 };
324 for (const [key, value] of Object.entries(nextOverrides)) {
325 if (value === undefined) {
326 delete nextOverrides[key as keyof typeof nextOverrides];
327 }
328 }
329 return {
330 backgroundActivity: {
331 schemaVersion: 1 as const,
332 profile: "custom" as const,
333 baseProfile: getBackgroundActivityBaseProfile(current),
334 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
335 },
336 };