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

StorageSettings.tsx

696 lines26.0 KB

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