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

StorageSettings.tsx

801 lines30.5 KB

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