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

SettingsPanels.logic.ts

283 lines9.7 KB

1import type {
2 BackgroundActivityProfile,
3 BackgroundActivitySettings,
4 ProviderDriverKind,
5 ProviderInstanceConfig,
6 ProviderInstanceId,
7 ServerSettings,
8 SidebarProjectGroupingMode,
9 UnifiedSettings,
10} from "@t3tools/contracts";
11import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
12import {
13 getBackgroundActivityBaseProfile,
14 normalizeBackgroundActivitySettings,
15 normalizeServerBackgroundActivitySettings,
16 resolveServerBackgroundActivitySettings,
17} from "@t3tools/shared/backgroundActivitySettings";
18import * as Duration from "effect/Duration";
19import * as Equal from "effect/Equal";
20​
21export function isProjectGroupingEnabled(mode: SidebarProjectGroupingMode): boolean {
22 return mode !== "separate";
24​
25export function projectGroupingModeFromToggle(
26 enabled: boolean,
27 lastEnabledMode: SidebarProjectGroupingMode = "repository",
28): SidebarProjectGroupingMode {
29 if (!enabled) return "separate";
30 return lastEnabledMode === "repository_path" ? "repository_path" : "repository";
32​
33const LAST_ENABLED_PROJECT_GROUPING_MODE_KEY = "t3code:last-enabled-project-grouping-mode";
34​
35export function readLastEnabledProjectGroupingMode(): SidebarProjectGroupingMode {
36 try {
37 return localStorage.getItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY) === "repository_path"
38 ? "repository_path"
39 : "repository";
40 } catch {
41 return "repository";
42 }
44​
45export function rememberEnabledProjectGroupingMode(mode: SidebarProjectGroupingMode): void {
46 if (mode === "separate") return;
47 try {
48 localStorage.setItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY, mode);
49 } catch {
50 // Storage can be unavailable in restricted browser contexts.
51 }
53​
54export function hasChangedBackgroundActivitySettings(
55 settings: Pick<
56 UnifiedSettings,
57 | "backgroundActivity"
58 | "backgroundActivityProfile"
59 | "automaticGitFetchInterval"
60 | "providerHealthRefreshInterval"
61 >,
62): boolean {
63 return (
64 !Equal.equals(settings.backgroundActivity, DEFAULT_UNIFIED_SETTINGS.backgroundActivity) ||
65 settings.backgroundActivityProfile !== DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile ||
66 !Equal.equals(
67 settings.automaticGitFetchInterval,
68 DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
69 ) ||
70 !Equal.equals(
71 settings.providerHealthRefreshInterval,
72 DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval,
73 )
74 );
76​
77type TypographySettings = Pick<
78 UnifiedSettings,
79 | "fontFamilySans"
80 | "fontFamilyComposer"
81 | "fontFamilyCode"
82 | "fontFamilyTerminal"
83 | "fontSizeInterface"
84 | "fontSizePrompt"
85 | "fontSizeCode"
86 | "fontSizeTerminal"
87>;
88​
89/** Labels the font rows whose family or size differs from the defaults. */
90export function getChangedTypographySettingLabels(settings: TypographySettings): string[] {
91 return [
92 ...(settings.fontFamilySans !== DEFAULT_UNIFIED_SETTINGS.fontFamilySans ||
93 settings.fontSizeInterface !== DEFAULT_UNIFIED_SETTINGS.fontSizeInterface
94 ? ["Interface font"]
95 : []),
96 ...(settings.fontFamilyComposer !== DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer ||
97 settings.fontSizePrompt !== DEFAULT_UNIFIED_SETTINGS.fontSizePrompt
98 ? ["Prompt font"]
99 : []),
100 ...(settings.fontFamilyCode !== DEFAULT_UNIFIED_SETTINGS.fontFamilyCode ||
101 settings.fontSizeCode !== DEFAULT_UNIFIED_SETTINGS.fontSizeCode
102 ? ["Code font"]
103 : []),
104 ...(settings.fontFamilyTerminal !== DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal ||
105 settings.fontSizeTerminal !== DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal
106 ? ["Terminal font"]
107 : []),
108 ];
110​
111export function resolveBackgroundActivityProfileOption(
112 settings: ServerSettings,
113): BackgroundActivityProfile | "advanced" {
114 const resolved = resolveServerBackgroundActivitySettings(settings);
115 const normalized = normalizeBackgroundActivitySettings({
116 schemaVersion: 1,
117 profile: "custom",
118 baseProfile: resolved.profile,
119 overrides: {
120 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
121 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
122 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
123 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
124 idleClientTtl: resolved.idleClientTtl,
125 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
126 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
127 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
128 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
129 },
130 });
131 return normalized.profile === "custom" ? "advanced" : normalized.profile;
133​
134export function backgroundActivitySharedPolicySettings(
135 settings: ServerSettings,
136 profile: BackgroundActivityProfile,
137): BackgroundActivitySettings {
138 const normalized = normalizeServerBackgroundActivitySettings(settings);
139 return {
140 schemaVersion: 1,
141 profile: "custom",
142 baseProfile: profile,
143 overrides: normalized.profile === "custom" ? normalized.overrides : {},
144 };
146​
147function collapseOtelSignalsUrl(input: {
148 readonly tracesUrl: string;
149 readonly metricsUrl: string;
150}): string | null {
151 const tracesSuffix = "/traces";
152 const metricsSuffix = "/metrics";
153 if (!input.tracesUrl.endsWith(tracesSuffix) || !input.metricsUrl.endsWith(metricsSuffix)) {
154 return null;
155 }
156​
157 const tracesBase = input.tracesUrl.slice(0, -tracesSuffix.length);
158 const metricsBase = input.metricsUrl.slice(0, -metricsSuffix.length);
159 if (tracesBase !== metricsBase) {
160 return null;
161 }
162​
163 return `${tracesBase}/{traces,metrics}`;
165​
166export function formatDiagnosticsDescription(input: {
167 readonly localTracingEnabled: boolean;
168 readonly otlpTracesEnabled: boolean;
169 readonly otlpTracesUrl?: string | undefined;
170 readonly otlpMetricsEnabled: boolean;
171 readonly otlpMetricsUrl?: string | undefined;
172}): string {
173 const mode = input.localTracingEnabled ? "Local trace file" : "Terminal logs only";
174 const tracesUrl = input.otlpTracesEnabled ? input.otlpTracesUrl : undefined;
175 const metricsUrl = input.otlpMetricsEnabled ? input.otlpMetricsUrl : undefined;
176​
177 if (tracesUrl && metricsUrl) {
178 const collapsedUrl = collapseOtelSignalsUrl({ tracesUrl, metricsUrl });
179 return collapsedUrl
180 ? `${mode}. Exporting OTEL to ${collapsedUrl}.`
181 : `${mode}. Exporting OTEL traces to ${tracesUrl} and metrics to ${metricsUrl}.`;
182 }
183​
184 if (tracesUrl) {
185 return `${mode}. Exporting OTEL traces to ${tracesUrl}.`;
186 }
187​
188 if (metricsUrl) {
189 return `${mode}. Exporting OTEL metrics to ${metricsUrl}.`;
190 }
191​
192 return `${mode}.`;
194​
195export function buildProviderInstanceUpdatePatch(input: {
196 readonly settings: Pick<ServerSettings, "providers" | "providerInstances">;
197 readonly instanceId: ProviderInstanceId;
198 readonly instance: ProviderInstanceConfig;
199 readonly driver: ProviderDriverKind;
200 readonly isDefault: boolean;
201 readonly textGenerationModelSelection?:
202 | ServerSettings["textGenerationModelSelection"]
203 | undefined;
204}): Partial<UnifiedSettings> {
205 type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
206 const legacyProviderDefaults = DEFAULT_UNIFIED_SETTINGS.providers as Record<
207 string,
208 LegacyProviderSettings | undefined
209 >;
210 const legacyProviderDefault = input.isDefault ? legacyProviderDefaults[input.driver] : undefined;
211 return {
212 ...(legacyProviderDefault !== undefined
213 ? {
214 providers: {
215 ...input.settings.providers,
216 [input.driver]: legacyProviderDefault,
217 } as ServerSettings["providers"],
218 }
219 : {}),
220 providerInstances: {
221 ...input.settings.providerInstances,
222 [input.instanceId]: input.instance,
223 },
224 ...(input.textGenerationModelSelection !== undefined
225 ? { textGenerationModelSelection: input.textGenerationModelSelection }
226 : {}),
227 };
229​
230// ── Background-activity interval helpers ─────────────────────────────
231// Shared by the General panel's interval rows and the Providers panel's
232// health-check row.
233​
234export const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
235​
236type BackgroundActivityOverridePatch = Partial<{
237 [K in keyof BackgroundActivitySettings["overrides"]]:
238 | BackgroundActivitySettings["overrides"][K]
239 | undefined;
240}>;
241​
242export function durationToSeconds(duration: Duration.Duration): number {
243 return Math.round(Duration.toMillis(duration) / 1_000);
245​
246export function normalizeIntervalSeconds(value: number | null, minimum = 0): number {
247 if (value === null || !Number.isFinite(value)) {
248 return minimum;
249 }
250 return Math.max(minimum, Math.round(value));
252​
253export function backgroundActivityOverrideSettings(
254 current: BackgroundActivitySettings,
255 resolved: ReturnType<typeof resolveServerBackgroundActivitySettings>,
256 overrides: BackgroundActivityOverridePatch,
257) {
258 const nextOverrides: BackgroundActivityOverridePatch = {
259 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
260 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
261 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
262 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
263 idleClientTtl: resolved.idleClientTtl,
264 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
265 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
266 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
267 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
268 ...overrides,
269 };
270 for (const [key, value] of Object.entries(nextOverrides)) {
271 if (value === undefined) {
272 delete nextOverrides[key as keyof typeof nextOverrides];
273 }
274 }
275 return {
276 backgroundActivity: {
277 schemaVersion: 1 as const,
278 profile: "custom" as const,
279 baseProfile: getBackgroundActivityBaseProfile(current),
280 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
281 },
282 };