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

StorageSettings.tsx

647 lines23.5 KB

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