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

BackgroundActivitySettings.tsx

489 lines19.4 KB

1import { useScopedSettingsWriteAllowed } from "./useScopedSettings";
2import { SettingsIcon } from "lucide-react";
3import { msg, T, useGT, useMessages, type Msg } from "gt-react";
4import { 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}: {
98 readonly open: boolean;
99 readonly onOpenChange: (open: boolean) => void;
100}) {
101 const searchableSetting = useSearchableSetting();
102 const gt = useGT();
103 const m = useMessages();
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>
127 <T>Background Activity</T>
128 </DialogTitle>
129 <DialogDescription>
130 <T>Tune the shared power policy and the background intervals that feed it.</T>
131 </DialogDescription>
132 </DialogHeader>
133 <DialogPanel>
134 <fieldset
135 disabled={!canWriteSettings}
136 className="min-w-0 overflow-hidden rounded-xl border bg-card text-card-foreground"
137 >
138 <div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
139 <div className="min-w-0 space-y-1">
140 <div className="text-sm font-medium">
141 <T>Shared policy</T>
142 </div>
143 <p className="text-xs leading-relaxed text-muted-foreground">
144 <T>Controls whether background work may run after a subscribed interval fires.</T>
145 </p>
146 </div>
147 <Select
148 value={activeProfile}
149 onValueChange={(value) => {
150 if (
151 value === "balanced" ||
152 value === "performance" ||
153 value === "battery-saver"
154 ) {
155 updateSettings({
156 backgroundActivity: backgroundActivitySharedPolicySettings(settings, value),
157 });
158 }
159 }}
160 >
161 <SelectTrigger
162 size="sm"
163 className="w-full sm:w-40"
164 aria-label={gt`Shared background policy`}
165 >
166 <SelectValue>{m(BACKGROUND_ACTIVITY_PROFILE_LABELS[activeProfile])}</SelectValue>
167 </SelectTrigger>
168 <SelectPopup align="end" alignItemWithTrigger={false}>
169 <SelectItem hideIndicator value="balanced">
170 {m(BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced)}
171 </SelectItem>
172 <SelectItem hideIndicator value="performance">
173 {m(BACKGROUND_ACTIVITY_PROFILE_LABELS.performance)}
174 </SelectItem>
175 <SelectItem hideIndicator value="battery-saver">
176 {m(BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"])}
177 </SelectItem>
178 </SelectPopup>
179 </Select>
180 </div>
181​
182 <div className="flex flex-col gap-3 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
183 <div className="min-w-0 space-y-1">
184 <div className="text-sm font-medium">
185 {searchableSetting("git-fetch-interval").title}
186 </div>
187 <p className="text-xs leading-relaxed text-muted-foreground">
188 <T>Refresh remote branch status in the background.</T>
189 </p>
190 </div>
191 <div className="flex shrink-0 items-center gap-2">
192 <IntervalSecondsField
193 labels={{
194 decrease: gt`Decrease Git fetch interval`,
195 input: gt`Git fetch interval in seconds`,
196 increase: gt`Increase Git fetch interval`,
197 }}
198 value={automaticGitFetchIntervalSeconds}
199 min={0}
200 step={5}
201 onCommit={(seconds, options) =>
202 updateSettings(
203 backgroundActivityOverrideSettings(
204 settings.backgroundActivity,
205 resolvedBackgroundActivity,
206 { automaticGitFetchInterval: Duration.seconds(seconds) },
207 ),
208 options,
209 )
210 }
211 />
212 <span className="text-xs text-muted-foreground">
213 <T>seconds</T>
214 </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">
221 <T>Provider health interval</T>
222 </div>
223 <p className="text-xs leading-relaxed text-muted-foreground">
224 <T>
225 Refresh provider availability, versions, and auth state. Model catalog updates
226 follow Provider update checks.
227 </T>
228 </p>
229 </div>
230 <div className="flex shrink-0 items-center gap-2">
231 <IntervalSecondsField
232 labels={{
233 decrease: gt`Decrease provider health interval`,
234 input: gt`Provider health interval in seconds`,
235 increase: gt`Increase provider health interval`,
236 }}
237 value={providerHealthRefreshIntervalSeconds}
238 min={0}
239 step={PROVIDER_HEALTH_INTERVAL_STEP_SECONDS}
240 onCommit={(seconds, options) =>
241 updateSettings(
242 backgroundActivityOverrideSettings(
243 settings.backgroundActivity,
244 resolvedBackgroundActivity,
245 { providerHealthRefreshInterval: Duration.seconds(seconds) },
246 ),
247 options,
248 )
249 }
250 />
251 <span className="text-xs text-muted-foreground">
252 <T>seconds</T>
253 </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">
260 <T>Host power monitor</T>
261 </div>
262 <p className="text-xs leading-relaxed text-muted-foreground">
263 <T>Poll host power state while clients are active.</T>
264 </p>
265 </div>
266 <div className="flex shrink-0 items-center gap-2">
267 <IntervalSecondsField
268 labels={{
269 decrease: gt`Decrease active host power interval`,
270 input: gt`Active host power interval in seconds`,
271 increase: gt`Increase active host power interval`,
272 }}
273 value={hostPowerMonitorActiveIntervalSeconds}
274 min={5}
275 step={5}
276 onCommit={(seconds, options) =>
277 updateSettings(
278 backgroundActivityOverrideSettings(
279 settings.backgroundActivity,
280 resolvedBackgroundActivity,
281 { hostPowerMonitorActiveInterval: Duration.seconds(seconds) },
282 ),
283 options,
284 )
285 }
286 />
287 <span className="text-xs text-muted-foreground">
288 <T>seconds</T>
289 </span>
290 </div>
291 </div>
292​
293 <div className="flex flex-col gap-3 border-t px-4 py-3 sm:flex-row sm:items-center sm:justify-between">
294 <div className="min-w-0 space-y-1">
295 <div className="text-sm font-medium">
296 <T>Idle host monitor</T>
297 </div>
298 <p className="text-xs leading-relaxed text-muted-foreground">
299 <T>Poll host power state when no foreground client is active.</T>
300 </p>
301 </div>
302 <div className="flex shrink-0 items-center gap-2">
303 <IntervalSecondsField
304 labels={{
305 decrease: gt`Decrease idle host power interval`,
306 input: gt`Idle host power interval in seconds`,
307 increase: gt`Increase idle host power interval`,
308 }}
309 value={hostPowerMonitorIdleIntervalSeconds}
310 min={5}
311 step={30}
312 onCommit={(seconds, options) =>
313 updateSettings(
314 backgroundActivityOverrideSettings(
315 settings.backgroundActivity,
316 resolvedBackgroundActivity,
317 { hostPowerMonitorIdleInterval: Duration.seconds(seconds) },
318 ),
319 options,
320 )
321 }
322 />
323 <span className="text-xs text-muted-foreground">
324 <T>seconds</T>
325 </span>
326 </div>
327 </div>
328​
329 <div className="grid gap-0 border-t sm:grid-cols-2">
330 {BACKGROUND_ACTIVITY_BOOLEAN_OVERRIDES.map(({ key, label }) => (
331 <label
332 key={key}
333 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"
334 >
335 <span className="text-sm font-medium">{m(label)}</span>
336 <Switch
337 checked={resolvedBackgroundActivity[key]}
338 onCheckedChange={(checked) =>
339 updateSettings(
340 backgroundActivityOverrideSettings(
341 settings.backgroundActivity,
342 resolvedBackgroundActivity,
343 {
344 [key]: Boolean(checked),
345 },
346 ),
347 )
348 }
349 aria-label={m(label)}
350 />
351 </label>
352 ))}
353 </div>
354 </fieldset>
355 </DialogPanel>
356 <DialogFooter>
357 <Button
358 variant="outline"
359 disabled={!canWriteSettings}
360 onClick={() => updateSettings(resetBackgroundActivitySettings())}
361 >
362 <T>Reset all</T>
363 </Button>
364 <Button onClick={() => onOpenChange(false)}>
365 <T>Done</T>
366 </Button>
367 </DialogFooter>
368 </DialogPopup>
369 </Dialog>
370 );
372​
373export function BackgroundActivitySettingsRow() {
374 const searchableSetting = useSearchableSetting();
375 const gt = useGT();
376 const m = useMessages();
377 const settings = useScopedSettings();
378 const updateSettings = useUpdateScopedSettings();
379 const { scope, environment } = useSettingsScope();
380 const environmentId = environment?.environmentId ?? null;
381 const isEnvironmentScope = scope.environmentIds.length === 1 && environmentId !== null;
382 const [backgroundActivityDialogOpen, setBackgroundActivityDialogOpen] = useState(false);
383 const mixedBackgroundActivity = useScopedSettingsMixed(["backgroundActivity"]);
384 const resolvedBackgroundActivity = resolveServerBackgroundActivitySettings(settings);
385 const activeBackgroundActivityProfile = resolvedBackgroundActivity.profile;
386 const backgroundActivityProfileOption = resolveBackgroundActivityProfileOption(settings);
387 const backgroundActivityDescription =
388 backgroundActivityProfileOption === "advanced"
389 ? gt`Uses custom intervals. Shared policy: ${{ profile: m(BACKGROUND_ACTIVITY_PROFILE_LABELS[activeBackgroundActivityProfile]) }}.`
390 : m(BACKGROUND_ACTIVITY_PROFILE_DESCRIPTIONS[resolvedBackgroundActivity.profile]);
391 const canResetBackgroundActivity = !Equal.equals(
392 settings.backgroundActivity,
393 DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
394 );
395​
396 return (
397 <SettingsRow
398 serverScoped
399 settingKeys={["backgroundActivity"]}
400 id={searchableSetting("background-activity").id}
401 title={
402 <span className="inline-flex items-center gap-1.5">
403 {searchableSetting("background-activity").title}
404 <PolicyTooltip>
405 {gt`This shared policy gates background work such as Git refreshes and provider health probes after their individual intervals elapse.`}
406 </PolicyTooltip>
407 </span>
408 }
409 description={backgroundActivityDescription}
410 resetAction={
411 canResetBackgroundActivity ? (
412 <SettingResetButton
413 ariaLabel={gt`Reset background activity to default`}
414 onClick={() => updateSettings(resetBackgroundActivitySettings())}
415 />
416 ) : null
417 }
418 control={
419 <>
420 <Select
421 value={mixedBackgroundActivity ? null : backgroundActivityProfileOption}
422 onValueChange={(value) => {
423 if (value === "advanced") {
424 if (isEnvironmentScope) setBackgroundActivityDialogOpen(true);
425 return;
426 }
427 if (value === "balanced" || value === "performance" || value === "battery-saver") {
428 updateSettings(backgroundActivityProfileSettings(value));
429 }
430 }}
431 >
432 <SelectTrigger
433 size="sm"
434 className="w-full sm:w-40"
435 aria-label={gt`Background activity profile`}
436 >
437 <SelectValue>
438 {(value: BackgroundActivityProfileOption | null) =>
439 value === null
440 ? gt({ context: "values differ across targets" })`Mixed`
441 : m(BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS[value])
442 }
443 </SelectValue>
444 </SelectTrigger>
445 <SelectPopup align="end" alignItemWithTrigger={false}>
446 <SelectItem hideIndicator value="balanced">
447 {m(BACKGROUND_ACTIVITY_PROFILE_LABELS.balanced)}
448 </SelectItem>
449 <SelectItem hideIndicator value="performance">
450 {m(BACKGROUND_ACTIVITY_PROFILE_LABELS.performance)}
451 </SelectItem>
452 <SelectItem hideIndicator value="battery-saver">
453 {m(BACKGROUND_ACTIVITY_PROFILE_LABELS["battery-saver"])}
454 </SelectItem>
455 <SelectItem hideIndicator value="advanced" disabled={!isEnvironmentScope}>
456 {isEnvironmentScope
457 ? m(BACKGROUND_ACTIVITY_PROFILE_OPTION_LABELS.advanced)
458 : gt`Advanced (one environment)`}
459 </SelectItem>
460 </SelectPopup>
461 </Select>
462 {backgroundActivityProfileOption === "advanced" && isEnvironmentScope ? (
463 <SharedTooltipTrigger
464 render={
465 <Button
466 size="icon-sm"
467 variant="outline"
468 aria-label={gt`Configure advanced background activity`}
469 onClick={() => setBackgroundActivityDialogOpen(true)}
470 >
471 <SettingsIcon className="size-4" />
472 </Button>
473 }
474 label={
475 <>
476 <T>Configure background activity</T>
477 </>
478 }
479 />
480 ) : null}
481 <BackgroundActivityAdvancedDialog
482 open={backgroundActivityDialogOpen && isEnvironmentScope}
483 onOpenChange={setBackgroundActivityDialogOpen}
484 />
485 </>
486 }
487 />
488 );