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 {
12 DEFAULT_UNIFIED_SETTINGS,
13 MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
14 MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS,
15} from "@t3tools/contracts/settings";
16import {
17 getBackgroundActivityBaseProfile,
18 normalizeBackgroundActivitySettings,
19 normalizeServerBackgroundActivitySettings,
20 resolveServerBackgroundActivitySettings,
21} from "@t3tools/shared/backgroundActivitySettings";
22import * as Duration from "effect/Duration";
23import * as Equal from "effect/Equal";
24
25export function isProjectGroupingEnabled(mode: SidebarProjectGroupingMode): boolean {
26 return mode !== "separate";
27}
28
29export function projectGroupingModeFromToggle(
30 enabled: boolean,
31 lastEnabledMode: SidebarProjectGroupingMode = "repository",
32): SidebarProjectGroupingMode {
33 if (!enabled) return "separate";
34 return lastEnabledMode === "repository_path" ? "repository_path" : "repository";
35}
36
37const LAST_ENABLED_PROJECT_GROUPING_MODE_KEY = "t3code:last-enabled-project-grouping-mode";
38
39export function readLastEnabledProjectGroupingMode(): SidebarProjectGroupingMode {
40 try {
41 return localStorage.getItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY) === "repository_path"
42 ? "repository_path"
43 : "repository";
44 } catch {
45 return "repository";
46 }
47}
48
49export function rememberEnabledProjectGroupingMode(mode: SidebarProjectGroupingMode): void {
50 if (mode === "separate") return;
51 try {
52 localStorage.setItem(LAST_ENABLED_PROJECT_GROUPING_MODE_KEY, mode);
53 } catch {}
54}
55
56export function hasChangedBackgroundActivitySettings(
57 settings: Pick<
58 UnifiedSettings,
59 | "backgroundActivity"
60 | "backgroundActivityProfile"
61 | "automaticGitFetchInterval"
62 | "providerHealthRefreshInterval"
63 >,
64): boolean {
65 return (
66 !Equal.equals(settings.backgroundActivity, DEFAULT_UNIFIED_SETTINGS.backgroundActivity) ||
67 settings.backgroundActivityProfile !== DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile ||
68 !Equal.equals(
69 settings.automaticGitFetchInterval,
70 DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
71 ) ||
72 !Equal.equals(
73 settings.providerHealthRefreshInterval,
74 DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval,
75 )
76 );
77}
78
79type TypographySettings = Pick<
80 UnifiedSettings,
81 | "fontFamilySans"
82 | "fontFamilyComposer"
83 | "fontFamilyCode"
84 | "fontFamilyTerminal"
85 | "fontSizeInterface"
86 | "fontSizePrompt"
87 | "fontSizeCode"
88 | "fontSizeTerminal"
89>;
90
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 | "browserSearchEngine"
122 | "browserCustomSearchUrl"
123 | "browserAutoShowFloatingPreview"
124 | "pullRequestLinksOpenInApp"
125>;
126
127function isSamePreviewViewport(
128 left: PreviewViewportSetting,
129 right: PreviewViewportSetting,
130): boolean {
131 if (left._tag !== right._tag) return false;
132 if (left._tag === "fill" || right._tag === "fill") return true;
133 if (left.width !== right.width || left.height !== right.height) return false;
134 return left._tag === "preset" && right._tag === "preset"
135 ? left.presetId === right.presetId
136 : true;
137}
138
139export function getChangedBrowserSettingLabels(settings: BrowserDefaultSettings): string[] {
140 return [
141 ...(isSamePreviewViewport(
142 settings.browserDefaultViewport,
143 DEFAULT_UNIFIED_SETTINGS.browserDefaultViewport,
144 )
145 ? []
146 : ["Browser viewport"]),
147 ...(settings.browserDefaultZoomFactor !== DEFAULT_UNIFIED_SETTINGS.browserDefaultZoomFactor
148 ? ["Browser zoom"]
149 : []),
150 ...(settings.browserDefaultAppearance !== DEFAULT_UNIFIED_SETTINGS.browserDefaultAppearance
151 ? ["Browser appearance"]
152 : []),
153 ...(settings.browserRecordingFrameRate !== DEFAULT_UNIFIED_SETTINGS.browserRecordingFrameRate
154 ? ["Recording frame rate"]
155 : []),
156 ...(settings.browserRecordingShowKeyPresses ? ["Recording key presses"] : []),
157 ...(settings.browserRecordingShowMousePresses ? ["Recording mouse presses"] : []),
158 ...(settings.browserLinkTarget !== DEFAULT_UNIFIED_SETTINGS.browserLinkTarget
159 ? ["Open links in"]
160 : []),
161 ...(settings.browserSearchEngine !== DEFAULT_UNIFIED_SETTINGS.browserSearchEngine ||
162 settings.browserCustomSearchUrl !== DEFAULT_UNIFIED_SETTINGS.browserCustomSearchUrl
163 ? ["Search engine"]
164 : []),
165 ...(settings.browserAutoShowFloatingPreview !==
166 DEFAULT_UNIFIED_SETTINGS.browserAutoShowFloatingPreview
167 ? ["Floating preview"]
168 : []),
169 ...(settings.pullRequestLinksOpenInApp !== DEFAULT_UNIFIED_SETTINGS.pullRequestLinksOpenInApp
170 ? ["Open pull requests in T3 Code"]
171 : []),
172 ];
173}
174
175export function resolveBackgroundActivityProfileOption(
176 settings: ServerSettings,
177): BackgroundActivityProfile | "advanced" {
178 const resolved = resolveServerBackgroundActivitySettings(settings);
179 const normalized = normalizeBackgroundActivitySettings({
180 schemaVersion: 1,
181 profile: "custom",
182 baseProfile: resolved.profile,
183 overrides: {
184 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
185 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
186 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
187 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
188 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
189 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
190 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
191 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
192 },
193 });
194 return normalized.profile === "custom" ? "advanced" : normalized.profile;
195}
196
197export function backgroundActivitySharedPolicySettings(
198 settings: ServerSettings,
199 profile: BackgroundActivityProfile,
200): BackgroundActivitySettings {
201 const normalized = normalizeServerBackgroundActivitySettings(settings);
202 return {
203 schemaVersion: 1,
204 profile: "custom",
205 baseProfile: profile,
206 overrides: normalized.profile === "custom" ? normalized.overrides : {},
207 };
208}
209
210export function buildProviderInstanceUpdatePatch(input: {
211 readonly settings: Pick<ServerSettings, "providerInstances">;
212 readonly instanceId: ProviderInstanceId;
213 readonly instance: ProviderInstanceConfig;
214 readonly textGenerationModelSelection?:
215 | ServerSettings["textGenerationModelSelection"]
216 | undefined;
217}): Partial<UnifiedSettings> {
218 return {
219 providerInstances: {
220 ...input.settings.providerInstances,
221 [input.instanceId]: input.instance,
222 },
223 ...(input.textGenerationModelSelection !== undefined
224 ? { textGenerationModelSelection: input.textGenerationModelSelection }
225 : {}),
226 };
227}
228
229export const PROVIDER_HEALTH_INTERVAL_STEP_SECONDS = 30;
230
231type BackgroundActivityOverridePatch = Partial<{
232 [K in keyof BackgroundActivitySettings["overrides"]]:
233 | BackgroundActivitySettings["overrides"][K]
234 | undefined;
235}>;
236
237export function durationToSeconds(duration: Duration.Duration): number {
238 return Math.round(Duration.toMillis(duration) / 1_000);
239}
240
241export function normalizeIntervalSeconds(value: number | null, minimum = 0): number {
242 if (value === null || !Number.isFinite(value)) {
243 return minimum;
244 }
245 return Math.max(minimum, Math.round(value));
246}
247
248export function backgroundActivityOverrideSettings(
249 current: BackgroundActivitySettings,
250 resolved: ReturnType<typeof resolveServerBackgroundActivitySettings>,
251 overrides: BackgroundActivityOverridePatch,
252) {
253 const nextOverrides: BackgroundActivityOverridePatch = {
254 automaticGitFetchInterval: resolved.automaticGitFetchInterval,
255 providerHealthRefreshInterval: resolved.providerHealthRefreshInterval,
256 hostPowerMonitorActiveInterval: resolved.hostPowerMonitorActiveInterval,
257 hostPowerMonitorIdleInterval: resolved.hostPowerMonitorIdleInterval,
258 pauseWhenHostLocked: resolved.pauseWhenHostLocked,
259 pauseWhenHostLowPower: resolved.pauseWhenHostLowPower,
260 pauseWhenClientLowPower: resolved.pauseWhenClientLowPower,
261 pauseWhenOnBattery: resolved.pauseWhenOnBattery,
262 ...overrides,
263 };
264 for (const [key, value] of Object.entries(nextOverrides)) {
265 if (value === undefined) {
266 delete nextOverrides[key as keyof typeof nextOverrides];
267 }
268 }
269 return {
270 backgroundActivity: {
271 schemaVersion: 1 as const,
272 profile: "custom" as const,
273 baseProfile: getBackgroundActivityBaseProfile(current),
274 overrides: nextOverrides as BackgroundActivitySettings["overrides"],
275 },
276 };
277}
278
279/**
280 * Saving a shorter age settles threads at once, so typing stays in `draft` until the edit is
281 * finished. `pending` is the submission in flight; `saved` is the only value a draft falls back to.
282 */
283export interface AutoSettleDaysField {
284 readonly saved: number;
285 readonly draft: string;
286 readonly dirty: boolean;
287 readonly pending: number | null;
288 readonly revision: number;
289}
290
291export function autoSettleDaysField(saved: number): AutoSettleDaysField {
292 return { saved, draft: String(saved), dirty: false, pending: null, revision: 0 };
293}
294
295export function syncAutoSettleDaysField(
296 field: AutoSettleDaysField,
297 saved: number,
298): AutoSettleDaysField {
299 // An earlier save can be confirmed while a later one is still in flight.
300 const pending = field.pending === saved ? null : field.pending;
301 if (field.saved === saved && pending === field.pending) return field;
302 return {
303 ...field,
304 saved,
305 pending,
306 draft: field.dirty ? field.draft : String(pending ?? saved),
307 };
308}
309
310export function editAutoSettleDaysField(
311 field: AutoSettleDaysField,
312 draft: string,
313): AutoSettleDaysField {
314 return { ...field, draft, dirty: true };
315}
316
317export function cancelAutoSettleDaysField(field: AutoSettleDaysField): AutoSettleDaysField {
318 return { ...field, draft: String(field.pending ?? field.saved), dirty: false };
319}
320
321export function commitAutoSettleDaysField(field: AutoSettleDaysField): {
322 readonly field: AutoSettleDaysField;
323 readonly submit: number | null;
324} {
325 const current = field.pending ?? field.saved;
326 const days = field.draft.trim() === "" ? Number.NaN : Number(field.draft);
327 if (
328 !Number.isInteger(days) ||
329 days < MIN_SIDEBAR_AUTO_SETTLE_AFTER_DAYS ||
330 days > MAX_SIDEBAR_AUTO_SETTLE_AFTER_DAYS
331 ) {
332 return { field: { ...field, draft: String(current), dirty: false }, submit: null };
333 }
334 const settled = { ...field, draft: String(days), dirty: false };
335 // An edit ending on the saved value is sent again: a save can land on the shown environment
336 // and fail on another, and retyping the number is how it is retried.
337 if (!field.dirty || days === field.pending) return { field: settled, submit: null };
338 return { field: { ...settled, pending: days, revision: field.revision + 1 }, submit: days };
339}
340
341export function failAutoSettleDaysField(
342 field: AutoSettleDaysField,
343 revision: number,
344): AutoSettleDaysField {
345 if (field.revision !== revision) return field;
346 return { ...field, pending: null, draft: field.dirty ? field.draft : String(field.saved) };
347}