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

SettingsPanels.logic.ts

332 lines11.4 KB

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