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

SettingsPanels.logic.ts

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