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

StorageSettings.tsx

758 lines28.6 KB

1import type {
2 StorageCleanupReport,
3 StorageCleanupSettings,
4 WorktreeCleanupRules,
5} from "@t3tools/contracts";
6import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
7import { useRef, useState } from "react";
8import { useAtomValue } from "@effect/atom-react";
9import {
10 isAtomCommandInterrupted,
11 squashAtomCommandFailure,
12} from "@t3tools/client-runtime/state/runtime";
13import { formatBytes } from "../../lib/formatBytes";
14import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
15import { serverEnvironment } from "../../state/server";
16import { useAtomCommand } from "../../state/use-atom-command";
17import { formatRelativeTimeLabel } from "../../timestampFormat";
18import { useNowMinute } from "../../hooks/useNowMinute";
19import { Button } from "../ui/button";
20import { toastManager } from "../ui/toast";
21​
22import { Input } from "../ui/input";
23import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
24import { Switch } from "../ui/switch";
25import {
26 NumberField,
27 NumberFieldDecrement,
28 NumberFieldGroup,
29 NumberFieldIncrement,
30 NumberFieldInput,
31} from "../ui/number-field";
32import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout";
33import { DatabaseStorageNotice } from "./DatabaseStorageNotice";
34import { AdvancedSettings } from "./AdvancedSettings";
35import { FoldedSettingsSection } from "./FoldedSettingsSection";
36import { SettingsScopeNotice } from "./SettingsScopeNotice";
37import { SettingsGroup } from "./SettingsGroup";
38import type { ScopedSettingsTarget } from "./scopedSettings";
39import { useSettingsScope } from "./SettingsScopeContext";
40import { searchableSetting } from "./settingsSearch";
41import {
42 useClearScopedSettings,
43 useScopedSettings,
44 useScopedSettingsMixed,
45 useUpdateScopedSettings,
46} from "./useScopedSettings";
47import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis";
48​
49export function WorktreesDirectoryRow() {
50 const { connectedEnvironments, targets } = useSettingsScope();
51 const settings = useScopedSettings();
52 const updateSettings = useUpdateScopedSettings();
53 const mixed = useScopedSettingsMixed(["worktreesDirectory"]);
54 const edited = useRef(false);
55 if (
56 connectedEnvironments.some(
57 (environment) =>
58 environment.serverConfig?.environment.capabilities.worktreesDirectory !== true,
59 )
60 )
61 return null;
62 const scopeKey = targets.map((target) => target.environmentId).join(",");
63​
64 return (
65 <SettingsRow
66 {...searchableSetting("storage-worktrees-location")}
67 description={
68 "Folder where new worktrees are created, on any drive, such as D:\\worktrees or ~/worktrees. Existing worktrees stay where they are. Leave empty to use the T3 home folder."
69 }
70 serverScoped
71 settingKeys={["worktreesDirectory"]}
72 resetAction={
73 mixed || settings.worktreesDirectory !== "" ? (
74 <SettingResetButton
75 label="worktree location"
76 onClick={() => updateSettings({ worktreesDirectory: "" })}
77 />
78 ) : null
79 }
80 control={
81 <Input
82 key={`${scopeKey}:${mixed}:${settings.worktreesDirectory}`}
83 aria-label="Worktree location"
84 autoCapitalize="none"
85 spellCheck={false}
86 placeholder={mixed ? "Mixed" : "Default"}
87 defaultValue={mixed ? "" : settings.worktreesDirectory}
88 onChange={() => {
89 edited.current = true;
90 }}
91 onBlur={(event) => {
92 const value = event.target.value.trim();
93 if (edited.current && (mixed || value !== settings.worktreesDirectory))
94 updateSettings({ worktreesDirectory: value });
95 edited.current = false;
96 }}
97 />
98 }
99 />
100 );
102​
103function RetentionControl({
104 label,
105 value,
106 onChange,
107 minimum = 1,
108}: {
109 label: string;
110 value: number | null;
111 onChange: (value: number | null) => void;
112 minimum?: number;
113}) {
114 const [draft, setDraft] = useState(value);
115 const [savedValue, setSavedValue] = useState(value);
116 if (savedValue !== value) {
117 setSavedValue(value);
118 setDraft(value);
119 }
120​
121 return (
122 <div className="flex items-center gap-3">
123 {value !== null ? (
124 <NumberField
125 value={draft}
126 min={minimum}
127 max={3650}
128 step={1}
129 size="sm"
130 className="w-auto"
131 onValueChange={setDraft}
132 onValueCommitted={(next) => {
133 if (next === null) setDraft(value);
134 else {
135 const days = Math.min(3650, Math.max(minimum, Math.round(next)));
136 setDraft(days);
137 onChange(days);
138 }
139 }}
140 >
141 <NumberFieldGroup>
142 <NumberFieldDecrement aria-label={`Decrease ${label}`} />
143 <NumberFieldInput
144 aria-label={`${label} in days`}
145 size={new Intl.NumberFormat().format(draft ?? value).length}
146 className="field-sizing-content w-auto min-w-[1ch] grow-0 text-right"
147 />
148 <span aria-hidden="true" className="self-center pr-2 text-xs">
149 days
150 </span>
151 <NumberFieldIncrement aria-label={`Increase ${label}`} />
152 </NumberFieldGroup>
153 </NumberField>
154 ) : (
155 <span className="text-xs text-muted-foreground">Off</span>
156 )}
157 <Switch
158 aria-label={label}
159 checked={value !== null}
160 onCheckedChange={(enabled) => onChange(enabled ? 8 : null)}
161 />
162 </div>
163 );
165​
166const KEEP_WHEN_LABELS = {
167 "any-local-files": "Any local files",
168 "uncommitted-changes": "Uncommitted changes",
169 "tracked-changes": "Edited tracked files",
170} as const;
171​
172function lastRunSummary(
173 entries: readonly { readonly label: string; readonly counts: string }[],
174 machineCount: number,
175) {
176 const first = entries[0];
177 if (!first) return "";
178 if (machineCount <= 1) return first.counts;
179 if (entries.length === machineCount && entries.every((entry) => entry.counts === first.counts)) {
180 return `${first.counts} on every machine`;
181 }
182 return entries.map((entry) => `${entry.label}: ${entry.counts}`).join(" · ");
184​
185function CleanupResults({
186 report,
187 environmentLabel,
188}: {
189 report: StorageCleanupReport;
190 environmentLabel: string;
191}) {
192 return (
193 <>
194 {report.entries.map((entry, index) => {
195 const name =
196 entry.kind === "worktree"
197 ? ((entry.threadId === null
198 ? entry.path
199 : entry.path?.split(/[\\/]/).findLast(Boolean)) ?? "Worktrees")
200 : entry.kind === "logs"
201 ? "Rotated logs"
202 : "Browser artifacts";
203 return (
204 <SettingsRow
205 key={`${entry.path ?? entry.kind}:${entry.threadId ?? index}`}
206 title={<span className="wrap-anywhere select-text">{name}</span>}
207 description={
208 <span className="block space-y-2 wrap-anywhere select-text">
209 <span className={`block ${entry.outcome === "failed" ? "text-destructive" : ""}`}>
210 {entry.reason}
211 </span>
212 <span className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 border-l border-border/60 pl-3">
213 <span>Machine</span>
214 <span className="text-foreground/80">{environmentLabel}</span>
215 {entry.projectPath && (
216 <>
217 <span>Project</span>
218 <code className="text-foreground/80">{entry.projectPath}</code>
219 </>
220 )}
221 {entry.path && (
222 <>
223 <span>Folder</span>
224 <code className="text-foreground/80">{entry.path}</code>
225 </>
226 )}
227 {entry.threadTitle && (
228 <>
229 <span>Thread</span>
230 <span>{entry.threadTitle}</span>
231 </>
232 )}
233 </span>
234 </span>
235 }
236 control={
237 (entry.outcome === "removed" ||
238 (entry.outcome === "kept" && entry.bytes !== null)) && (
239 <span className="text-xs text-muted-foreground">
240 {[
241 entry.kind !== "worktree" && entry.files !== null
242 ? `${entry.files.toLocaleString()} ${entry.files === 1 ? "file" : "files"}`
243 : null,
244 entry.bytes !== null ? formatBytes(entry.bytes) : null,
245 ]
246 .filter(Boolean)
247 .join(" · ")}
248 </span>
249 )
250 }
251 />
252 );
253 })}
254 {report.omittedCount > 0 && (
255 <p className="px-3 py-2.5 text-xs text-muted-foreground sm:px-4">
256 {environmentLabel}: {report.omittedCount.toLocaleString()} more results.
257 </p>
258 )}
259 {report.entries.length === 0 && report.omittedCount === 0 && (
260 <p className="px-3 py-2.5 text-xs text-muted-foreground sm:px-4">
261 {environmentLabel}: Nothing needed cleanup.
262 </p>
263 )}
264 </>
265 );
267​
268const storageCleanupReportsAtom = environmentAtomList(
269 "web-storage-cleanup-reports",
270 (environmentId) => serverEnvironment.storageCleanupReport({ environmentId, input: {} }),
271);
272const storageCleanupPermissionsAtom = environmentAtomList(
273 "web-storage-cleanup-permissions",
274 serverEnvironment.runStorageCleanup.permissionAtom,
275);
276​
277function CleanupSection() {
278 const nowMinute = useNowMinute();
279 const nowMs = Date.parse(`${nowMinute}:00.000Z`);
280 const { connectedEnvironments } = useSettingsScope();
281 const [pending, setPending] = useState(false);
282 const run = useAtomCommand(serverEnvironment.runStorageCleanup);
283 const supported = connectedEnvironments.filter(
284 (environment) => environment.serverConfig?.environment.capabilities.storageCleanupRun === true,
285 );
286 const supportedIds = supported.map(({ environmentId }) => environmentId);
287 const reports = useAtomValue(storageCleanupReportsAtom(environmentIdsKey(supportedIds)));
288 const permissions = useAtomValue(storageCleanupPermissionsAtom(environmentIdsKey(supportedIds)));
289 const state = supportedIds.map((environmentId, index) => {
290 const query = reports[index]!;
291 return {
292 environmentId,
293 allowed: permissions[index]!,
294 report: query._tag === "Success" ? query.value : null,
295 loading: query.waiting,
296 failed: query._tag === "Failure",
297 };
298 });
299 const hasRules = supported.some((environment) => {
300 const settings = environment.serverConfig?.settings;
301 if (!settings) return false;
302 const enabled = (rules: WorktreeCleanupRules) =>
303 rules.worktreeAfterDays !== null ||
304 rules.worktreeSettledAfterDays !== null ||
305 rules.worktreeOnMerge ||
306 rules.worktreeOnDelete ||
307 rules.worktreeUnchanged;
308 return (
309 settings.storageCleanup.browserArtifactsAfterDays !== null ||
310 settings.storageCleanup.logsAfterDays !== null ||
311 enabled(resolveWorktreeCleanup(settings, null)) ||
312 Object.values(settings.projectSettingsOverrides).some(
313 (override) =>
314 override.worktreeCleanup?.mode === "custom" && enabled(override.worktreeCleanup.rules),
315 )
316 );
317 });
318 if (supported.length === 0) return null;
319 const summaries = supported.map((environment) => {
320 const query = state.find((entry) => entry.environmentId === environment.environmentId);
321 const report = query?.report ?? null;
322 return {
323 environment,
324 report,
325 label: settingsScopeEnvironmentLabel(environment, connectedEnvironments),
326 counts: report
327 ? `${report.counts.removed} removed, ${report.counts.kept} kept${report.counts.failed > 0 ? `, ${report.counts.failed} failed` : ""}`
328 : "",
329 description: report
330 ? `Last run ${formatRelativeTimeLabel(report.finishedAt, nowMs)}. ${formatBytes(report.bytesFreed)} recovered.${report.counts.failed > 0 ? ` ${report.counts.failed} ${report.counts.failed === 1 ? "item" : "items"} couldn't be removed.` : ""}`
331 : query?.failed
332 ? "Could not load the last run."
333 : query?.loading
334 ? "Loading last run…"
335 : "Cleanup hasn't run yet.",
336 };
337 });
338 const deleteNow = async () => {
339 if (pending) return;
340 setPending(true);
341 await Promise.all(
342 supported
343 .filter((environment) =>
344 state.some((entry) => entry.environmentId === environment.environmentId && entry.allowed),
345 )
346 .map(async (environment) => {
347 const result = await run({ environmentId: environment.environmentId, input: {} });
348 if (result._tag === "Success") {
349 const failures = result.value.entries.filter((entry) => entry.outcome === "failed");
350 if (failures.length > 0)
351 toastManager.add({
352 type: "error",
353 title: `Cleanup failed on ${environment.label}`,
354 description: failures[0]!.reason,
355 });
356 } else if (!isAtomCommandInterrupted(result)) {
357 toastManager.add({
358 type: "error",
359 title: `Could not run cleanup on ${environment.label}`,
360 description: String(squashAtomCommandFailure(result)),
361 });
362 }
363 }),
364 ).finally(() => setPending(false));
365 };
366 return (
367 <SettingsSection id="storage-cleanup" title="Cleanup" variant="plain">
368 <SettingsGroup>
369 <SettingsRow
370 {...searchableSetting("storage-delete-now")}
371 description={
372 <span>
373 {!hasRules
374 ? "Turn on a cleanup rule to use this."
375 : summaries.map(({ environment, label, description }) => (
376 <span key={environment.environmentId} className="block">
377 {supported.length > 1 ? `${label}: ` : ""}
378 {description}
379 </span>
380 ))}
381 </span>
382 }
383 control={
384 <Button
385 variant="outline"
386 size="sm"
387 disabled={pending || !hasRules || !state.some((entry) => entry.allowed)}
388 onClick={() => void deleteNow()}
389 >
390 {pending ? "Deleting…" : "Delete now"}
391 </Button>
392 }
393 />
394 </SettingsGroup>
395 {summaries.some(({ report }) => report !== null) && (
396 <FoldedSettingsSection
397 id="storage-cleanup-last-run"
398 title="Last run"
399 headerPlacement="inside"
400 summary={lastRunSummary(
401 summaries.filter(({ report }) => report !== null),
402 connectedEnvironments.length,
403 )}
404 >
405 {summaries.map(
406 ({ environment, label, report }) =>
407 report && (
408 <CleanupResults
409 key={environment.environmentId}
410 report={report}
411 environmentLabel={label}
412 />
413 ),
414 )}
415 </FoldedSettingsSection>
416 )}
417 </SettingsSection>
418 );
420​
421function supportsStorageCleanup(
422 environments: ReadonlyArray<{
423 readonly serverConfig: {
424 readonly environment: { readonly capabilities: { readonly storageCleanup?: boolean } };
425 } | null;
426 }>,
427) {
428 return environments.every(
429 (environment) => environment.serverConfig?.environment.capabilities.storageCleanup === true,
430 );
432​
433/** Narrows a mixed selection to the machines that support cleanup. */
434function StorageCleanupScopeNotice() {
435 const { connectedEnvironments } = useSettingsScope();
436 return (
437 <SettingsScopeNotice
438 inline
439 target="environment"
440 eligibleEnvironmentIds={connectedEnvironments
441 .filter(
442 (environment) =>
443 environment.serverConfig?.environment.capabilities.storageCleanup === true,
444 )
445 .map((environment) => environment.environmentId)}
446 >
447 Update the selected environments to use storage cleanup, or choose a machine that supports it.
448 </SettingsScopeNotice>
449 );
451​
452export function WorktreeCleanupSection() {
453 const { scope, environments, connectedEnvironments, targets, target } = useSettingsScope();
454 const scopedSettings = useScopedSettings();
455 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
456 const settings = {
457 ...scopedSettings.storageCleanup,
458 ...resolveWorktreeCleanup(scopedSettings, null),
459 };
460 const projectMode = (entry: ScopedSettingsTarget | null) =>
461 entry?.sources.worktreeCleanup === "project"
462 ? (entry.settings.worktreeCleanup?.mode ?? "inherit")
463 : "inherit";
464 const mode = projectMode(target);
465 const mixedModes = targets.some((entry) => projectMode(entry) !== mode);
466 const updateSettings = useUpdateScopedSettings();
467 const clearSettings = useClearScopedSettings();
468 const ruleStatus = (key: keyof StorageCleanupSettings) =>
469 targets.some(
470 (target) =>
471 ({ ...target.settings.storageCleanup, ...resolveWorktreeCleanup(target.settings, null) })[
472 key
473 ] !== settings[key],
474 )
475 ? "Mixed across selected machines"
476 : undefined;
477 const update = (patch: Partial<StorageCleanupSettings>) =>
478 updateSettings({ storageCleanup: patch });
479 const updateWorktree = (patch: Partial<WorktreeCleanupRules>) =>
480 isProjectScope
481 ? updateSettings({ worktreeCleanup: { mode: "custom", rules: patch } })
482 : update(patch);
483​
484 if (
485 isProjectScope &&
486 connectedEnvironments.some(
487 (environment) =>
488 environment.serverConfig?.environment.capabilities.projectWorktreeCleanup !== true,
489 )
490 ) {
491 return (
492 <SettingsSection id="storage-worktrees" title="Cleanup" variant="plain">
493 <SettingsScopeNotice inline target="all">
494 Update the selected machines to configure project worktree cleanup.
495 </SettingsScopeNotice>
496 </SettingsSection>
497 );
498 }
499 if (!supportsStorageCleanup(connectedEnvironments)) {
500 return (
501 <SettingsSection id="storage-worktrees" title="Cleanup" variant="plain">
502 <StorageCleanupScopeNotice />
503 </SettingsSection>
504 );
505 }
506​
507 return (
508 <SettingsSection id="storage-worktrees" title="Cleanup">
509 <>
510 {isProjectScope && (
511 <SettingsRow
512 title="Automatic worktree cleanup"
513 description={
514 mode === "off"
515 ? "Keep this project's worktrees until you delete them manually."
516 : mode === "custom"
517 ? "Use these rules for this project."
518 : "Use each machine's worktree cleanup settings."
519 }
520 serverScoped
521 settingKeys={["worktreeCleanup"]}
522 mixed={mixedModes}
523 control={
524 <Select
525 value={mixedModes ? null : mode}
526 onValueChange={(next) => {
527 if (next === "inherit") clearSettings(["worktreeCleanup"]);
528 else if (next === "off") updateSettings({ worktreeCleanup: { mode: "off" } });
529 else if (next === "custom")
530 updateSettings({ worktreeCleanup: { mode: "custom", rules: {} } });
531 }}
532 >
533 <SelectTrigger size="sm" aria-label="Automatic worktree cleanup">
534 <SelectValue>
535 {mixedModes
536 ? "Mixed"
537 : mode === "inherit"
538 ? "Inherit"
539 : mode === "off"
540 ? "Off"
541 : "Custom"}
542 </SelectValue>
543 </SelectTrigger>
544 <SelectPopup align="end" alignItemWithTrigger={false}>
545 <SelectItem value="inherit">Inherit</SelectItem>
546 <SelectItem value="off">Off</SelectItem>
547 <SelectItem value="custom">Custom</SelectItem>
548 </SelectPopup>
549 </Select>
550 }
551 />
552 )}
553 {(!isProjectScope || (!mixedModes && mode === "custom")) && (
554 <>
555 <SettingsRow
556 title="Delete worktrees with deleted threads"
557 status={ruleStatus("worktreeOnDelete")}
558 description="Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept."
559 serverScoped={!isProjectScope}
560 control={
561 <Switch
562 aria-label="Delete worktrees with deleted threads"
563 checked={settings.worktreeOnDelete}
564 onCheckedChange={(worktreeOnDelete) => updateWorktree({ worktreeOnDelete })}
565 />
566 }
567 />
568 <SettingsRow
569 title="Delete merged worktrees"
570 status={ruleStatus("worktreeOnMerge")}
571 description="Remove worktrees whose pull request is merged and whose commits are included in the default branch."
572 serverScoped={!isProjectScope}
573 control={
574 <Switch
575 aria-label="Delete merged worktrees"
576 checked={settings.worktreeOnMerge}
577 onCheckedChange={(worktreeOnMerge) => updateWorktree({ worktreeOnMerge })}
578 />
579 }
580 />
581 <SettingsRow
582 title="Delete inactive worktrees"
583 status={ruleStatus("worktreeAfterDays")}
584 description="Remove worktrees after their threads have been inactive for this many days. Branches and thread history are kept."
585 serverScoped={!isProjectScope}
586 control={
587 <RetentionControl
588 label="Delete inactive worktrees"
589 value={settings.worktreeAfterDays}
590 onChange={(worktreeAfterDays) => updateWorktree({ worktreeAfterDays })}
591 />
592 }
593 />
594 <AdvancedSettings
595 // The keep-when search result lands on this section, not its row.
596 targetIds={["storage-worktrees", searchableSetting("storage-worktree-keep-when").id]}
597 >
598 {connectedEnvironments.length > 0 &&
599 connectedEnvironments.every(
600 (environment) =>
601 environment.serverConfig?.environment.capabilities.settledWorktreeCleanup ===
602 true,
603 ) && (
604 <SettingsRow
605 title="Delete settled worktrees"
606 status={[
607 ruleStatus("worktreeSettledAfterDays"),
608 environments.length > connectedEnvironments.length
609 ? "Offline machines will not get this setting"
610 : undefined,
611 ]
612 .filter(Boolean)
613 .join(". ")}
614 description="Remove worktrees this many days after their thread settles. Set 0 days to remove them at the next cleanup. Branches and thread history are kept."
615 serverScoped={!isProjectScope}
616 control={
617 <RetentionControl
618 label="Delete settled worktrees"
619 value={settings.worktreeSettledAfterDays}
620 minimum={0}
621 onChange={(worktreeSettledAfterDays) =>
622 updateWorktree({ worktreeSettledAfterDays })
623 }
624 />
625 }
626 />
627 )}
628 <SettingsRow
629 title="Delete unchanged worktrees"
630 status={ruleStatus("worktreeUnchanged")}
631 description="Remove worktrees with no commits beyond the default branch."
632 serverScoped={!isProjectScope}
633 control={
634 <Switch
635 aria-label="Delete unchanged worktrees"
636 checked={settings.worktreeUnchanged}
637 onCheckedChange={(worktreeUnchanged) => updateWorktree({ worktreeUnchanged })}
638 />
639 }
640 />
641 {connectedEnvironments.every(
642 (environment) =>
643 environment.serverConfig?.environment.capabilities.storageCleanupRun === true,
644 ) && (
645 <SettingsRow
646 {...searchableSetting("storage-worktree-keep-when")}
647 status={ruleStatus("worktreeKeepWhen")}
648 description={
649 settings.worktreeKeepWhen === "any-local-files"
650 ? "Includes ignored files, except node_modules."
651 : settings.worktreeKeepWhen === "tracked-changes"
652 ? "Deletes untracked and ignored files, including .env."
653 : "Keeps edits and untracked files. Deletes ignored files, including .env."
654 }
655 serverScoped={!isProjectScope}
656 control={
657 <Select
658 value={ruleStatus("worktreeKeepWhen") ? null : settings.worktreeKeepWhen}
659 onValueChange={(next) => {
660 if (
661 next === "any-local-files" ||
662 next === "uncommitted-changes" ||
663 next === "tracked-changes"
664 )
665 updateWorktree({ worktreeKeepWhen: next });
666 }}
667 >
668 <SelectTrigger size="sm" aria-label="Keep worktrees with local changes">
669 <SelectValue>
670 {ruleStatus("worktreeKeepWhen")
671 ? "Mixed"
672 : KEEP_WHEN_LABELS[settings.worktreeKeepWhen]}
673 </SelectValue>
674 </SelectTrigger>
675 <SelectPopup align="end" alignItemWithTrigger={false}>
676 <SelectItem value="any-local-files">Any local files</SelectItem>
677 <SelectItem value="uncommitted-changes">Uncommitted changes</SelectItem>
678 <SelectItem value="tracked-changes">Edited tracked files</SelectItem>
679 </SelectPopup>
680 </Select>
681 }
682 />
683 )}
684 </AdvancedSettings>
685 </>
686 )}
687 </>
688 </SettingsSection>
689 );
691​
692/** Retention for logs and captures, and the manual cleanup run, which covers worktrees too. */
693export function StorageCleanupSections() {
694 const { scope, connectedEnvironments, targets } = useSettingsScope();
695 const scopedSettings = useScopedSettings();
696 const updateSettings = useUpdateScopedSettings();
697 if (scope.kind === "project" || scope.kind === "checkout") return null;
698 const settings = scopedSettings.storageCleanup;
699 const ruleStatus = (key: "browserArtifactsAfterDays" | "logsAfterDays") =>
700 targets.some((target) => target.settings.storageCleanup[key] !== settings[key])
701 ? "Mixed across selected machines"
702 : undefined;
703 const update = (patch: Partial<StorageCleanupSettings>) =>
704 updateSettings({ storageCleanup: patch });
705 const databaseStorageNotice = (
706 <DatabaseStorageNotice
707 environments={connectedEnvironments.filter(
708 (environment) =>
709 environment.serverConfig?.environment.capabilities.databaseStorage === true,
710 )}
711 />
712 );
713 if (!supportsStorageCleanup(connectedEnvironments)) {
714 return (
715 <>
716 {databaseStorageNotice}
717 <SettingsSection id="storage-artifacts" title="Artifacts and logs" variant="plain">
718 <StorageCleanupScopeNotice />
719 </SettingsSection>
720 </>
721 );
722 }
723​
724 return (
725 <>
726 {databaseStorageNotice}
727 <SettingsSection id="storage-artifacts" title="Artifacts and logs">
728 <SettingsRow
729 title="Delete old browser artifacts"
730 status={ruleStatus("browserArtifactsAfterDays")}
731 description="Delete saved browser captures after this many days. Older capture links will no longer open."
732 serverScoped
733 control={
734 <RetentionControl
735 label="Delete old browser artifacts"
736 value={settings.browserArtifactsAfterDays}
737 onChange={(browserArtifactsAfterDays) => update({ browserArtifactsAfterDays })}
738 />
739 }
740 />
741 <SettingsRow
742 title="Delete old rotated logs"
743 status={ruleStatus("logsAfterDays")}
744 description="Delete inactive rotated log files after this many days. Current logs are kept."
745 serverScoped
746 control={
747 <RetentionControl
748 label="Delete old rotated logs"
749 value={settings.logsAfterDays}
750 onChange={(logsAfterDays) => update({ logsAfterDays })}
751 />
752 }
753 />
754 </SettingsSection>
755 <CleanupSection />
756 </>
757 );