Open History to see the last commit
1import type { StorageCleanupSettings, WorktreeCleanupRules } from "@t3tools/contracts";
2import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
3import { useRef, useState } from "react";
4
5import { Input } from "../ui/input";
6import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
7import { Switch } from "../ui/switch";
8import {
9 NumberField,
10 NumberFieldDecrement,
11 NumberFieldGroup,
12 NumberFieldIncrement,
13 NumberFieldInput,
14} from "../ui/number-field";
15import {
16 SettingResetButton,
17 SettingsPageContainer,
18 SettingsRow,
19 SettingsSection,
20} from "./settingsLayout";
21import { SettingsScopeNotice } from "./SettingsScopeNotice";
22import type { ScopedSettingsTarget } from "./scopedSettings";
23import { useSettingsScope } from "./SettingsScopeContext";
24import { searchableSetting } from "./settingsSearch";
25import {
26 useClearScopedSettings,
27 useScopedSettings,
28 useScopedSettingsMixed,
29 useUpdateScopedSettings,
30} from "./useScopedSettings";
31
32function WorktreesDirectoryRow() {
33 const { connectedEnvironments, targets } = useSettingsScope();
34 const settings = useScopedSettings();
35 const updateSettings = useUpdateScopedSettings();
36 const mixed = useScopedSettingsMixed(["worktreesDirectory"]);
37 const edited = useRef(false);
38 if (
39 connectedEnvironments.some(
40 (environment) =>
41 environment.serverConfig?.environment.capabilities.worktreesDirectory !== true,
42 )
43 )
44 return null;
45 const scopeKey = targets.map((target) => target.environmentId).join(",");
46
47 return (
48 <SettingsRow
49 {...searchableSetting("storage-worktrees-location")}
50 description={
51 "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."
52 }
53 serverScoped
54 settingKeys={["worktreesDirectory"]}
55 resetAction={
56 mixed || settings.worktreesDirectory !== "" ? (
57 <SettingResetButton
58 label="worktree location"
59 onClick={() => updateSettings({ worktreesDirectory: "" })}
60 />
61 ) : null
62 }
63 control={
64 <Input
65 key={`${scopeKey}:${mixed}:${settings.worktreesDirectory}`}
66 aria-label="Worktree location"
67 autoCapitalize="none"
68 spellCheck={false}
69 placeholder={mixed ? "Mixed" : "Default"}
70 defaultValue={mixed ? "" : settings.worktreesDirectory}
71 onChange={() => {
72 edited.current = true;
73 }}
74 onBlur={(event) => {
75 const value = event.target.value.trim();
76 if (edited.current && (mixed || value !== settings.worktreesDirectory))
77 updateSettings({ worktreesDirectory: value });
78 edited.current = false;
79 }}
80 />
81 }
82 />
83 );
84}
85
86function RetentionControl({
87 label,
88 value,
89 onChange,
90}: {
91 label: string;
92 value: number | null;
93 onChange: (value: number | null) => void;
94}) {
95 const [draft, setDraft] = useState(value);
96 const [savedValue, setSavedValue] = useState(value);
97 if (savedValue !== value) {
98 setSavedValue(value);
99 setDraft(value);
100 }
101
102 return (
103 <div className="flex items-center gap-3">
104 {value !== null ? (
105 <NumberField
106 value={draft}
107 min={1}
108 max={3650}
109 step={1}
110 size="sm"
111 className="w-auto"
112 onValueChange={setDraft}
113 onValueCommitted={(next) => {
114 if (next === null) setDraft(value);
115 else {
116 const days = Math.min(3650, Math.max(1, Math.round(next)));
117 setDraft(days);
118 onChange(days);
119 }
120 }}
121 >
122 <NumberFieldGroup>
123 <NumberFieldDecrement aria-label={`Decrease ${label}`} />
124 <NumberFieldInput
125 aria-label={`${label} in days`}
126 size={new Intl.NumberFormat().format(draft ?? value).length}
127 className="field-sizing-content w-auto min-w-[1ch] grow-0 text-right"
128 />
129 <span aria-hidden="true" className="self-center pr-2 text-xs">
130 days
131 </span>
132 <NumberFieldIncrement aria-label={`Increase ${label}`} />
133 </NumberFieldGroup>
134 </NumberField>
135 ) : (
136 <span className="text-xs text-muted-foreground">Off</span>
137 )}
138 <Switch
139 aria-label={label}
140 checked={value !== null}
141 onCheckedChange={(enabled) => onChange(enabled ? 8 : null)}
142 />
143 </div>
144 );
145}
146
147export function StorageSettingsPanel() {
148 const { scope, connectedEnvironments, targets, target } = useSettingsScope();
149 const scopedSettings = useScopedSettings();
150 const isProjectScope = scope.kind === "project" || scope.kind === "checkout";
151 const settings = {
152 ...scopedSettings.storageCleanup,
153 ...resolveWorktreeCleanup(scopedSettings, null),
154 };
155 const projectMode = (entry: ScopedSettingsTarget | null) =>
156 entry?.sources.worktreeCleanup === "project"
157 ? (entry.settings.worktreeCleanup?.mode ?? "inherit")
158 : "inherit";
159 const mode = projectMode(target);
160 const mixedModes = targets.some((entry) => projectMode(entry) !== mode);
161 const updateSettings = useUpdateScopedSettings();
162 const clearSettings = useClearScopedSettings();
163 const ruleStatus = (key: keyof StorageCleanupSettings) =>
164 targets.some(
165 (target) =>
166 ({ ...target.settings.storageCleanup, ...resolveWorktreeCleanup(target.settings, null) })[
167 key
168 ] !== settings[key],
169 )
170 ? "Mixed across selected machines"
171 : undefined;
172 const update = (patch: Partial<StorageCleanupSettings>) =>
173 updateSettings({ storageCleanup: patch });
174 const updateWorktree = (patch: Partial<WorktreeCleanupRules>) =>
175 isProjectScope
176 ? updateSettings({ worktreeCleanup: { mode: "custom", rules: patch } })
177 : update(patch);
178
179 if (
180 isProjectScope &&
181 connectedEnvironments.some(
182 (environment) =>
183 environment.serverConfig?.environment.capabilities.projectWorktreeCleanup !== true,
184 )
185 ) {
186 return (
187 <SettingsScopeNotice target="all">
188 Update the selected machines to configure project worktree cleanup.
189 </SettingsScopeNotice>
190 );
191 }
192
193 if (
194 connectedEnvironments.some(
195 (environment) => environment.serverConfig?.environment.capabilities.storageCleanup !== true,
196 )
197 ) {
198 return (
199 <SettingsScopeNotice
200 target="environment"
201 eligibleEnvironmentIds={connectedEnvironments
202 .filter(
203 (environment) =>
204 environment.serverConfig?.environment.capabilities.storageCleanup === true,
205 )
206 .map((environment) => environment.environmentId)}
207 >
208 Update the selected environments to use storage cleanup, or choose a machine that supports
209 it.
210 </SettingsScopeNotice>
211 );
212 }
213
214 return (
215 <SettingsPageContainer>
216 <SettingsSection id="storage-worktrees" title="Worktrees">
217 {!isProjectScope && <WorktreesDirectoryRow />}
218 {isProjectScope && (
219 <SettingsRow
220 title="Automatic worktree cleanup"
221 description={
222 mode === "off"
223 ? "Keep this project's worktrees until you delete them manually."
224 : mode === "custom"
225 ? "Use these rules for this project."
226 : "Use each machine's worktree cleanup settings."
227 }
228 serverScoped
229 settingKeys={["worktreeCleanup"]}
230 mixed={mixedModes}
231 control={
232 <Select
233 value={mixedModes ? null : mode}
234 onValueChange={(next) => {
235 if (next === "inherit") clearSettings(["worktreeCleanup"]);
236 else if (next === "off") updateSettings({ worktreeCleanup: { mode: "off" } });
237 else if (next === "custom")
238 updateSettings({ worktreeCleanup: { mode: "custom", rules: {} } });
239 }}
240 >
241 <SelectTrigger size="sm" aria-label="Automatic worktree cleanup">
242 <SelectValue>
243 {mixedModes
244 ? "Mixed"
245 : mode === "inherit"
246 ? "Inherit"
247 : mode === "off"
248 ? "Off"
249 : "Custom"}
250 </SelectValue>
251 </SelectTrigger>
252 <SelectPopup align="end" alignItemWithTrigger={false}>
253 <SelectItem value="inherit">Inherit</SelectItem>
254 <SelectItem value="off">Off</SelectItem>
255 <SelectItem value="custom">Custom</SelectItem>
256 </SelectPopup>
257 </Select>
258 }
259 />
260 )}
261 {(!isProjectScope || (!mixedModes && mode === "custom")) && (
262 <>
263 <SettingsRow
264 title="Delete worktrees with deleted threads"
265 status={ruleStatus("worktreeOnDelete")}
266 description="Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept."
267 serverScoped={!isProjectScope}
268 control={
269 <Switch
270 aria-label="Delete worktrees with deleted threads"
271 checked={settings.worktreeOnDelete}
272 onCheckedChange={(worktreeOnDelete) => updateWorktree({ worktreeOnDelete })}
273 />
274 }
275 />
276 <SettingsRow
277 title="Delete inactive worktrees"
278 status={ruleStatus("worktreeAfterDays")}
279 description="Remove worktrees after their threads have been inactive for this many days. Branches and thread history are kept."
280 serverScoped={!isProjectScope}
281 control={
282 <RetentionControl
283 label="Delete inactive worktrees"
284 value={settings.worktreeAfterDays}
285 onChange={(worktreeAfterDays) => updateWorktree({ worktreeAfterDays })}
286 />
287 }
288 />
289 <SettingsRow
290 title="Delete merged worktrees"
291 status={ruleStatus("worktreeOnMerge")}
292 description="Remove worktrees whose pull request is merged and whose commits are included in the default branch."
293 serverScoped={!isProjectScope}
294 control={
295 <Switch
296 aria-label="Delete merged worktrees"
297 checked={settings.worktreeOnMerge}
298 onCheckedChange={(worktreeOnMerge) => updateWorktree({ worktreeOnMerge })}
299 />
300 }
301 />
302 <SettingsRow
303 title="Delete unchanged worktrees"
304 status={ruleStatus("worktreeUnchanged")}
305 description="Remove worktrees with no commits beyond the default branch."
306 serverScoped={!isProjectScope}
307 control={
308 <Switch
309 aria-label="Delete unchanged worktrees"
310 checked={settings.worktreeUnchanged}
311 onCheckedChange={(worktreeUnchanged) => updateWorktree({ worktreeUnchanged })}
312 />
313 }
314 />
315 </>
316 )}
317 </SettingsSection>
318
319 {!isProjectScope && (
320 <SettingsSection id="storage-artifacts" title="Artifacts and logs">
321 <SettingsRow
322 title="Delete old browser artifacts"
323 status={ruleStatus("browserArtifactsAfterDays")}
324 description="Delete saved browser captures after this many days. Older capture links will no longer open."
325 serverScoped
326 control={
327 <RetentionControl
328 label="Delete old browser artifacts"
329 value={settings.browserArtifactsAfterDays}
330 onChange={(browserArtifactsAfterDays) => update({ browserArtifactsAfterDays })}
331 />
332 }
333 />
334 <SettingsRow
335 title="Delete old rotated logs"
336 status={ruleStatus("logsAfterDays")}
337 description="Delete inactive rotated log files after this many days. Current logs are kept."
338 serverScoped
339 control={
340 <RetentionControl
341 label="Delete old rotated logs"
342 value={settings.logsAfterDays}
343 onChange={(logsAfterDays) => update({ logsAfterDays })}
344 />
345 }
346 />
347 </SettingsSection>
348 )}
349 </SettingsPageContainer>
350 );
351}