Open History to see the last commit
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";
24}
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";
32}
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 }
44}
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 }
53}
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 );
76}
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 ];
110}
111
112export type BrowserDefaultSettings = Pick<
113 UnifiedSettings,
114 | "browserDefaultViewport"
115 | "browserDefaultZoomFactor"
116 | "browserDefaultAppearance"
117 | "browserRecordingFrameRate"
118 | "browserRecordingShowKeyPresses"
119 | "browserRecordingShowMousePresses"
120 | "browserLinkTarget"
121 | "browserAutoShowFloatingPreview"
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;
141}
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 ];
171}
172
173export function resolveBackgroundActivityProfileOption(
174 settings: ServerSettings,
175): BackgroundActivityProfile | "advanced" {
176 const resolved = resolveServerBackgroundActivitySettings(settings);
177 const normalized = normalizeBackgroundActivitySettings({
178 schemaVersion: 1,
179 profile: "custom",
180 baseProfile: resolved.profile,
181 overrides: {
182 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
183 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
184 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
185 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
186 idleClientTtl: resolved.idleClientTtl,
187 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
188 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
189 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
190 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
191 },
192 });
193 return normalized.profile === "custom" ? "advanced" : normalized.profile;
194}
195
196export function backgroundActivitySharedPolicySettings(
197 settings: ServerSettings,
198 profile: BackgroundActivityProfile,
199): BackgroundActivitySettings {
200 const normalized = normalizeServerBackgroundActivitySettings(settings);
201 return {
202 schemaVersion: 1,
203 profile: "custom",
204 baseProfile: profile,
205 overrides: normalized.profile === "custom" ? normalized.overrides : {},
206 };
207}
208
209function collapseOtelSignalsUrl(input: {
210 readonly tracesUrl: string;
211 readonly metricsUrl: string;
212}): string | null {
213 const tracesSuffix = "/traces";
214 const metricsSuffix = "/metrics";
215 if (!input.tracesUrl.endsWith(tracesSuffix) || !input.metricsUrl.endsWith(metricsSuffix)) {
216 return null;
217 }
218
219 const tracesBase = input.tracesUrl.slice(0, -tracesSuffix.length);
220 const metricsBase = input.metricsUrl.slice(0, -metricsSuffix.length);
221 if (tracesBase !== metricsBase) {
222 return null;
223 }
224
225 return `${tracesBase}/{traces,metrics}`;
226}
227
228export function formatDiagnosticsDescription(input: {
229 readonly localTracingEnabled: boolean;
230 readonly otlpTracesEnabled: boolean;
231 readonly otlpTracesUrl?: string | undefined;
232 readonly otlpMetricsEnabled: boolean;
233 readonly otlpMetricsUrl?: string | undefined;
234}): string {
235 const mode = input.localTracingEnabled ? "Local trace file" : "Terminal logs only";
236 const tracesUrl = input.otlpTracesEnabled ? input.otlpTracesUrl : undefined;
237 const metricsUrl = input.otlpMetricsEnabled ? input.otlpMetricsUrl : undefined;
238
239 if (tracesUrl && metricsUrl) {
240 const collapsedUrl = collapseOtelSignalsUrl({ tracesUrl, metricsUrl });
241 return collapsedUrl
242 ? `${mode}. Exporting OTEL to ${collapsedUrl}.`
243 : `${mode}. Exporting OTEL traces to ${tracesUrl} and metrics to ${metricsUrl}.`;
244 }
245
246 if (tracesUrl) {
247 return `${mode}. Exporting OTEL traces to ${tracesUrl}.`;
248 }
249
250 if (metricsUrl) {
251 return `${mode}. Exporting OTEL metrics to ${metricsUrl}.`;
252 }
253
254 return `${mode}.`;
255}
256
257export function buildProviderInstanceUpdatePatch(input: {
258 readonly settings: Pick<ServerSettings, "providers" | "providerInstances">;
259 readonly instanceId: ProviderInstanceId;
260 readonly instance: ProviderInstanceConfig;
261 readonly driver: ProviderDriverKind;
262 readonly isDefault: boolean;
263 readonly textGenerationModelSelection?:
264 | ServerSettings["textGenerationModelSelection"]
265 | undefined;
266}): Partial<UnifiedSettings> {
267 type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
268 const legacyProviderDefaults = DEFAULT_UNIFIED_SETTINGS.providers as Record<
269 string,
270 LegacyProviderSettings | undefined
271 >;
272 const legacyProviderDefault = input.isDefault ? legacyProviderDefaults[input.driver] : undefined;
273 return {
274 ...(legacyProviderDefault !== undefined
275 ? {
276 providers: {
277 ...input.settings.providers,
278 [input.driver]: legacyProviderDefault,
279 } as ServerSettings["providers"],
280 }
281 : {}),
282 providerInstances: {
283 ...input.settings.providerInstances,
284 [input.instanceId]: input.instance,
285 },
286 ...(input.textGenerationModelSelection !== undefined
287 ? { textGenerationModelSelection: input.textGenerationModelSelection }
288 : {}),
289 };
290}
291
292// ── Background-activity interval helpers ─────────────────────────────
293// Shared by the General panel's interval rows and the Providers panel's
294// health-check row.
295
296export const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
297
298type BackgroundActivityOverridePatch = Partial<{
299 [K in keyof BackgroundActivitySettings["overrides"]]:
300 | BackgroundActivitySettings["overrides"][K]
301 | undefined;
302}>;
303
304export function durationToSeconds(duration: Duration.Duration): number {
305 return Math.round(Duration.toMillis(duration) / 1_000);
306}
307
308export function normalizeIntervalSeconds(value: number | null, minimum = 0): number {
309 if (value === null || !Number.isFinite(value)) {
310 return minimum;
311 }
312 return Math.max(minimum, Math.round(value));
313}
314
315export function backgroundActivityOverrideSettings(
316 current: BackgroundActivitySettings,
317 resolved: ReturnType<typeof resolveServerBackgroundActivitySettings>,
318 overrides: BackgroundActivityOverridePatch,
319) {
320 const nextOverrides: BackgroundActivityOverridePatch = {
321 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
322 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
323 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
324 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
325 idleClientTtl: resolved.idleClientTtl,
326 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
327 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
328 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
329 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
330 ...overrides,
331 };
332 for (const [key, value] of Object.entries(nextOverrides)) {
333 if (value === undefined) {
334 delete nextOverrides[key as keyof typeof nextOverrides];
335 }
336 }
337 return {
338 backgroundActivity: {
339 schemaVersion: 1 as const,
340 profile: "custom" as const,
341 baseProfile: getBackgroundActivityBaseProfile(current),
342 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
343 },
344 };
345}