Open History to see the last commit
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";
23}
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";
31}
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 }
43}
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}
51
52export function hasChangedBackgroundActivitySettings(
53 settings: Pick<
54 UnifiedSettings,
55 | "backgroundActivity"
56 | "backgroundActivityProfile"
57 | "automaticGitFetchInterval"
58 | "providerHealthRefreshInterval"
59 >,
60): boolean {
61 return (
62 !Equal.equals(settings.backgroundActivity, DEFAULT_UNIFIED_SETTINGS.backgroundActivity) ||
63 settings.backgroundActivityProfile !== DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile ||
64 !Equal.equals(
65 settings.automaticGitFetchInterval,
66 DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
67 ) ||
68 !Equal.equals(
69 settings.providerHealthRefreshInterval,
70 DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval,
71 )
72 );
73}
74
75type TypographySettings = Pick<
76 UnifiedSettings,
77 | "fontFamilySans"
78 | "fontFamilyComposer"
79 | "fontFamilyCode"
80 | "fontFamilyTerminal"
81 | "fontSizeInterface"
82 | "fontSizePrompt"
83 | "fontSizeCode"
84 | "fontSizeTerminal"
85>;
86
87export function getChangedTypographySettingLabels(settings: TypographySettings): string[] {
88 return [
89 ...(settings.fontFamilySans !== DEFAULT_UNIFIED_SETTINGS.fontFamilySans ||
90 settings.fontSizeInterface !== DEFAULT_UNIFIED_SETTINGS.fontSizeInterface
91 ? ["Interface font"]
92 : []),
93 ...(settings.fontFamilyComposer !== DEFAULT_UNIFIED_SETTINGS.fontFamilyComposer ||
94 settings.fontSizePrompt !== DEFAULT_UNIFIED_SETTINGS.fontSizePrompt
95 ? ["Prompt font"]
96 : []),
97 ...(settings.fontFamilyCode !== DEFAULT_UNIFIED_SETTINGS.fontFamilyCode ||
98 settings.fontSizeCode !== DEFAULT_UNIFIED_SETTINGS.fontSizeCode
99 ? ["Code font"]
100 : []),
101 ...(settings.fontFamilyTerminal !== DEFAULT_UNIFIED_SETTINGS.fontFamilyTerminal ||
102 settings.fontSizeTerminal !== DEFAULT_UNIFIED_SETTINGS.fontSizeTerminal
103 ? ["Terminal font"]
104 : []),
105 ];
106}
107
108export type BrowserDefaultSettings = Pick<
109 UnifiedSettings,
110 | "browserDefaultViewport"
111 | "browserDefaultZoomFactor"
112 | "browserDefaultAppearance"
113 | "browserRecordingFrameRate"
114 | "browserRecordingShowKeyPresses"
115 | "browserRecordingShowMousePresses"
116 | "browserLinkTarget"
117 | "browserAutoShowFloatingPreview"
118 | "pullRequestLinksOpenInApp"
119>;
120
121function isSamePreviewViewport(
122 left: PreviewViewportSetting,
123 right: PreviewViewportSetting,
124): boolean {
125 if (left._tag !== right._tag) return false;
126 if (left._tag === "fill" || right._tag === "fill") return true;
127 if (left.width !== right.width || left.height !== right.height) return false;
128 return left._tag === "preset" && right._tag === "preset"
129 ? left.presetId === right.presetId
130 : true;
131}
132
133export function getChangedBrowserSettingLabels(settings: BrowserDefaultSettings): string[] {
134 return [
135 ...(isSamePreviewViewport(
136 settings.browserDefaultViewport,
137 DEFAULT_UNIFIED_SETTINGS.browserDefaultViewport,
138 )
139 ? []
140 : ["Browser viewport"]),
141 ...(settings.browserDefaultZoomFactor !== DEFAULT_UNIFIED_SETTINGS.browserDefaultZoomFactor
142 ? ["Browser zoom"]
143 : []),
144 ...(settings.browserDefaultAppearance !== DEFAULT_UNIFIED_SETTINGS.browserDefaultAppearance
145 ? ["Browser appearance"]
146 : []),
147 ...(settings.browserRecordingFrameRate !== DEFAULT_UNIFIED_SETTINGS.browserRecordingFrameRate
148 ? ["Recording frame rate"]
149 : []),
150 ...(settings.browserRecordingShowKeyPresses ? ["Recording key presses"] : []),
151 ...(settings.browserRecordingShowMousePresses ? ["Recording mouse presses"] : []),
152 ...(settings.browserLinkTarget !== DEFAULT_UNIFIED_SETTINGS.browserLinkTarget
153 ? ["Open links in"]
154 : []),
155 ...(settings.browserAutoShowFloatingPreview !==
156 DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview
157 ? ["Floating preview"]
158 : []),
159 ...(settings.pullRequestLinksOpenInApp !== DEFAULT_UNIFIED_SETTINGS.pullRequestLinksOpenInApp
160 ? ["Open pull requests in T3 Code"]
161 : []),
162 ];
163}
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;
186}
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 };
199}
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}`;
218}
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}.`;
247}
248
249export function buildProviderInstanceUpdatePatch(input: {
250 readonly settings: Pick<ServerSettings, "providerInstances">;
251 readonly instanceId: ProviderInstanceId;
252 readonly instance: ProviderInstanceConfig;
253 readonly textGenerationModelSelection?:
254 | ServerSettings["textGenerationModelSelection"]
255 | undefined;
256}): Partial<UnifiedSettings> {
257 return {
258 providerInstances: {
259 ...input.settings.providerInstances,
260 [input.instanceId]: input.instance,
261 },
262 ...(input.textGenerationModelSelection !== undefined
263 ? { textGenerationModelSelection: input.textGenerationModelSelection }
264 : {}),
265 };
266}
267
268export const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
269
270type BackgroundActivityOverridePatch = Partial<{
271 [K in keyof BackgroundActivitySettings["overrides"]]:
272 | BackgroundActivitySettings["overrides"][K]
273 | undefined;
274}>;
275
276export function durationToSeconds(duration: Duration.Duration): number {
277 return Math.round(Duration.toMillis(duration) / 1_000);
278}
279
280export function normalizeIntervalSeconds(value: number | null, minimum = 0): number {
281 if (value === null || !Number.isFinite(value)) {
282 return minimum;
283 }
284 return Math.max(minimum, Math.round(value));
285}
286
287export function backgroundActivityOverrideSettings(
288 current: BackgroundActivitySettings,
289 resolved: ReturnType<typeof resolveServerBackgroundActivitySettings>,
290 overrides: BackgroundActivityOverridePatch,
291) {
292 const nextOverrides: BackgroundActivityOverridePatch = {
293 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
294 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
295 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
296 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
297 idleClientTtl: resolved.idleClientTtl,
298 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
299 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
300 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
301 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
302 ...overrides,
303 };
304 for (const [key, value] of Object.entries(nextOverrides)) {
305 if (value === undefined) {
306 delete nextOverrides[key as keyof typeof nextOverrides];
307 }
308 }
309 return {
310 backgroundActivity: {
311 schemaVersion: 1 as const,
312 profile: "custom" as const,
313 baseProfile: getBackgroundActivityBaseProfile(current),
314 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
315 },
316 };
317}