Open History to see the last commit
1import type {
2 StorageCleanupReport,
3 StorageCleanupSettings,
4 WorktreeCleanupRules,
5} from "@t3tools/contracts";
6import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
7import { useRef, useState } from "react";
8import { useAtomValue } from "@effect/atom-react";
9import { 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 Atom.make((get) =>
263 connectedEnvironments.flatMap((environment) => {
264 if (environment.serverConfig?.environment.capabilities.storageCleanupRun !== true)
265 return [];
266 const query = get(
267 serverEnvironment.storageCleanupReport({
268 environmentId: environment.environmentId,
269 input: {},
270 }),
271 );
272 return [
273 {
274 environmentId: environment.environmentId,
275 allowed: get(
276 serverEnvironment.runStorageCleanup.permissionAtom(environment.environmentId),
277 ),
278 report: query._tag === "Success" ? query.value : null,
279 loading: query.waiting,
280 failed: query._tag === "Failure",
281 },
282 ];
283 }),
284 ),
285 );
286 const hasRules = supported.some((environment) => {
287 const settings = environment.serverConfig?.settings;
288 if (!settings) return false;
289 const enabled = (rules: WorktreeCleanupRules) =>
290 rules.worktreeAfterDays !== null ||
291 rules.worktreeSettledAfterDays !== null ||
292 rules.worktreeOnMerge ||
293 rules.worktreeOnDelete ||
294 rules.worktreeUnchanged;
295 return (
296 settings.storageCleanup.browserArtifactsAfterDays !== null ||
297 settings.storageCleanup.logsAfterDays !== null ||
298 enabled(resolveWorktreeCleanup(settings, null)) ||
299 Object.values(settings.projectSettingsOverrides).some(
300 (override) =>
301 override.worktreeCleanup?.mode === "custom" && enabled(override.worktreeCleanup.rules),
302 )
303 );
304 });
305 if (supported.length === 0) return null;
306 const summaries = supported.map((environment) => {
307 const query = state.find((entry) => entry.environmentId === environment.environmentId);
308 const report = query?.report ?? null;
309 return {
310 environment,
311 report,
312 label: settingsScopeEnvironmentLabel(environment, connectedEnvironments),
313 counts: report
314 ? `${report.counts.removed} removed, ${report.counts.kept} kept${report.counts.failed > 0 ? `, ${report.counts.failed} failed` : ""}`
315 : "",
316 description: report
317 ? `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.` : ""}`
318 : query?.failed
319 ? "Could not load the last run."
320 : query?.loading
321 ? "Loading last run…"
322 : "Cleanup hasn't run yet.",
323 };
324 });
325 const deleteNow = async () => {
326 if (pending) return;
327 setPending(true);
328 await Promise.all(
329 supported
330 .filter((environment) =>
331 state.some((entry) => entry.environmentId === environment.environmentId && entry.allowed),
332 )
333 .map(async (environment) => {
334 const result = await run({ environmentId: environment.environmentId, input: {} });
335 if (result._tag === "Success") {
336 const failures = result.value.entries.filter((entry) => entry.outcome === "failed");
337 if (failures.length > 0)
338 toastManager.add({
339 type: "error",
340 title: `Cleanup failed on ${environment.label}`,
341 description: failures[0]!.reason,
342 });
343 } else if (!isAtomCommandInterrupted(result)) {
344 toastManager.add({
345 type: "error",
346 title: `Could not run cleanup on ${environment.label}`,
347 description: String(squashAtomCommandFailure(result)),
348 });
349 }
350 }),
351 ).finally(() => setPending(false));
352 };
353 return (
354 <SettingsSection id="storage-cleanup" title="Cleanup" variant="plain">
355 <SettingsGroup>
356 <SettingsRow
357 {...searchableSetting("storage-delete-now")}
358 description={
359 <span>
360 {!hasRules
361 ? "Turn on a cleanup rule to use this."
362 : summaries.map(({ environment, label, description }) => (
363 <span key={environment.environmentId} className="block">
364 {supported.length > 1 ? `${label}: ` : ""}
365 {description}
366 </span>
367 ))}
368 </span>
369 }
370 control={
371 <Button
372 variant="outline"
373 size="sm"
374 disabled={pending || !hasRules || !state.some((entry) => entry.allowed)}
375 onClick={() => void deleteNow()}
376 >
377 {pending ? "Deleting…" : "Delete now"}
378 </Button>
379 }
380 />
381 </SettingsGroup>
382 {summaries.some(({ report }) => report !== null) && (
383 <FoldedSettingsSection
384 id="storage-cleanup-last-run"
385 title="Last run"
386 headerPlacement="inside"
387 summary={lastRunSummary(
388 summaries.filter(({ report }) => report !== null),
389 connectedEnvironments.length,
390 )}
391 >
392 {summaries.map(
393 ({ environment, label, report }) =>
394 report && (
395 <CleanupResults
396 key={environment.environmentId}
397 report={report}
398 environmentLabel={connectedEnvironments.length > 1 ? label : undefined}
399 />
400 ),
401 )}
402 </FoldedSettingsSection>
403 )}
404 </SettingsSection>
405 );
406}
407
408export function StorageSettingsPanel() {
409 const { scope, environments, connectedEnvironments, targets, target } = useSettingsScope();
410 const scopedSettings = useScopedSettings();
411 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
412 const settings = {
413 ...scopedSettings.storageCleanup,
414 ...resolveWorktreeCleanup(scopedSettings, null),
415 };
416 const projectMode = (entry: ScopedSettingsTarget | null) =>
417 entry?.sources.worktreeCleanup === "project"
418 ? (entry.settings.worktreeCleanup?.mode ?? "inherit")
419 : "inherit";
420 const mode = projectMode(target);
421 const mixedModes = targets.some((entry) => projectMode(entry) !== mode);
422 const updateSettings = useUpdateScopedSettings();
423 const clearSettings = useClearScopedSettings();
424 const ruleStatus = (key: keyof StorageCleanupSettings) =>
425 targets.some(
426 (target) =>
427 ({ ...target.settings.storageCleanup, ...resolveWorktreeCleanup(target.settings, null) })[
428 key
429 ] !== settings[key],
430 )
431 ? "Mixed across selected machines"
432 : undefined;
433 const update = (patch: Partial<StorageCleanupSettings>) =>
434 updateSettings({ storageCleanup: patch });
435 const updateWorktree = (patch: Partial<WorktreeCleanupRules>) =>
436 isProjectScope
437 ? updateSettings({ worktreeCleanup: { mode: "custom", rules: patch } })
438 : update(patch);
439
440 if (
441 isProjectScope &&
442 connectedEnvironments.some(
443 (environment) =>
444 environment.serverConfig?.environment.capabilities.projectWorktreeCleanup !== true,
445 )
446 ) {
447 return (
448 <SettingsScopeNotice target="all">
449 Update the selected machines to configure project worktree cleanup.
450 </SettingsScopeNotice>
451 );
452 }
453
454 if (
455 connectedEnvironments.some(
456 (environment) => environment.serverConfig?.environment.capabilities.storageCleanup !== true,
457 )
458 ) {
459 return (
460 <SettingsScopeNotice
461 target="environment"
462 eligibleEnvironmentIds={connectedEnvironments
463 .filter(
464 (environment) =>
465 environment.serverConfig?.environment.capabilities.storageCleanup === true,
466 )
467 .map((environment) => environment.environmentId)}
468 >
469 Update the selected environments to use storage cleanup, or choose a machine that supports
470 it.
471 </SettingsScopeNotice>
472 );
473 }
474
475 return (
476 <SettingsPageContainer>
477 {!isProjectScope &&
478 connectedEnvironments
479 .filter(
480 (environment) =>
481 environment.serverConfig?.environment.capabilities.databaseStorage === true,
482 )
483 .map((environment) => (
484 <DatabaseStorageNotice
485 key={environment.environmentId}
486 environmentId={environment.environmentId}
487 label={environment.label}
488 />
489 ))}
490 <SettingsSection id="storage-worktrees" title="Worktrees">
491 {!isProjectScope && <WorktreesDirectoryRow />}
492 {isProjectScope && (
493 <SettingsRow
494 title="Automatic worktree cleanup"
495 description={
496 mode === "off"
497 ? "Keep this project's worktrees until you delete them manually."
498 : mode === "custom"
499 ? "Use these rules for this project."
500 : "Use each machine's worktree cleanup settings."
501 }
502 serverScoped
503 settingKeys={["worktreeCleanup"]}
504 mixed={mixedModes}
505 control={
506 <Select
507 value={mixedModes ? null : mode}
508 onValueChange={(next) => {
509 if (next === "inherit") clearSettings(["worktreeCleanup"]);
510 else if (next === "off") updateSettings({ worktreeCleanup: { mode: "off" } });
511 else if (next === "custom")
512 updateSettings({ worktreeCleanup: { mode: "custom", rules: {} } });
513 }}
514 >
515 <SelectTrigger size="sm" aria-label="Automatic worktree cleanup">
516 <SelectValue>
517 {mixedModes
518 ? "Mixed"
519 : mode === "inherit"
520 ? "Inherit"
521 : mode === "off"
522 ? "Off"
523 : "Custom"}
524 </SelectValue>
525 </SelectTrigger>
526 <SelectPopup align="end" alignItemWithTrigger={false}>
527 <SelectItem value="inherit">Inherit</SelectItem>
528 <SelectItem value="off">Off</SelectItem>
529 <SelectItem value="custom">Custom</SelectItem>
530 </SelectPopup>
531 </Select>
532 }
533 />
534 )}
535 {(!isProjectScope || (!mixedModes && mode === "custom")) && (
536 <>
537 <SettingsRow
538 title="Delete worktrees with deleted threads"
539 status={ruleStatus("worktreeOnDelete")}
540 description="Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept."
541 serverScoped={!isProjectScope}
542 control={
543 <Switch
544 aria-label="Delete worktrees with deleted threads"
545 checked={settings.worktreeOnDelete}
546 onCheckedChange={(worktreeOnDelete) => updateWorktree({ worktreeOnDelete })}
547 />
548 }
549 />
550 <SettingsRow
551 title="Delete inactive worktrees"
552 status={ruleStatus("worktreeAfterDays")}
553 description="Remove worktrees after their threads have been inactive for this many days. Branches and thread history are kept."
554 serverScoped={!isProjectScope}
555 control={
556 <RetentionControl
557 label="Delete inactive worktrees"
558 value={settings.worktreeAfterDays}
559 onChange={(worktreeAfterDays) => updateWorktree({ worktreeAfterDays })}
560 />
561 }
562 />
563 {connectedEnvironments.length > 0 &&
564 connectedEnvironments.every(
565 (environment) =>
566 environment.serverConfig?.environment.capabilities.settledWorktreeCleanup ===
567 true,
568 ) && (
569 <SettingsRow
570 title="Delete settled worktrees"
571 status={[
572 ruleStatus("worktreeSettledAfterDays"),
573 environments.length > connectedEnvironments.length
574 ? "Offline machines will not get this setting"
575 : undefined,
576 ]
577 .filter(Boolean)
578 .join(". ")}
579 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."
580 serverScoped={!isProjectScope}
581 control={
582 <RetentionControl
583 label="Delete settled worktrees"
584 value={settings.worktreeSettledAfterDays}
585 minimum={0}
586 onChange={(worktreeSettledAfterDays) =>
587 updateWorktree({ worktreeSettledAfterDays })
588 }
589 />
590 }
591 />
592 )}
593 <SettingsRow
594 title="Delete merged worktrees"
595 status={ruleStatus("worktreeOnMerge")}
596 description="Remove worktrees whose pull request is merged and whose commits are included in the default branch."
597 serverScoped={!isProjectScope}
598 control={
599 <Switch
600 aria-label="Delete merged worktrees"
601 checked={settings.worktreeOnMerge}
602 onCheckedChange={(worktreeOnMerge) => updateWorktree({ worktreeOnMerge })}
603 />
604 }
605 />
606 <SettingsRow
607 title="Delete unchanged worktrees"
608 status={ruleStatus("worktreeUnchanged")}
609 description="Remove worktrees with no commits beyond the default branch."
610 serverScoped={!isProjectScope}
611 control={
612 <Switch
613 aria-label="Delete unchanged worktrees"
614 checked={settings.worktreeUnchanged}
615 onCheckedChange={(worktreeUnchanged) => updateWorktree({ worktreeUnchanged })}
616 />
617 }
618 />
619 {connectedEnvironments.every(
620 (environment) =>
621 environment.serverConfig?.environment.capabilities.storageCleanupRun === true,
622 ) && (
623 <SettingsRow
624 {...searchableSetting("storage-worktree-keep-when")}
625 status={ruleStatus("worktreeKeepWhen")}
626 description={
627 settings.worktreeKeepWhen === "any-local-files"
628 ? "Includes ignored files, except node_modules."
629 : settings.worktreeKeepWhen === "tracked-changes"
630 ? "Deletes untracked and ignored files, including .env."
631 : "Keeps edits and untracked files. Deletes ignored files, including .env."
632 }
633 serverScoped={!isProjectScope}
634 control={
635 <Select
636 value={ruleStatus("worktreeKeepWhen") ? null : settings.worktreeKeepWhen}
637 onValueChange={(next) => {
638 if (
639 next === "any-local-files" ||
640 next === "uncommitted-changes" ||
641 next === "tracked-changes"
642 )
643 updateWorktree({ worktreeKeepWhen: next });
644 }}
645 >
646 <SelectTrigger size="sm" aria-label="Keep worktrees with local changes">
647 <SelectValue>
648 {ruleStatus("worktreeKeepWhen")
649 ? "Mixed"
650 : KEEP_WHEN_LABELS[settings.worktreeKeepWhen]}
651 </SelectValue>
652 </SelectTrigger>
653 <SelectPopup align="end" alignItemWithTrigger={false}>
654 <SelectItem value="any-local-files">Any local files</SelectItem>
655 <SelectItem value="uncommitted-changes">Uncommitted changes</SelectItem>
656 <SelectItem value="tracked-changes">Edited tracked files</SelectItem>
657 </SelectPopup>
658 </Select>
659 }
660 />
661 )}
662 </>
663 )}
664 </SettingsSection>
665
666 {!isProjectScope && (
667 <SettingsSection id="storage-artifacts" title="Artifacts and logs">
668 <SettingsRow
669 title="Delete old browser artifacts"
670 status={ruleStatus("browserArtifactsAfterDays")}
671 description="Delete saved browser captures after this many days. Older capture links will no longer open."
672 serverScoped
673 control={
674 <RetentionControl
675 label="Delete old browser artifacts"
676 value={settings.browserArtifactsAfterDays}
677 onChange={(browserArtifactsAfterDays) => update({ browserArtifactsAfterDays })}
678 />
679 }
680 />
681 <SettingsRow
682 title="Delete old rotated logs"
683 status={ruleStatus("logsAfterDays")}
684 description="Delete inactive rotated log files after this many days. Current logs are kept."
685 serverScoped
686 control={
687 <RetentionControl
688 label="Delete old rotated logs"
689 value={settings.logsAfterDays}
690 onChange={(logsAfterDays) => update({ logsAfterDays })}
691 />
692 }
693 />
694 </SettingsSection>
695 )}
696 {!isProjectScope && <CleanupSection />}
697 </SettingsPageContainer>
698 );
699}