Open History to see the last commit
1import { useScopedSettingsWriteAllowed } from "./useScopedSettings";
2import { SettingsIcon } from "lucide-react";
3import { useState } from "react";
4import { type BackgroundActivityProfile } from "@t3tools/contracts";
5import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
6import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
7import * as Duration from "effect/Duration";
8import * as Equal from "effect/Equal";
9import {
10 useScopedSettings,
11 useScopedSettingsMixed,
12 useUpdateScopedSettings,
13} from "./useScopedSettings";
14import { useSettingsScope } from "./SettingsScopeContext";
15import { Button } from "../ui/button";
16import {
17 Dialog,
18 DialogDescription,
19 DialogFooter,
20 DialogHeader,
21 DialogPanel,
22 DialogPopup,
23 DialogTitle,
24} from "../ui/dialog";
25import {
26 NumberField,
27 NumberFieldDecrement,
28 NumberFieldGroup,
29 NumberFieldIncrement,
30 NumberFieldInput,
31} from "../ui/number-field";
32import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
33import { Switch } from "../ui/switch";
34import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
35import {
36 backgroundActivityOverrideSettings,
37 backgroundActivitySharedPolicySettings,
38 durationToSeconds,
39 normalizeIntervalSeconds,
40 PROVIDER_HEALTH_INTERVAL_STEP_SECONDS,
41 resolveBackgroundActivityProfileOption,
42} from "./SettingsPanels.logic";
43import { PolicyTooltip, SettingResetButton, SettingsRow } from "./settingsLayout";
44import { searchableSetting } from "./settingsSearch";
45
46const BACKGROUND_ACTIVITY_PROFILE_LABELS: Record<BackgroundActivityProfile, string> = {
47 balanced: "Balanced",
48 performance: "Performance",
49 "battery-saver": "Battery saver",
50};
51
52type BackgroundActivityProfileOption = BackgroundActivityProfile | "advanced";
53
54const BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS: Record<BackgroundActivityProfileOption, string> = {
55 ...BACKGROUND_ACTIVITY_PROFILE_LABELS,
56 advanced: "Advanced",
57};
58
59const BACKGROUND_ACTIVITY_PROFILE_DESCRIPTIONS: Record<BackgroundActivityProfile, string> = {
60 balanced: "Pauses probes for idle clients, locked hosts, or low power mode.",
61 performance: "Allows scoped background probes while any subscribed client remains connected.",
62 "battery-saver": "Also pauses background probes when the host or client is on battery.",
63};
64
65const ADVANCED_BACKGROUND_ACTIVITY_DESCRIPTION = "Uses custom intervals.";
66
67const BACKGROUND_ACTIVITY_BOOLEAN_OVERRIDES: ReadonlyArray<{
68 readonly key:
69 | "pauseWhenHostLocked"
70 | "pauseWhenHostLowPower"
71 | "pauseWhenClientLowPower"
72 | "pauseWhenOnBattery";
73 readonly label: string;
74}> = [
75 { key: "pauseWhenHostLocked", label: "Pause when host is locked" },
76 { key: "pauseWhenHostLowPower", label: "Pause on host low power" },
77 { key: "pauseWhenClientLowPower", label: "Pause on client low power" },
78 { key: "pauseWhenOnBattery", label: "Pause on battery" },
79];
80
81function resetBackgroundActivitySettings() {
82 return {
83 backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
84 };
85}
86
87function backgroundActivityProfileSettings(profile: BackgroundActivityProfile) {
88 return {
89 backgroundActivity: {
90 schemaVersion: 1 as const,
91 profile,
92 overrides: {},
93 },
94 };
95}
96
97function BackgroundActivityAdvancedDialog({
98 open,
99 onOpenChange,
100}: {
101 readonly open: boolean;
102 readonly onOpenChange: (open: boolean) => void;
103}) {
104 const canWriteSettings = useScopedSettingsWriteAllowed();
105 const settings = useScopedSettings();
106 const updateSettings = useUpdateScopedSettings();
107 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
108 const activeProfile = resolvedBackgroundActivity.profile;
109 const automaticGitFetchIntervalSeconds = durationToSeconds(
110 resolvedBackgroundActivity.automaticGitFetchInterval,
111 );
112 const providerHealthRefreshIntervalSeconds = durationToSeconds(
113 resolvedBackgroundActivity.providerHealthRefreshInterval,
114 );
115 const hostPowerMonitorActiveIntervalSeconds = durationToSeconds(
116 resolvedBackgroundActivity.hostPowerMonitorActiveInterval,
117 );
118 const hostPowerMonitorIdleIntervalSeconds = durationToSeconds(
119 resolvedBackgroundActivity.hostPowerMonitorIdleInterval,
120 );
121
122 return (
123 <Dialog open={open && canWriteSettings} onOpenChange={onOpenChange}>
124 <DialogPopup className="max-w-xl">
125 <DialogHeader>
126 <DialogTitle>Background Activity</DialogTitle>
127 <DialogDescription>
128 Tune the shared power policy and the background intervals that feed it.
129 </DialogDescription>
130 </DialogHeader>
131 <DialogPanel>
132 <fieldset
133 disabled={!canWriteSettings}
134 className="min-w-0 overflow-hidden rounded-xl border bg-card text-card-foreground"
135 >
136 <div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
137 <div className="min-w-0 space-y-1">
138 <div className="text-sm font-medium">Shared policy</div>
139 <p className="text-xs leading-relaxed text-muted-foreground">
140 Controls whether background work may run after a subscribed interval fires.
141 </p>
142 </div>
143 <Select
144 value={activeProfile}
145 onValueChange={(value) => {
146 if (
147 value === "balanced" ||
148 value === "performance" ||
149 value === "battery-saver"
150 ) {
151 updateSettings({
152 backgroundActivity: backgroundActivitySharedPolicySettings(settings, value),
153 });
154 }
155 }}
156 >
157 <SelectTrigger
158 size="sm"
159 className="w-full sm:w-40"
160 aria-label="Shared background policy"
161 >
162 <SelectValue>{BACKGROUND_ACTIVITY_PROFILE_LABELS[activeProfile]}</SelectValue>
163 </SelectTrigger>
164 <SelectPopup align="end" alignItemWithTrigger={false}>
165 <SelectItem hideIndicator value="balanced">
166 {BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced}
167 </SelectItem>
168 <SelectItem hideIndicator value="performance">
169 {BACKGROUND_ACTIVITY_PROFILE_LABELS.performance}
170 </SelectItem>
171 <SelectItem hideIndicator value="battery-saver">
172 {BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"]}
173 </SelectItem>
174 </SelectPopup>
175 </Select>
176 </div>
177
178 <div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
179 <div className="min-w-0 space-y-1">
180 <div className="text-sm font-medium">
181 {searchableSetting("git-fetch-interval").title}
182 </div>
183 <p className="text-xs leading-relaxed text-muted-foreground">
184 Refresh remote branch status in the background.
185 </p>
186 </div>
187 <div className="flex shrink-0 items-center gap-2">
188 <NumberField
189 value={automaticGitFetchIntervalSeconds}
190 min={0}
191 step={5}
192 size="sm"
193 className="w-32"
194 onValueChange={(value) =>
195 updateSettings(
196 backgroundActivityOverrideSettings(
197 settings.backgroundActivity,
198 resolvedBackgroundActivity,
199 {
200 automaticGitFetchInterval: Duration.seconds(
201 normalizeIntervalSeconds(value),
202 ),
203 },
204 ),
205 )
206 }
207 >
208 <NumberFieldGroup>
209 <NumberFieldDecrement aria-label="Decrease Git fetch interval" />
210 <NumberFieldInput aria-label="Git fetch interval in seconds" />
211 <NumberFieldIncrement aria-label="Increase Git fetch interval" />
212 </NumberFieldGroup>
213 </NumberField>
214 <span className="text-xs text-muted-foreground">seconds</span>
215 </div>
216 </div>
217
218 <div className="flex flex-col gap-3 px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
219 <div className="min-w-0 space-y-1">
220 <div className="text-sm font-medium">Provider health interval</div>
221 <p className="text-xs leading-relaxed text-muted-foreground">
222 Refresh provider availability, versions, and auth state. Model catalog updates
223 follow Provider update checks.
224 </p>
225 </div>
226 <div className="flex shrink-0 items-center gap-2">
227 <NumberField
228 value={providerHealthRefreshIntervalSeconds}
229 min={0}
230 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
231 size="sm"
232 className="w-32"
233 onValueChange={(value) =>
234 updateSettings(
235 backgroundActivityOverrideSettings(
236 settings.backgroundActivity,
237 resolvedBackgroundActivity,
238 {
239 providerHealthRefreshInterval: Duration.seconds(
240 normalizeIntervalSeconds(value),
241 ),
242 },
243 ),
244 )
245 }
246 >
247 <NumberFieldGroup>
248 <NumberFieldDecrement aria-label="Decrease provider health interval" />
249 <NumberFieldInput aria-label="Provider health interval in seconds" />
250 <NumberFieldIncrement aria-label="Increase provider health interval" />
251 </NumberFieldGroup>
252 </NumberField>
253 <span className="text-xs text-muted-foreground">seconds</span>
254 </div>
255 </div>
256
257 <div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
258 <div className="min-w-0 space-y-1">
259 <div className="text-sm font-medium">Host power monitor</div>
260 <p className="text-xs leading-relaxed text-muted-foreground">
261 Poll host power state while clients are active.
262 </p>
263 </div>
264 <div className="flex shrink-0 items-center gap-2">
265 <NumberField
266 value={hostPowerMonitorActiveIntervalSeconds}
267 min={5}
268 step={5}
269 size="sm"
270 className="w-32"
271 onValueChange={(value) =>
272 updateSettings(
273 backgroundActivityOverrideSettings(
274 settings.backgroundActivity,
275 resolvedBackgroundActivity,
276 {
277 hostPowerMonitorActiveInterval: Duration.seconds(
278 normalizeIntervalSeconds(value, 5),
279 ),
280 },
281 ),
282 )
283 }
284 >
285 <NumberFieldGroup>
286 <NumberFieldDecrement aria-label="Decrease active host power interval" />
287 <NumberFieldInput aria-label="Active host power interval in seconds" />
288 <NumberFieldIncrement aria-label="Increase active host power interval" />
289 </NumberFieldGroup>
290 </NumberField>
291 <span className="text-xs text-muted-foreground">seconds</span>
292 </div>
293 </div>
294
295 <div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
296 <div className="min-w-0 space-y-1">
297 <div className="text-sm font-medium">Idle host monitor</div>
298 <p className="text-xs leading-relaxed text-muted-foreground">
299 Poll host power state when no foreground client is active.
300 </p>
301 </div>
302 <div className="flex shrink-0 items-center gap-2">
303 <NumberField
304 value={hostPowerMonitorIdleIntervalSeconds}
305 min={5}
306 step={30}
307 size="sm"
308 className="w-32"
309 onValueChange={(value) =>
310 updateSettings(
311 backgroundActivityOverrideSettings(
312 settings.backgroundActivity,
313 resolvedBackgroundActivity,
314 {
315 hostPowerMonitorIdleInterval: Duration.seconds(
316 normalizeIntervalSeconds(value, 5),
317 ),
318 },
319 ),
320 )
321 }
322 >
323 <NumberFieldGroup>
324 <NumberFieldDecrement aria-label="Decrease idle host power interval" />
325 <NumberFieldInput aria-label="Idle host power interval in seconds" />
326 <NumberFieldIncrement aria-label="Increase idle host power interval" />
327 </NumberFieldGroup>
328 </NumberField>
329 <span className="text-xs text-muted-foreground">seconds</span>
330 </div>
331 </div>
332
333 <div className="grid gap-0 border-t sm:grid-cols-2">
334 {BACKGROUND_ACTIVITY_BOOLEAN_OVERRIDES.map(({ key, label }) => (
335 <label
336 key={key}
337 className="flex items-center justify-between gap-3 border-b px-4 py-3 last:border-b-0 sm:border-r sm:even:border-r-0"
338 >
339 <span className="text-sm font-medium">{label}</span>
340 <Switch
341 checked={resolvedBackgroundActivity[key]}
342 onCheckedChange={(checked) =>
343 updateSettings(
344 backgroundActivityOverrideSettings(
345 settings.backgroundActivity,
346 resolvedBackgroundActivity,
347 {
348 [key]: Boolean(checked),
349 },
350 ),
351 )
352 }
353 aria-label={label}
354 />
355 </label>
356 ))}
357 </div>
358 </fieldset>
359 </DialogPanel>
360 <DialogFooter>
361 <Button
362 variant="outline"
363 disabled={!canWriteSettings}
364 onClick={() => updateSettings(resetBackgroundActivitySettings())}
365 >
366 Reset all
367 </Button>
368 <Button onClick={() => onOpenChange(false)}>Done</Button>
369 </DialogFooter>
370 </DialogPopup>
371 </Dialog>
372 );
373}
374
375export function BackgroundActivitySettingsRow() {
376 const settings = useScopedSettings();
377 const updateSettings = useUpdateScopedSettings();
378 const { scope, environment } = useSettingsScope();
379 const environmentId = environment?.environmentId ?? null;
380 const isEnvironmentScope = scope.environmentIds.length === 1 && environmentId !== null;
381 const [backgroundActivityDialogOpen, setBackgroundActivityDialogOpen] = useState(false);
382 const mixedBackgroundActivity = useScopedSettingsMixed(["backgroundActivity"]);
383 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
384 const activeBackgroundActivityProfile = resolvedBackgroundActivity.profile;
385 const backgroundActivityProfileOption = resolveBackgroundActivityProfileOption(settings);
386 const backgroundActivityDescription =
387 backgroundActivityProfileOption === "advanced"
388 ? `${ADVANCED_BACKGROUND_ACTIVITY_DESCRIPTION} Shared policy: ${
389 BACKGROUND_ACTIVITY_PROFILE_LABELS[activeBackgroundActivityProfile]
390 }.`
391 : BACKGROUND_ACTIVITY_PROFILE_DESCRIPTIONS[resolvedBackgroundActivity.profile];
392 const canResetBackgroundActivity = !Equal.equals(
393 settings.backgroundActivity,
394 DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
395 );
396
397 return (
398 <SettingsRow
399 serverScoped
400 settingKeys={["backgroundActivity"]}
401 id={searchableSetting("background-activity").id}
402 title={
403 <span className="inline-flex items-center gap-1.5">
404 {searchableSetting("background-activity").title}
405 <PolicyTooltip>
406 This shared policy gates background work such as Git refreshes and provider health
407 probes after their individual intervals elapse.
408 </PolicyTooltip>
409 </span>
410 }
411 description={backgroundActivityDescription}
412 resetAction={
413 canResetBackgroundActivity ? (
414 <SettingResetButton
415 label="background activity"
416 onClick={() => updateSettings(resetBackgroundActivitySettings())}
417 />
418 ) : null
419 }
420 control={
421 <>
422 <Select
423 value={mixedBackgroundActivity ? null : backgroundActivityProfileOption}
424 onValueChange={(value) => {
425 if (value === "advanced") {
426 if (isEnvironmentScope) setBackgroundActivityDialogOpen(true);
427 return;
428 }
429 if (value === "balanced" || value === "performance" || value === "battery-saver") {
430 updateSettings(backgroundActivityProfileSettings(value));
431 }
432 }}
433 >
434 <SelectTrigger
435 size="sm"
436 className="w-full sm:w-40"
437 aria-label="Background activity profile"
438 >
439 <SelectValue>
440 {(value: BackgroundActivityProfileOption | null) =>
441 value === null ? "Mixed" : BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS[value]
442 }
443 </SelectValue>
444 </SelectTrigger>
445 <SelectPopup align="end" alignItemWithTrigger={false}>
446 <SelectItem hideIndicator value="balanced">
447 {BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced}
448 </SelectItem>
449 <SelectItem hideIndicator value="performance">
450 {BACKGROUND_ACTIVITY_PROFILE_LABELS.performance}
451 </SelectItem>
452 <SelectItem hideIndicator value="battery-saver">
453 {BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"]}
454 </SelectItem>
455 <SelectItem hideIndicator value="advanced" disabled={!isEnvironmentScope}>
456 {isEnvironmentScope
457 ? BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS.advanced
458 : `${BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS.advanced} (one environment)`}
459 </SelectItem>
460 </SelectPopup>
461 </Select>
462 {backgroundActivityProfileOption === "advanced" && isEnvironmentScope ? (
463 <Tooltip>
464 <TooltipTrigger
465 render={
466 <Button
467 size="icon-sm"
468 variant="outline"
469 aria-label="Configure advanced background activity"
470 onClick={() => setBackgroundActivityDialogOpen(true)}
471 >
472 <SettingsIcon className="size-4" />
473 </Button>
474 }
475 />
476 <TooltipPopup side="top">Configure background activity</TooltipPopup>
477 </Tooltip>
478 ) : null}
479 <BackgroundActivityAdvancedDialog
480 open={backgroundActivityDialogOpen && isEnvironmentScope}
481 onOpenChange={setBackgroundActivityDialogOpen}
482 />
483 </>
484 }
485 />
486 );
487}