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