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