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