Open History to see the last commit
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";
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 // Storage can be unavailable in restricted browser contexts.
51 }
52}
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 );
75}
76
77export function resolveBackgroundActivityProfileOption(
78 settings: ServerSettings,
79): BackgroundActivityProfile | "advanced" {
80 const resolved = resolveServerBackgroundActivitySettings(settings);
81 const normalized = normalizeBackgroundActivitySettings({
82 schemaVersion: 1,
83 profile: "custom",
84 baseProfile: resolved.profile,
85 overrides: {
86 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
87 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
88 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
89 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
90 idleClientTtl: resolved.idleClientTtl,
91 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
92 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
93 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
94 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
95 },
96 });
97 return normalized.profile === "custom" ? "advanced" : normalized.profile;
98}
99
100export function backgroundActivitySharedPolicySettings(
101 settings: ServerSettings,
102 profile: BackgroundActivityProfile,
103): BackgroundActivitySettings {
104 const normalized = normalizeServerBackgroundActivitySettings(settings);
105 return {
106 schemaVersion: 1,
107 profile: "custom",
108 baseProfile: profile,
109 overrides: normalized.profile === "custom" ? normalized.overrides : {},
110 };
111}
112
113function collapseOtelSignalsUrl(input: {
114 readonly tracesUrl: string;
115 readonly metricsUrl: string;
116}): string | null {
117 const tracesSuffix = "/traces";
118 const metricsSuffix = "/metrics";
119 if (!input.tracesUrl.endsWith(tracesSuffix) || !input.metricsUrl.endsWith(metricsSuffix)) {
120 return null;
121 }
122
123 const tracesBase = input.tracesUrl.slice(0, -tracesSuffix.length);
124 const metricsBase = input.metricsUrl.slice(0, -metricsSuffix.length);
125 if (tracesBase !== metricsBase) {
126 return null;
127 }
128
129 return `${tracesBase}/{traces,metrics}`;
130}
131
132export function formatDiagnosticsDescription(input: {
133 readonly localTracingEnabled: boolean;
134 readonly otlpTracesEnabled: boolean;
135 readonly otlpTracesUrl?: string | undefined;
136 readonly otlpMetricsEnabled: boolean;
137 readonly otlpMetricsUrl?: string | undefined;
138}): string {
139 const mode = input.localTracingEnabled ? "Local trace file" : "Terminal logs only";
140 const tracesUrl = input.otlpTracesEnabled ? input.otlpTracesUrl : undefined;
141 const metricsUrl = input.otlpMetricsEnabled ? input.otlpMetricsUrl : undefined;
142
143 if (tracesUrl && metricsUrl) {
144 const collapsedUrl = collapseOtelSignalsUrl({ tracesUrl, metricsUrl });
145 return collapsedUrl
146 ? `${mode}. Exporting OTEL to ${collapsedUrl}.`
147 : `${mode}. Exporting OTEL traces to ${tracesUrl} and metrics to ${metricsUrl}.`;
148 }
149
150 if (tracesUrl) {
151 return `${mode}. Exporting OTEL traces to ${tracesUrl}.`;
152 }
153
154 if (metricsUrl) {
155 return `${mode}. Exporting OTEL metrics to ${metricsUrl}.`;
156 }
157
158 return `${mode}.`;
159}
160
161export function buildProviderInstanceUpdatePatch(input: {
162 readonly settings: Pick<ServerSettings, "providers" | "providerInstances">;
163 readonly instanceId: ProviderInstanceId;
164 readonly instance: ProviderInstanceConfig;
165 readonly driver: ProviderDriverKind;
166 readonly isDefault: boolean;
167 readonly textGenerationModelSelection?:
168 | ServerSettings["textGenerationModelSelection"]
169 | undefined;
170}): Partial<UnifiedSettings> {
171 type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
172 const legacyProviderDefaults = DEFAULT_UNIFIED_SETTINGS.providers as Record<
173 string,
174 LegacyProviderSettings | undefined
175 >;
176 const legacyProviderDefault = input.isDefault ? legacyProviderDefaults[input.driver] : undefined;
177 return {
178 ...(legacyProviderDefault !== undefined
179 ? {
180 providers: {
181 ...input.settings.providers,
182 [input.driver]: legacyProviderDefault,
183 } as ServerSettings["providers"],
184 }
185 : {}),
186 providerInstances: {
187 ...input.settings.providerInstances,
188 [input.instanceId]: input.instance,
189 },
190 ...(input.textGenerationModelSelection !== undefined
191 ? { textGenerationModelSelection: input.textGenerationModelSelection }
192 : {}),
193 };
194}
195
196// ── Background-activity interval helpers ─────────────────────────────
197// Shared by the General panel's interval rows and the Providers panel's
198// health-check row.
199
200export const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
201
202type BackgroundActivityOverridePatch = Partial<{
203 [K in keyof BackgroundActivitySettings["overrides"]]:
204 | BackgroundActivitySettings["overrides"][K]
205 | undefined;
206}>;
207
208export function durationToSeconds(duration: Duration.Duration): number {
209 return Math.round(Duration.toMillis(duration) / 1_000);
210}
211
212export function normalizeIntervalSeconds(value: number | null, minimum = 0): number {
213 if (value === null || !Number.isFinite(value)) {
214 return minimum;
215 }
216 return Math.max(minimum, Math.round(value));
217}
218
219export function backgroundActivityOverrideSettings(
220 current: BackgroundActivitySettings,
221 resolved: ReturnType<typeof resolveServerBackgroundActivitySettings>,
222 overrides: BackgroundActivityOverridePatch,
223) {
224 const nextOverrides: BackgroundActivityOverridePatch = {
225 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
226 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
227 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
228 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
229 idleClientTtl: resolved.idleClientTtl,
230 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
231 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
232 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
233 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
234 ...overrides,
235 };
236 for (const [key, value] of Object.entries(nextOverrides)) {
237 if (value === undefined) {
238 delete nextOverrides[key as keyof typeof nextOverrides];
239 }
240 }
241 return {
242 backgroundActivity: {
243 schemaVersion: 1 as const,
244 profile: "custom" as const,
245 baseProfile: getBackgroundActivityBaseProfile(current),
246 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
247 },
248 };
249}