Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

BackgroundActivitySettings.tsx

496 lines19.8 KB

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