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

StorageSettings.tsx

963 lines37.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";
24import { msg, T, useGT, useMessages, Var, plural, part } from "gt-react";
25import { m, type MessageResolver } from "../../i18n/messages";
26​
27import { Input } from "../ui/input";
28import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
29import { Switch } from "../ui/switch";
30import {
31 NumberField,
32 NumberFieldDecrement,
33 NumberFieldGroup,
34 NumberFieldIncrement,
35 NumberFieldInput,
36} from "../ui/number-field";
37import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout";
38import { DatabaseStorageNotice } from "./DatabaseStorageNotice";
39import { AdvancedSettings } from "./AdvancedSettings";
40import { FoldedSettingsSection } from "./FoldedSettingsSection";
41import { SettingsScopeNotice } from "./SettingsScopeNotice";
42import { SettingsGroup } from "./SettingsGroup";
43import type { ScopedSettingsTarget } from "./scopedSettings";
44import { useSettingsScope } from "./SettingsScopeContext";
45import { useSearchableSetting } from "./settingsSearch";
46import {
47 useClearScopedSettings,
48 useScopedSettings,
49 useScopedSettingsMixed,
50 useUpdateScopedSettings,
51} from "./useScopedSettings";
52import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis";
53import { commitNumberFieldOnEnter } from "./commitNumberFieldOnEnter";
54​
55export function WorktreesDirectoryRow() {
56 const setting = useSearchableSetting();
57 const gt = useGT();
58 const { connectedEnvironments, targets } = useSettingsScope();
59 const settings = useScopedSettings();
60 const updateSettings = useUpdateScopedSettings();
61 const mixed = useScopedSettingsMixed(["worktreesDirectory"]);
62 const edited = useRef(false);
63 const draft = useRef("");
64 if (
65 connectedEnvironments.some(
66 (environment) =>
67 environment.serverConfig?.environment.capabilities.worktreesDirectory !== true,
68 )
69 )
70 return null;
71 const scopeKey = targets.map((target) => target.environmentId).join(",");
72​
73 return (
74 <SettingsRow
75 {...setting("storage-worktrees-location")}
76 description={gt`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.`}
77 serverScoped
78 settingKeys={["worktreesDirectory"]}
79 resetAction={
80 mixed || settings.worktreesDirectory !== "" ? (
81 <SettingResetButton
82 ariaLabel={gt`Reset worktree location to default`}
83 onClick={() => updateSettings({ worktreesDirectory: "" })}
84 />
85 ) : null
86 }
87 control={
88 <Input
89 key={`${scopeKey}:${mixed}:${settings.worktreesDirectory}`}
90 aria-label={gt`Worktree location`}
91 autoCapitalize="none"
92 spellCheck={false}
93 placeholder={mixed ? gt`Mixed` : gt`Default`}
94 defaultValue={mixed ? "" : settings.worktreesDirectory}
95 onFocus={(event) => {
96 draft.current = event.target.value;
97 }}
98 onChange={(event) => {
99 edited.current = true;
100 draft.current = resolvePastedPath(draft.current, event.target.value);
101 event.target.value = draft.current;
102 }}
103 onBlur={(event) => {
104 const value = event.target.value.trim();
105 if (edited.current && (mixed || value !== settings.worktreesDirectory))
106 updateSettings({ worktreesDirectory: value });
107 edited.current = false;
108 }}
109 />
110 }
111 />
112 );
114​
115type SaveOptions = Parameters<ReturnType<typeof useUpdateScopedSettings>>[1];
116​
117function RetentionControl({
118 label,
119 value,
120 onChange,
121 minimum = 1,
122}: {
123 label: string;
124 value: number | null;
125 onChange: (value: number | null, onFailed: () => void) => void;
126 minimum?: number;
127}) {
128 const gt = useGT();
129 const [draft, setDraft] = useState(value);
130 const [savedValue, setSavedValue] = useState(value);
131 // Saving an age can start a cleanup sweep, so turning a rule on only opens a draft.
132 // While its first save is in flight this holds that submission.
133 const [enabling, setEnabling] = useState<"draft" | "edited" | { days: number } | null>(null);
134 // Holds an age until Enter or focus leaves the row: one edited before focus moved to the
135 // switch, so switching off never saves it first, or one stepped toward a rule's first age,
136 // so raising it from 8 never saves a shorter age on the way.
137 const [held, setHeld] = useState(false);
138 // Hides a saved rule's age once it is switched off, so no blur can save it after null.
139 const [switchedOff, setSwitchedOff] = useState(false);
140 if (savedValue !== value) {
141 setSavedValue(value);
142 setDraft(value);
143 setEnabling(null);
144 setHeld(false);
145 setSwitchedOff(false);
146 }
147 const pending = typeof enabling === "object" ? enabling : null;
148 const on = (value !== null && !switchedOff) || enabling !== null;
149 const row = useRef<HTMLDivElement>(null);
150​
151 const commit = (next: number) => {
152 const days = Math.min(3650, Math.max(minimum, Math.round(next)));
153 setDraft(days);
154 setHeld(false);
155 if (days === pending?.days) return;
156 if (value !== null) {
157 onChange(days, () => {});
158 return;
159 }
160 const submission = { days };
161 setEnabling(submission);
162 onChange(days, () => setEnabling((current) => (current === submission ? null : current)));
163 };
164​
165 const switchOff = () => {
166 setDraft(value);
167 setHeld(false);
168 setEnabling(null);
169 if (value === null && pending === null) return;
170 setSwitchedOff(true);
171 onChange(null, () => setSwitchedOff(false));
172 };
173​
174 return (
175 <div
176 ref={row}
177 className="flex items-center gap-3"
178 onBlur={(event) => {
179 if (event.currentTarget.contains(event.relatedTarget)) return;
180 if (held && draft !== null) commit(draft);
181 else setEnabling((current) => (typeof current === "string" ? null : current));
182 }}
183 onKeyDown={(event) => {
184 if (
185 event.key !== "Escape" ||
186 event.nativeEvent.isComposing ||
187 event.keyCode === 229 ||
188 (!held && typeof enabling !== "string")
189 ) {
190 return;
191 }
192 // An unhandled Escape closes the settings page.
193 event.preventDefault();
194 event.stopPropagation();
195 setDraft(pending?.days ?? value);
196 setHeld(false);
197 setEnabling((current) => (typeof current === "string" ? null : current));
198 }}
199 >
200 {on ? (
201 <NumberField
202 value={draft}
203 min={minimum}
204 max={3650}
205 step={1}
206 size="sm"
207 className="w-auto"
208 onValueChange={(next) => {
209 setDraft(next);
210 setEnabling((current) => (current === "draft" ? "edited" : current));
211 }}
212 onValueCommitted={(next, { reason, event }) => {
213 if (next === null) setDraft(value);
214 else if (
215 reason === "input-blur"
216 ? event instanceof FocusEvent &&
217 event.relatedTarget instanceof Node &&
218 row.current?.contains(event.relatedTarget)
219 : value === null
220 ) {
221 setDraft(next);
222 setHeld(true);
223 } else commit(next);
224 }}
225 >
226 <NumberFieldGroup>
227 <NumberFieldDecrement aria-label={gt`Decrease ${{ label }}`} />
228 <NumberFieldInput
229 aria-label={gt`${{ label }} in days`}
230 autoFocus={value === null}
231 size={5}
232 className="w-auto grow-0 text-right"
233 // Any typed or pasted edit replaces a held age: NumberField commits it on blur itself,
234 // and text it cannot parse yet must not leave the held age to be saved.
235 onChange={() => setHeld(false)}
236 onPaste={() => setHeld(false)}
237 onKeyDown={(event) => {
238 if (event.nativeEvent.isComposing || event.keyCode === 229) return;
239 if (event.key === "Enter") {
240 // Blurring lets NumberField parse the visible text and commit it once. It
241 // skips an unedited value, so an untouched draft is committed here.
242 const input = event.currentTarget;
243 const shown =
244 draft !== null && input.value === new Intl.NumberFormat().format(draft);
245 if (enabling === "draft" && shown) commit(draft);
246 commitNumberFieldOnEnter(event);
247 }
248 }}
249 />
250 <span aria-hidden="true" className="self-center pr-2 text-xs">
251 {gt`${plural({ count: draft ?? 0 }, { one: "day", other: "days" })}`}
252 </span>
253 <NumberFieldIncrement aria-label={gt`Increase ${{ label }}`} />
254 </NumberFieldGroup>
255 </NumberField>
256 ) : (
257 <span className="text-xs text-muted-foreground">
258 <T>Off</T>
259 </span>
260 )}
261 <Switch
262 aria-label={label}
263 checked={on}
264 // Keeps focus in the age field, so switching off never commits an edited age first.
265 onMouseDown={(event) => event.preventDefault()}
266 onCheckedChange={(enabled) => {
267 if (enabled) {
268 setDraft(8);
269 setEnabling("draft");
270 } else switchOff();
271 }}
272 />
273 </div>
274 );
276​
277const KEEP_WHEN_LABELS = {
278 "any-local-files": msg("Any local files"),
279 "uncommitted-changes": msg("Uncommitted changes"),
280 "tracked-changes": msg("Edited tracked files"),
281} as const;
282​
283function lastRunSummary(
284 entries: readonly { readonly label: string; readonly counts: string }[],
285 machineCount: number,
286 resolve: MessageResolver = m,
287) {
288 const first = entries[0];
289 if (!first) return "";
290 if (machineCount <= 1) return first.counts;
291 if (entries.length === machineCount && entries.every((entry) => entry.counts === first.counts)) {
292 return resolve(msg`${{ counts: first.counts }} on every machine`);
293 }
294 return entries.map((entry) => `${entry.label}: ${entry.counts}`).join(" · ");
296​
297function CleanupResults({
298 report,
299 environmentLabel,
300}: {
301 report: StorageCleanupReport;
302 environmentLabel: string;
303}) {
304 const gt = useGT();
305 return (
306 <>
307 {report.entries.map((entry, index) => {
308 const name =
309 entry.kind === "worktree"
310 ? ((entry.threadId === null
311 ? entry.path
312 : entry.path?.split(/[\\/]/).findLast(Boolean)) ?? gt`Worktrees`)
313 : entry.kind === "logs"
314 ? gt`Rotated logs`
315 : gt`Browser artifacts`;
316 return (
317 <SettingsRow
318 key={`${entry.path ?? entry.kind}:${entry.threadId ?? index}`}
319 title={<span className="wrap-anywhere select-text">{name}</span>}
320 description={
321 <span className="block space-y-2 wrap-anywhere select-text">
322 <span className={`block ${entry.outcome === "failed" ? "text-destructive" : ""}`}>
323 {entry.reason}
324 </span>
325 <span className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 border-l border-border/60 pl-3">
326 <span>
327 <T>Machine</T>
328 </span>
329 <span className="text-foreground/80">{environmentLabel}</span>
330 {entry.projectPath && (
331 <>
332 <span>
333 <T>Project</T>
334 </span>
335 <code className="text-foreground/80">{entry.projectPath}</code>
336 </>
337 )}
338 {entry.path && (
339 <>
340 <span>
341 <T>Folder</T>
342 </span>
343 <code className="text-foreground/80">{entry.path}</code>
344 </>
345 )}
346 {entry.threadTitle && (
347 <>
348 <span>
349 <T>Thread</T>
350 </span>
351 <span>{entry.threadTitle}</span>
352 </>
353 )}
354 </span>
355 </span>
356 }
357 control={
358 (entry.outcome === "removed" ||
359 (entry.outcome === "kept" && entry.bytes !== null)) && (
360 <span className="text-xs text-muted-foreground">
361 {[
362 entry.kind !== "worktree" && entry.files !== null
363 ? gt`${plural(
364 { count: entry.files },
365 {
366 one: part`${{ formatted: entry.files.toLocaleString() }} file`,
367 other: part`${{ formatted: entry.files.toLocaleString() }} files`,
368 },
369 )}`
370 : null,
371 entry.bytes !== null ? formatBytes(entry.bytes) : null,
372 ]
373 .filter(Boolean)
374 .join(" · ")}
375 </span>
376 )
377 }
378 />
379 );
380 })}
381 {report.omittedCount > 0 && (
382 <p className="px-3 py-2.5 text-xs text-muted-foreground sm:px-4">
383 {gt`${plural(
384 { omitted: report.omittedCount },
385 {
386 one: part`${{ environment: environmentLabel }}: ${{ count: report.omittedCount.toLocaleString() }} more result.`,
387 other: part`${{ environment: environmentLabel }}: ${{ count: report.omittedCount.toLocaleString() }} more results.`,
388 },
389 )}`}
390 </p>
391 )}
392 {report.entries.length === 0 && report.omittedCount === 0 && (
393 <p className="px-3 py-2.5 text-xs text-muted-foreground sm:px-4">
394 <T>
395 <Var>{environmentLabel}</Var>: Nothing needed cleanup.
396 </T>
397 </p>
398 )}
399 </>
400 );
402​
403const storageCleanupReportsAtom = environmentAtomList(
404 "web-storage-cleanup-reports",
405 (environmentId) => serverEnvironment.storageCleanupReport({ environmentId, input: {} }),
406);
407const storageCleanupPermissionsAtom = environmentAtomList(
408 "web-storage-cleanup-permissions",
409 serverEnvironment.runStorageCleanup.permissionAtom,
410);
411​
412function CleanupSection() {
413 const messages = useMessages();
414 const setting = useSearchableSetting();
415 const gt = useGT();
416 const nowMinute = useNowMinute();
417 const nowMs = Date.parse(`${nowMinute}:00.000Z`);
418 const { connectedEnvironments } = useSettingsScope();
419 const [pending, setPending] = useState(false);
420 const run = useAtomCommand(serverEnvironment.runStorageCleanup);
421 const supported = connectedEnvironments.filter(
422 (environment) => environment.serverConfig?.environment.capabilities.storageCleanupRun === true,
423 );
424 const supportedIds = supported.map(({ environmentId }) => environmentId);
425 const reports = useAtomValue(storageCleanupReportsAtom(environmentIdsKey(supportedIds)));
426 const permissions = useAtomValue(storageCleanupPermissionsAtom(environmentIdsKey(supportedIds)));
427 const state = supportedIds.map((environmentId, index) => {
428 const query = reports[index]!;
429 return {
430 environmentId,
431 allowed: permissions[index]!,
432 report: query._tag === "Success" ? query.value : null,
433 loading: query.waiting,
434 failed: query._tag === "Failure",
435 };
436 });
437 const hasRules = supported.some((environment) => {
438 const settings = environment.serverConfig?.settings;
439 if (!settings) return false;
440 const enabled = (rules: WorktreeCleanupRules) =>
441 rules.worktreeAfterDays !== null ||
442 rules.worktreeSettledAfterDays !== null ||
443 rules.worktreeOnMerge ||
444 rules.worktreeOnDelete ||
445 rules.worktreeUnchanged;
446 return (
447 settings.storageCleanup.browserArtifactsAfterDays !== null ||
448 settings.storageCleanup.logsAfterDays !== null ||
449 enabled(resolveWorktreeCleanup(settings, null)) ||
450 Object.values(settings.projectSettingsOverrides).some(
451 (override) =>
452 override.worktreeCleanup?.mode === "custom" && enabled(override.worktreeCleanup.rules),
453 )
454 );
455 });
456 if (supported.length === 0) return null;
457 const summaries = supported.map((environment) => {
458 const query = state.find((entry) => entry.environmentId === environment.environmentId);
459 const report = query?.report ?? null;
460 return {
461 environment,
462 report,
463 label: settingsScopeEnvironmentLabel(environment, connectedEnvironments),
464 counts: report
465 ? report.counts.failed > 0
466 ? gt`${{ removed: report.counts.removed }} removed, ${{ kept: report.counts.kept }} kept, ${{ failed: report.counts.failed }} failed`
467 : gt`${{ removed: report.counts.removed }} removed, ${{ kept: report.counts.kept }} kept`
468 : "",
469 description: report
470 ? report.counts.failed > 0
471 ? gt`${plural(
472 { count: report.counts.failed },
473 {
474 one: part`Last run ${{ when: formatRelativeTimeLabel(report.finishedAt, nowMs, messages) }}. ${{ bytes: formatBytes(report.bytesFreed) }} recovered. ${{ count: report.counts.failed }} item couldn't be removed.`,
475 other: part`Last run ${{ when: formatRelativeTimeLabel(report.finishedAt, nowMs, messages) }}. ${{ bytes: formatBytes(report.bytesFreed) }} recovered. ${{ count: report.counts.failed }} items couldn't be removed.`,
476 },
477 )}`
478 : gt`Last run ${{ when: formatRelativeTimeLabel(report.finishedAt, nowMs, messages) }}. ${{ bytes: formatBytes(report.bytesFreed) }} recovered.`
479 : query?.failed
480 ? gt`Could not load the last run.`
481 : query?.loading
482 ? gt`Loading last run…`
483 : gt`Cleanup hasn't run yet.`,
484 };
485 });
486 const deleteNow = async () => {
487 if (pending) return;
488 setPending(true);
489 await Promise.all(
490 supported
491 .filter((environment) =>
492 state.some((entry) => entry.environmentId === environment.environmentId && entry.allowed),
493 )
494 .map(async (environment) => {
495 const result = await run({ environmentId: environment.environmentId, input: {} });
496 if (result._tag === "Success") {
497 const failures = result.value.entries.filter((entry) => entry.outcome === "failed");
498 if (failures.length > 0)
499 toastManager.add({
500 type: "error",
501 title: gt`Cleanup failed on ${{ label: environment.label }}`,
502 description: failures[0]!.reason,
503 });
504 } else if (!isAtomCommandInterrupted(result)) {
505 toastManager.add({
506 type: "error",
507 title: gt`Could not run cleanup on ${{ label: environment.label }}`,
508 description: String(squashAtomCommandFailure(result)),
509 });
510 }
511 }),
512 ).finally(() => setPending(false));
513 };
514 return (
515 <SettingsSection id="storage-cleanup" title={gt`Cleanup`} variant="plain">
516 <SettingsGroup>
517 <SettingsRow
518 {...setting("storage-delete-now")}
519 description={
520 <span>
521 {!hasRules
522 ? gt`Turn on a cleanup rule to use this.`
523 : summaries.map(({ environment, label, description }) => (
524 <span key={environment.environmentId} className="block">
525 {supported.length > 1 ? `${label}: ` : ""}
526 {description}
527 </span>
528 ))}
529 </span>
530 }
531 control={
532 <Button
533 variant="outline"
534 size="sm"
535 disabled={pending || !hasRules || !state.some((entry) => entry.allowed)}
536 onClick={() => void deleteNow()}
537 >
538 {pending ? gt`Deleting…` : gt`Delete now`}
539 </Button>
540 }
541 />
542 </SettingsGroup>
543 {summaries.some(({ report }) => report !== null) && (
544 <FoldedSettingsSection
545 id="storage-cleanup-last-run"
546 title={gt`Last run`}
547 headerPlacement="inside"
548 summary={lastRunSummary(
549 summaries.filter(({ report }) => report !== null),
550 connectedEnvironments.length,
551 messages,
552 )}
553 >
554 {summaries.map(
555 ({ environment, label, report }) =>
556 report && (
557 <CleanupResults
558 key={environment.environmentId}
559 report={report}
560 environmentLabel={label}
561 />
562 ),
563 )}
564 </FoldedSettingsSection>
565 )}
566 </SettingsSection>
567 );
569​
570function supportsStorageCleanup(
571 environments: ReadonlyArray<{
572 readonly serverConfig: {
573 readonly environment: { readonly capabilities: { readonly storageCleanup?: boolean } };
574 } | null;
575 }>,
576) {
577 return environments.every(
578 (environment) => environment.serverConfig?.environment.capabilities.storageCleanup === true,
579 );
581​
582/** Narrows a mixed selection to the machines that support cleanup. */
583function StorageCleanupScopeNotice() {
584 const gt = useGT();
585 const { connectedEnvironments } = useSettingsScope();
586 return (
587 <SettingsScopeNotice
588 inline
589 target="environment"
590 eligibleEnvironmentIds={connectedEnvironments
591 .filter(
592 (environment) =>
593 environment.serverConfig?.environment.capabilities.storageCleanup === true,
594 )
595 .map((environment) => environment.environmentId)}
596 >
597 {gt`Update the selected environments to use storage cleanup, or choose a machine that supports it.`}
598 </SettingsScopeNotice>
599 );
601​
602export function WorktreeCleanupSection() {
603 const messages = useMessages();
604 const setting = useSearchableSetting();
605 const gt = useGT();
606 const { scope, environments, connectedEnvironments, targets, target } = useSettingsScope();
607 const scopedSettings = useScopedSettings();
608 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
609 const settings = {
610 ...scopedSettings.storageCleanup,
611 ...resolveWorktreeCleanup(scopedSettings, null),
612 };
613 const projectMode = (entry: ScopedSettingsTarget | null) =>
614 entry?.sources.worktreeCleanup === "project"
615 ? (entry.settings.worktreeCleanup?.mode ?? "inherit")
616 : "inherit";
617 const mode = projectMode(target);
618 const mixedModes = targets.some((entry) => projectMode(entry) !== mode);
619 const updateSettings = useUpdateScopedSettings();
620 const clearSettings = useClearScopedSettings();
621 const ruleStatus = (key: keyof StorageCleanupSettings) =>
622 targets.some(
623 (target) =>
624 ({ ...target.settings.storageCleanup, ...resolveWorktreeCleanup(target.settings, null) })[
625 key
626 ] !== settings[key],
627 )
628 ? gt`Mixed across selected machines`
629 : undefined;
630 // A policy locks these through worktreeCleanup, which also reaches each project's own rules.
631 const lockablePath = (key: keyof WorktreeCleanupRules) =>
632 isProjectScope ? ["worktreeCleanup"] : ["worktreeCleanup", `storageCleanup.${key}`];
633 const update = (patch: Partial<StorageCleanupSettings>, options?: SaveOptions) =>
634 updateSettings({ storageCleanup: patch }, options);
635 const updateWorktree = (patch: Partial<WorktreeCleanupRules>, options?: SaveOptions) =>
636 isProjectScope
637 ? updateSettings({ worktreeCleanup: { mode: "custom", rules: patch } }, options)
638 : update(patch, options);
639​
640 if (
641 isProjectScope &&
642 connectedEnvironments.some(
643 (environment) =>
644 environment.serverConfig?.environment.capabilities.projectWorktreeCleanup !== true,
645 )
646 ) {
647 return (
648 <SettingsSection id="storage-worktrees" title={gt`Cleanup`} variant="plain">
649 <SettingsScopeNotice inline target="all">
650 {gt`Update the selected machines to configure project worktree cleanup.`}
651 </SettingsScopeNotice>
652 </SettingsSection>
653 );
654 }
655 if (!supportsStorageCleanup(connectedEnvironments)) {
656 return (
657 <SettingsSection id="storage-worktrees" title={gt`Cleanup`} variant="plain">
658 <StorageCleanupScopeNotice />
659 </SettingsSection>
660 );
661 }
662​
663 return (
664 <SettingsSection id="storage-worktrees" title={gt`Cleanup`}>
665 <>
666 {isProjectScope && (
667 <SettingsRow
668 title={gt`Automatic worktree cleanup`}
669 description={
670 mode === "off"
671 ? gt`Keep this project's worktrees until you delete them manually.`
672 : mode === "custom"
673 ? gt`Use these rules for this project.`
674 : gt`Use each machine's worktree cleanup settings.`
675 }
676 serverScoped
677 settingKeys={["worktreeCleanup"]}
678 mixed={mixedModes}
679 control={
680 <Select
681 value={mixedModes ? null : mode}
682 onValueChange={(next) => {
683 if (next === "inherit") clearSettings(["worktreeCleanup"]);
684 else if (next === "off") updateSettings({ worktreeCleanup: { mode: "off" } });
685 else if (next === "custom")
686 updateSettings({ worktreeCleanup: { mode: "custom", rules: {} } });
687 }}
688 >
689 <SelectTrigger size="sm" aria-label={gt`Automatic worktree cleanup`}>
690 <SelectValue>
691 {mixedModes
692 ? gt`Mixed`
693 : mode === "inherit"
694 ? gt`Inherit`
695 : mode === "off"
696 ? gt`Off`
697 : gt`Custom`}
698 </SelectValue>
699 </SelectTrigger>
700 <SelectPopup align="end" alignItemWithTrigger={false}>
701 <SelectItem value="inherit">
702 <T>Inherit</T>
703 </SelectItem>
704 <SelectItem value="off">
705 <T>Off</T>
706 </SelectItem>
707 <SelectItem value="custom">
708 <T>Custom</T>
709 </SelectItem>
710 </SelectPopup>
711 </Select>
712 }
713 />
714 )}
715 {(!isProjectScope || (!mixedModes && mode === "custom")) && (
716 <>
717 <SettingsRow
718 title={gt`Delete worktrees with deleted threads`}
719 status={ruleStatus("worktreeOnDelete")}
720 managedPaths={lockablePath("worktreeOnDelete")}
721 description={gt`Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept.`}
722 serverScoped={!isProjectScope}
723 control={
724 <Switch
725 aria-label={gt`Delete worktrees with deleted threads`}
726 checked={settings.worktreeOnDelete}
727 onCheckedChange={(worktreeOnDelete) => updateWorktree({ worktreeOnDelete })}
728 />
729 }
730 />
731 <SettingsRow
732 title={gt`Delete merged worktrees`}
733 status={ruleStatus("worktreeOnMerge")}
734 managedPaths={lockablePath("worktreeOnMerge")}
735 description={gt`Remove worktrees whose pull request is merged and whose commits are included in the default branch.`}
736 serverScoped={!isProjectScope}
737 control={
738 <Switch
739 aria-label={gt`Delete merged worktrees`}
740 checked={settings.worktreeOnMerge}
741 onCheckedChange={(worktreeOnMerge) => updateWorktree({ worktreeOnMerge })}
742 />
743 }
744 />
745 <SettingsRow
746 title={gt`Delete inactive worktrees`}
747 status={ruleStatus("worktreeAfterDays")}
748 managedPaths={lockablePath("worktreeAfterDays")}
749 description={gt`Remove worktrees after their threads have been inactive for this many days. Branches and thread history are kept.`}
750 serverScoped={!isProjectScope}
751 control={
752 <RetentionControl
753 label={gt`Delete inactive worktrees`}
754 value={settings.worktreeAfterDays}
755 onChange={(worktreeAfterDays, onFailed) =>
756 updateWorktree({ worktreeAfterDays }, { onFailed })
757 }
758 />
759 }
760 />
761 <AdvancedSettings
762 // The keep-when search result lands on this section, not its row.
763 targetIds={["storage-worktrees", setting("storage-worktree-keep-when").id]}
764 >
765 {connectedEnvironments.length > 0 &&
766 connectedEnvironments.every(
767 (environment) =>
768 environment.serverConfig?.environment.capabilities.settledWorktreeCleanup ===
769 true,
770 ) && (
771 <SettingsRow
772 title={gt`Delete settled worktrees`}
773 managedPaths={lockablePath("worktreeSettledAfterDays")}
774 status={[
775 ruleStatus("worktreeSettledAfterDays"),
776 environments.length > connectedEnvironments.length
777 ? gt`Offline machines will not get this setting`
778 : undefined,
779 ]
780 .filter(Boolean)
781 .join(". ")}
782 description={gt`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.`}
783 serverScoped={!isProjectScope}
784 control={
785 <RetentionControl
786 label={gt`Delete settled worktrees`}
787 value={settings.worktreeSettledAfterDays}
788 minimum={0}
789 onChange={(worktreeSettledAfterDays, onFailed) =>
790 updateWorktree({ worktreeSettledAfterDays }, { onFailed })
791 }
792 />
793 }
794 />
795 )}
796 <SettingsRow
797 title={gt`Delete unchanged worktrees`}
798 status={ruleStatus("worktreeUnchanged")}
799 managedPaths={lockablePath("worktreeUnchanged")}
800 description={gt`Remove worktrees with no commits beyond the default branch.`}
801 serverScoped={!isProjectScope}
802 control={
803 <Switch
804 aria-label={gt`Delete unchanged worktrees`}
805 checked={settings.worktreeUnchanged}
806 onCheckedChange={(worktreeUnchanged) => updateWorktree({ worktreeUnchanged })}
807 />
808 }
809 />
810 {connectedEnvironments.every(
811 (environment) =>
812 environment.serverConfig?.environment.capabilities.storageCleanupRun === true,
813 ) && (
814 <SettingsRow
815 {...setting("storage-worktree-keep-when")}
816 status={ruleStatus("worktreeKeepWhen")}
817 managedPaths={lockablePath("worktreeKeepWhen")}
818 description={
819 settings.worktreeKeepWhen === "any-local-files"
820 ? gt`Includes ignored files, except node_modules.`
821 : settings.worktreeKeepWhen === "tracked-changes"
822 ? gt`Deletes untracked and ignored files, including .env.`
823 : gt`Keeps edits and untracked files. Deletes ignored files, including .env.`
824 }
825 serverScoped={!isProjectScope}
826 control={
827 <Select
828 value={ruleStatus("worktreeKeepWhen") ? null : settings.worktreeKeepWhen}
829 onValueChange={(next) => {
830 if (
831 next === "any-local-files" ||
832 next === "uncommitted-changes" ||
833 next === "tracked-changes"
834 )
835 updateWorktree({ worktreeKeepWhen: next });
836 }}
837 >
838 <SelectTrigger size="sm" aria-label={gt`Keep worktrees with local changes`}>
839 <SelectValue>
840 {ruleStatus("worktreeKeepWhen")
841 ? gt`Mixed`
842 : messages(KEEP_WHEN_LABELS[settings.worktreeKeepWhen])}
843 </SelectValue>
844 </SelectTrigger>
845 <SelectPopup align="end" alignItemWithTrigger={false}>
846 <SelectItem value="any-local-files">
847 <T>Any local files</T>
848 </SelectItem>
849 <SelectItem value="uncommitted-changes">
850 <T>Uncommitted changes</T>
851 </SelectItem>
852 <SelectItem value="tracked-changes">
853 <T>Edited tracked files</T>
854 </SelectItem>
855 </SelectPopup>
856 </Select>
857 }
858 />
859 )}
860 </AdvancedSettings>
861 </>
862 )}
863 </>
864 </SettingsSection>
865 );
867​
868/** Retention for logs and captures, and the manual cleanup run, which covers worktrees too. */
869export function StorageCleanupSections() {
870 const gt = useGT();
871 const { scope, connectedEnvironments, targets } = useSettingsScope();
872 const scopedSettings = useScopedSettings();
873 const updateSettings = useUpdateScopedSettings();
874 const settings = scopedSettings.storageCleanup;
875 const targetIdsKey = environmentIdsKey(targets.map((target) => target.environmentId).sort());
876 const artifactsMixed =
877 targets.length > 1 &&
878 targets.some(
879 (target) =>
880 target.settings.storageCleanup.browserArtifactsAfterDays !==
881 settings.browserArtifactsAfterDays,
882 );
883 const logsMixed =
884 targets.length > 1 &&
885 targets.some(
886 (target) => target.settings.storageCleanup.logsAfterDays !== settings.logsAfterDays,
887 );
888 const settledArtifactsStatus = useDebouncedValue(`${targetIdsKey}:${artifactsMixed}`, 300);
889 const settledLogsStatus = useDebouncedValue(`${targetIdsKey}:${logsMixed}`, 300);
890 const artifactsStatus =
891 targets.length > 1 && settledArtifactsStatus === `${targetIdsKey}:true`
892 ? gt`Mixed across selected machines`
893 : undefined;
894 const logsStatus =
895 targets.length > 1 && settledLogsStatus === `${targetIdsKey}:true`
896 ? gt`Mixed across selected machines`
897 : undefined;
898 if (scope.kind === "project" || scope.kind === "checkout") return null;
899 const update = (patch: Partial<StorageCleanupSettings>, options: SaveOptions) =>
900 updateSettings({ storageCleanup: patch }, options);
901 const databaseStorageNotice = (
902 <DatabaseStorageNotice
903 environments={connectedEnvironments.filter(
904 (environment) =>
905 environment.serverConfig?.environment.capabilities.databaseStorage === true,
906 )}
907 />
908 );
909 if (!supportsStorageCleanup(connectedEnvironments)) {
910 return (
911 <>
912 <SettingsSection id="storage-artifacts" title={gt`Artifacts and logs`} variant="plain">
913 <StorageCleanupScopeNotice />
914 </SettingsSection>
915 {databaseStorageNotice}
916 </>
917 );
918 }
919​
920 // Machines report their databases after the page renders, so the notice goes last to push nothing down.
921 return (
922 <>
923 <SettingsSection id="storage-artifacts" title={gt`Artifacts and logs`}>
924 <AnimatedHeight>
925 <SettingsRow
926 title={gt`Delete old browser artifacts`}
927 status={artifactsStatus}
928 managedPaths={["storageCleanup.browserArtifactsAfterDays"]}
929 description={gt`Delete saved browser captures after this many days. Older capture links will no longer open.`}
930 serverScoped
931 control={
932 <RetentionControl
933 label={gt`Delete old browser artifacts`}
934 value={settings.browserArtifactsAfterDays}
935 onChange={(browserArtifactsAfterDays, onFailed) =>
936 update({ browserArtifactsAfterDays }, { onFailed })
937 }
938 />
939 }
940 />
941 </AnimatedHeight>
942 <AnimatedHeight>
943 <SettingsRow
944 title={gt`Delete old rotated logs`}
945 status={logsStatus}
946 managedPaths={["storageCleanup.logsAfterDays"]}
947 description={gt`Delete inactive rotated log files after this many days. Current logs are kept.`}
948 serverScoped
949 control={
950 <RetentionControl
951 label={gt`Delete old rotated logs`}
952 value={settings.logsAfterDays}
953 onChange={(logsAfterDays, onFailed) => update({ logsAfterDays }, { onFailed })}
954 />
955 }
956 />
957 </AnimatedHeight>
958 </SettingsSection>
959 <CleanupSection />
960 {databaseStorageNotice}
961 </>
962 );