The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { |
| 2 | StorageCleanupReport, |
| 3 | StorageCleanupSettings, |
| 4 | WorktreeCleanupRules, |
| 5 | } from "@t3tools/contracts"; |
| 6 | import { resolvePastedPath } from "@t3tools/shared/path"; |
| 7 | import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings"; |
| 8 | import { useRef, useState } from "react"; |
| 9 | import { useAtomValue } from "@effect/atom-react"; |
| 10 | import { |
| 11 | isAtomCommandInterrupted, |
| 12 | squashAtomCommandFailure, |
| 13 | } from "@t3tools/client-runtime/state/runtime"; |
| 14 | import { formatBytes } from "../../lib/formatBytes"; |
| 15 | import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList"; |
| 16 | import { serverEnvironment } from "../../state/server"; |
| 17 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 18 | import { formatRelativeTimeLabel } from "../../timestampFormat"; |
| 19 | import { useNowMinute } from "../../hooks/useNowMinute"; |
| 20 | import { useDebouncedValue } from "../../state/queries"; |
| 21 | import { AnimatedHeight } from "../AnimatedHeight"; |
| 22 | import { Button } from "../ui/button"; |
| 23 | import { toastManager } from "../ui/toast"; |
| 24 | import { msg, T, useGT, useMessages, Var } from "gt-react"; |
| 25 | import { m, type MessageResolver } from "../../i18n/messages"; |
| 26 | |
| 27 | import { Input } from "../ui/input"; |
| 28 | import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; |
| 29 | import { Switch } from "../ui/switch"; |
| 30 | import { |
| 31 | NumberField, |
| 32 | NumberFieldDecrement, |
| 33 | NumberFieldGroup, |
| 34 | NumberFieldIncrement, |
| 35 | NumberFieldInput, |
| 36 | } from "../ui/number-field"; |
| 37 | import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout"; |
| 38 | import { DatabaseStorageNotice } from "./DatabaseStorageNotice"; |
| 39 | import { AdvancedSettings } from "./AdvancedSettings"; |
| 40 | import { FoldedSettingsSection } from "./FoldedSettingsSection"; |
| 41 | import { SettingsScopeNotice } from "./SettingsScopeNotice"; |
| 42 | import { SettingsGroup } from "./SettingsGroup"; |
| 43 | import type { ScopedSettingsTarget } from "./scopedSettings"; |
| 44 | import { useSettingsScope } from "./SettingsScopeContext"; |
| 45 | import { useSearchableSetting } from "./settingsSearch"; |
| 46 | import { |
| 47 | useClearScopedSettings, |
| 48 | useScopedSettings, |
| 49 | useScopedSettingsMixed, |
| 50 | useUpdateScopedSettings, |
| 51 | } from "./useScopedSettings"; |
| 52 | import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis"; |
| 53 | |
| 54 | export function WorktreesDirectoryRow() { |
| 55 | const setting = useSearchableSetting(); |
| 56 | const gt = useGT(); |
| 57 | const { connectedEnvironments, targets } = useSettingsScope(); |
| 58 | const settings = useScopedSettings(); |
| 59 | const updateSettings = useUpdateScopedSettings(); |
| 60 | const mixed = useScopedSettingsMixed(["worktreesDirectory"]); |
| 61 | const edited = useRef(false); |
| 62 | const draft = useRef(""); |
| 63 | if ( |
| 64 | connectedEnvironments.some( |
| 65 | (environment) => |
| 66 | environment.serverConfig?.environment.capabilities.worktreesDirectory !== true, |
| 67 | ) |
| 68 | ) |
| 69 | return null; |
| 70 | const scopeKey = targets.map((target) => target.environmentId).join(","); |
| 71 | |
| 72 | return ( |
| 73 | <SettingsRow |
| 74 | {...setting("storage-worktrees-location")} |
| 75 | description={gt( |
| 76 | "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.", |
| 77 | )} |
| 78 | serverScoped |
| 79 | settingKeys={["worktreesDirectory"]} |
| 80 | resetAction={ |
| 81 | mixed || settings.worktreesDirectory !== "" ? ( |
| 82 | <SettingResetButton |
| 83 | ariaLabel={gt("Reset worktree location to default")} |
| 84 | onClick={() => updateSettings({ worktreesDirectory: "" })} |
| 85 | /> |
| 86 | ) : null |
| 87 | } |
| 88 | control={ |
| 89 | <Input |
| 90 | key={`${scopeKey}:${mixed}:${settings.worktreesDirectory}`} |
| 91 | aria-label={gt("Worktree location")} |
| 92 | autoCapitalize="none" |
| 93 | spellCheck={false} |
| 94 | placeholder={mixed ? gt("Mixed") : gt("Default")} |
| 95 | defaultValue={mixed ? "" : settings.worktreesDirectory} |
| 96 | onFocus={(event) => { |
| 97 | draft.current = event.target.value; |
| 98 | }} |
| 99 | onChange={(event) => { |
| 100 | edited.current = true; |
| 101 | draft.current = resolvePastedPath(draft.current, event.target.value); |
| 102 | event.target.value = draft.current; |
| 103 | }} |
| 104 | onBlur={(event) => { |
| 105 | const value = event.target.value.trim(); |
| 106 | if (edited.current && (mixed || value !== settings.worktreesDirectory)) |
| 107 | updateSettings({ worktreesDirectory: value }); |
| 108 | edited.current = false; |
| 109 | }} |
| 110 | /> |
| 111 | } |
| 112 | /> |
| 113 | ); |
| 114 | } |
| 115 | |
| 116 | type SaveOptions = Parameters<ReturnType<typeof useUpdateScopedSettings>>[1]; |
| 117 | |
| 118 | function RetentionControl({ |
| 119 | label, |
| 120 | value, |
| 121 | onChange, |
| 122 | minimum = 1, |
| 123 | }: { |
| 124 | label: string; |
| 125 | value: number | null; |
| 126 | onChange: (value: number | null, onFailed: () => void) => void; |
| 127 | minimum?: number; |
| 128 | }) { |
| 129 | const gt = useGT(); |
| 130 | const [draft, setDraft] = useState(value); |
| 131 | const [savedValue, setSavedValue] = useState(value); |
| 132 | // Saving an age can start a cleanup sweep, so turning a rule on only opens a draft. |
| 133 | // While its first save is in flight this holds that submission. |
| 134 | const [enabling, setEnabling] = useState<"draft" | "edited" | { days: number } | null>(null); |
| 135 | // Holds an age until Enter or focus leaves the row: one edited before focus moved to the |
| 136 | // switch, so switching off never saves it first, or one stepped toward a rule's first age, |
| 137 | // so raising it from 8 never saves a shorter age on the way. |
| 138 | const [held, setHeld] = useState(false); |
| 139 | // Hides a saved rule's age once it is switched off, so no blur can save it after null. |
| 140 | const [switchedOff, setSwitchedOff] = useState(false); |
| 141 | if (savedValue !== value) { |
| 142 | setSavedValue(value); |
| 143 | setDraft(value); |
| 144 | setEnabling(null); |
| 145 | setHeld(false); |
| 146 | setSwitchedOff(false); |
| 147 | } |
| 148 | const pending = typeof enabling === "object" ? enabling : null; |
| 149 | const on = (value !== null && !switchedOff) || enabling !== null; |
| 150 | const row = useRef<HTMLDivElement>(null); |
| 151 | |
| 152 | const commit = (next: number) => { |
| 153 | const days = Math.min(3650, Math.max(minimum, Math.round(next))); |
| 154 | setDraft(days); |
| 155 | setHeld(false); |
| 156 | if (days === pending?.days) return; |
| 157 | if (value !== null) { |
| 158 | onChange(days, () => {}); |
| 159 | return; |
| 160 | } |
| 161 | const submission = { days }; |
| 162 | setEnabling(submission); |
| 163 | onChange(days, () => setEnabling((current) => (current === submission ? null : current))); |
| 164 | }; |
| 165 | |
| 166 | const switchOff = () => { |
| 167 | setDraft(value); |
| 168 | setHeld(false); |
| 169 | setEnabling(null); |
| 170 | if (value === null && pending === null) return; |
| 171 | setSwitchedOff(true); |
| 172 | onChange(null, () => setSwitchedOff(false)); |
| 173 | }; |
| 174 | |
| 175 | return ( |
| 176 | <div |
| 177 | ref={row} |
| 178 | className="flex items-center gap-3" |
| 179 | onBlur={(event) => { |
| 180 | if (event.currentTarget.contains(event.relatedTarget)) return; |
| 181 | if (held && draft !== null) commit(draft); |
| 182 | else setEnabling((current) => (typeof current === "string" ? null : current)); |
| 183 | }} |
| 184 | > |
| 185 | {on ? ( |
| 186 | <NumberField |
| 187 | value={draft} |
| 188 | min={minimum} |
| 189 | max={3650} |
| 190 | step={1} |
| 191 | size="sm" |
| 192 | className="w-auto" |
| 193 | onValueChange={(next) => { |
| 194 | setDraft(next); |
| 195 | setEnabling((current) => (current === "draft" ? "edited" : current)); |
| 196 | }} |
| 197 | onValueCommitted={(next, { reason, event }) => { |
| 198 | if (next === null) setDraft(value); |
| 199 | else if ( |
| 200 | reason === "input-blur" |
| 201 | ? event instanceof FocusEvent && |
| 202 | event.relatedTarget instanceof Node && |
| 203 | row.current?.contains(event.relatedTarget) |
| 204 | : value === null |
| 205 | ) { |
| 206 | setDraft(next); |
| 207 | setHeld(true); |
| 208 | } else commit(next); |
| 209 | }} |
| 210 | > |
| 211 | <NumberFieldGroup> |
| 212 | <NumberFieldDecrement aria-label={gt("Decrease {label}", { label })} /> |
| 213 | <NumberFieldInput |
| 214 | aria-label={gt("{label} in days", { label })} |
| 215 | autoFocus={value === null} |
| 216 | size={5} |
| 217 | className="w-auto grow-0 text-right" |
| 218 | // Any typed or pasted edit replaces a held age: NumberField commits it on blur itself, |
| 219 | // and text it cannot parse yet must not leave the held age to be saved. |
| 220 | onChange={() => setHeld(false)} |
| 221 | onPaste={() => setHeld(false)} |
| 222 | onKeyDown={(event) => { |
| 223 | if (event.nativeEvent.isComposing || event.keyCode === 229) return; |
| 224 | if (event.key === "Enter") { |
| 225 | // Blurring lets NumberField parse the visible text and commit it once. It |
| 226 | // skips an unedited value, so an untouched draft is committed here. |
| 227 | const input = event.currentTarget; |
| 228 | const shown = |
| 229 | draft !== null && input.value === new Intl.NumberFormat().format(draft); |
| 230 | if (enabling === "draft" && shown) commit(draft); |
| 231 | input.blur(); |
| 232 | } else if (event.key === "Escape" && (held || typeof enabling === "string")) { |
| 233 | // An unhandled Escape closes the settings page. |
| 234 | event.preventDefault(); |
| 235 | event.stopPropagation(); |
| 236 | setDraft(pending?.days ?? value); |
| 237 | setHeld(false); |
| 238 | setEnabling((current) => (typeof current === "string" ? null : current)); |
| 239 | } |
| 240 | }} |
| 241 | /> |
| 242 | <span aria-hidden="true" className="self-center pr-2 text-xs"> |
| 243 | days |
| 244 | </span> |
| 245 | <NumberFieldIncrement aria-label={gt("Increase {label}", { label })} /> |
| 246 | </NumberFieldGroup> |
| 247 | </NumberField> |
| 248 | ) : ( |
| 249 | <span className="text-xs text-muted-foreground"> |
| 250 | <T>Off</T> |
| 251 | </span> |
| 252 | )} |
| 253 | <Switch |
| 254 | aria-label={label} |
| 255 | checked={on} |
| 256 | // Keeps focus in the age field, so switching off never commits an edited age first. |
| 257 | onMouseDown={(event) => event.preventDefault()} |
| 258 | onCheckedChange={(enabled) => { |
| 259 | if (enabled) { |
| 260 | setDraft(8); |
| 261 | setEnabling("draft"); |
| 262 | } else switchOff(); |
| 263 | }} |
| 264 | /> |
| 265 | </div> |
| 266 | ); |
| 267 | } |
| 268 | |
| 269 | const KEEP_WHEN_LABELS = { |
| 270 | "any-local-files": msg("Any local files"), |
| 271 | "uncommitted-changes": msg("Uncommitted changes"), |
| 272 | "tracked-changes": msg("Edited tracked files"), |
| 273 | } as const; |
| 274 | |
| 275 | function lastRunSummary( |
| 276 | entries: readonly { readonly label: string; readonly counts: string }[], |
| 277 | machineCount: number, |
| 278 | resolve: MessageResolver = m, |
| 279 | ) { |
| 280 | const first = entries[0]; |
| 281 | if (!first) return ""; |
| 282 | if (machineCount <= 1) return first.counts; |
| 283 | if (entries.length === machineCount && entries.every((entry) => entry.counts === first.counts)) { |
| 284 | return resolve(msg("{counts} on every machine", { counts: first.counts })); |
| 285 | } |
| 286 | return entries.map((entry) => `${entry.label}: ${entry.counts}`).join(" · "); |
| 287 | } |
| 288 | |
| 289 | function CleanupResults({ |
| 290 | report, |
| 291 | environmentLabel, |
| 292 | }: { |
| 293 | report: StorageCleanupReport; |
| 294 | environmentLabel: string; |
| 295 | }) { |
| 296 | const gt = useGT(); |
| 297 | return ( |
| 298 | <> |
| 299 | {report.entries.map((entry, index) => { |
| 300 | const name = |
| 301 | entry.kind === "worktree" |
| 302 | ? ((entry.threadId === null |
| 303 | ? entry.path |
| 304 | : entry.path?.split(/[\\/]/).findLast(Boolean)) ?? gt("Worktrees")) |
| 305 | : entry.kind === "logs" |
| 306 | ? gt("Rotated logs") |
| 307 | : gt("Browser artifacts"); |
| 308 | return ( |
| 309 | <SettingsRow |
| 310 | key={`${entry.path ?? entry.kind}:${entry.threadId ?? index}`} |
| 311 | title={<span className="wrap-anywhere select-text">{name}</span>} |
| 312 | description={ |
| 313 | <span className="block space-y-2 wrap-anywhere select-text"> |
| 314 | <span className={`block ${entry.outcome === "failed" ? "text-destructive" : ""}`}> |
| 315 | {entry.reason} |
| 316 | </span> |
| 317 | <span className="grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 border-l border-border/60 pl-3"> |
| 318 | <span> |
| 319 | <T>Machine</T> |
| 320 | </span> |
| 321 | <span className="text-foreground/80">{environmentLabel}</span> |
| 322 | {entry.projectPath && ( |
| 323 | <> |
| 324 | <span> |
| 325 | <T>Project</T> |
| 326 | </span> |
| 327 | <code className="text-foreground/80">{entry.projectPath}</code> |
| 328 | </> |
| 329 | )} |
| 330 | {entry.path && ( |
| 331 | <> |
| 332 | <span> |
| 333 | <T>Folder</T> |
| 334 | </span> |
| 335 | <code className="text-foreground/80">{entry.path}</code> |
| 336 | </> |
| 337 | )} |
| 338 | {entry.threadTitle && ( |
| 339 | <> |
| 340 | <span> |
| 341 | <T>Thread</T> |
| 342 | </span> |
| 343 | <span>{entry.threadTitle}</span> |
| 344 | </> |
| 345 | )} |
| 346 | </span> |
| 347 | </span> |
| 348 | } |
| 349 | control={ |
| 350 | (entry.outcome === "removed" || |
| 351 | (entry.outcome === "kept" && entry.bytes !== null)) && ( |
| 352 | <span className="text-xs text-muted-foreground"> |
| 353 | {[ |
| 354 | entry.kind !== "worktree" && entry.files !== null |
| 355 | ? gt("{count, plural, one {{formatted} file} other {{formatted} files}}", { |
| 356 | count: entry.files, |
| 357 | formatted: entry.files.toLocaleString(), |
| 358 | }) |
| 359 | : null, |
| 360 | entry.bytes !== null ? formatBytes(entry.bytes) : null, |
| 361 | ] |
| 362 | .filter(Boolean) |
| 363 | .join(" · ")} |
| 364 | </span> |
| 365 | ) |
| 366 | } |
| 367 | /> |
| 368 | ); |
| 369 | })} |
| 370 | {report.omittedCount > 0 && ( |
| 371 | <p className="px-3 py-2.5 text-xs text-muted-foreground sm:px-4"> |
| 372 | {gt( |
| 373 | "{omitted, plural, one {{environment}: {count} more results.} other {{environment}: {count} more results.}}", |
| 374 | { |
| 375 | omitted: report.omittedCount, |
| 376 | environment: environmentLabel, |
| 377 | count: report.omittedCount.toLocaleString(), |
| 378 | }, |
| 379 | )} |
| 380 | </p> |
| 381 | )} |
| 382 | {report.entries.length === 0 && report.omittedCount === 0 && ( |
| 383 | <p className="px-3 py-2.5 text-xs text-muted-foreground sm:px-4"> |
| 384 | <T> |
| 385 | <Var>{environmentLabel}</Var>: Nothing needed cleanup. |
| 386 | </T> |
| 387 | </p> |
| 388 | )} |
| 389 | </> |
| 390 | ); |
| 391 | } |
| 392 | |
| 393 | const storageCleanupReportsAtom = environmentAtomList( |
| 394 | "web-storage-cleanup-reports", |
| 395 | (environmentId) => serverEnvironment.storageCleanupReport({ environmentId, input: {} }), |
| 396 | ); |
| 397 | const storageCleanupPermissionsAtom = environmentAtomList( |
| 398 | "web-storage-cleanup-permissions", |
| 399 | serverEnvironment.runStorageCleanup.permissionAtom, |
| 400 | ); |
| 401 | |
| 402 | function CleanupSection() { |
| 403 | const messages = useMessages(); |
| 404 | const setting = useSearchableSetting(); |
| 405 | const gt = useGT(); |
| 406 | const nowMinute = useNowMinute(); |
| 407 | const nowMs = Date.parse(`${nowMinute}:00.000Z`); |
| 408 | const { connectedEnvironments } = useSettingsScope(); |
| 409 | const [pending, setPending] = useState(false); |
| 410 | const run = useAtomCommand(serverEnvironment.runStorageCleanup); |
| 411 | const supported = connectedEnvironments.filter( |
| 412 | (environment) => environment.serverConfig?.environment.capabilities.storageCleanupRun === true, |
| 413 | ); |
| 414 | const supportedIds = supported.map(({ environmentId }) => environmentId); |
| 415 | const reports = useAtomValue(storageCleanupReportsAtom(environmentIdsKey(supportedIds))); |
| 416 | const permissions = useAtomValue(storageCleanupPermissionsAtom(environmentIdsKey(supportedIds))); |
| 417 | const state = supportedIds.map((environmentId, index) => { |
| 418 | const query = reports[index]!; |
| 419 | return { |
| 420 | environmentId, |
| 421 | allowed: permissions[index]!, |
| 422 | report: query._tag === "Success" ? query.value : null, |
| 423 | loading: query.waiting, |
| 424 | failed: query._tag === "Failure", |
| 425 | }; |
| 426 | }); |
| 427 | const hasRules = supported.some((environment) => { |
| 428 | const settings = environment.serverConfig?.settings; |
| 429 | if (!settings) return false; |
| 430 | const enabled = (rules: WorktreeCleanupRules) => |
| 431 | rules.worktreeAfterDays !== null || |
| 432 | rules.worktreeSettledAfterDays !== null || |
| 433 | rules.worktreeOnMerge || |
| 434 | rules.worktreeOnDelete || |
| 435 | rules.worktreeUnchanged; |
| 436 | return ( |
| 437 | settings.storageCleanup.browserArtifactsAfterDays !== null || |
| 438 | settings.storageCleanup.logsAfterDays !== null || |
| 439 | enabled(resolveWorktreeCleanup(settings, null)) || |
| 440 | Object.values(settings.projectSettingsOverrides).some( |
| 441 | (override) => |
| 442 | override.worktreeCleanup?.mode === "custom" && enabled(override.worktreeCleanup.rules), |
| 443 | ) |
| 444 | ); |
| 445 | }); |
| 446 | if (supported.length === 0) return null; |
| 447 | const summaries = supported.map((environment) => { |
| 448 | const query = state.find((entry) => entry.environmentId === environment.environmentId); |
| 449 | const report = query?.report ?? null; |
| 450 | return { |
| 451 | environment, |
| 452 | report, |
| 453 | label: settingsScopeEnvironmentLabel(environment, connectedEnvironments), |
| 454 | counts: report |
| 455 | ? report.counts.failed > 0 |
| 456 | ? gt("{removed} removed, {kept} kept, {failed} failed", report.counts) |
| 457 | : gt("{removed} removed, {kept} kept", report.counts) |
| 458 | : "", |
| 459 | description: report |
| 460 | ? report.counts.failed > 0 |
| 461 | ? gt( |
| 462 | "{count, plural, one {Last run {when}. {bytes} recovered. {count} item couldn't be removed.} other {Last run {when}. {bytes} recovered. {count} items couldn't be removed.}}", |
| 463 | { |
| 464 | count: report.counts.failed, |
| 465 | when: formatRelativeTimeLabel(report.finishedAt, nowMs, messages), |
| 466 | bytes: formatBytes(report.bytesFreed), |
| 467 | }, |
| 468 | ) |
| 469 | : gt("Last run {when}. {bytes} recovered.", { |
| 470 | when: formatRelativeTimeLabel(report.finishedAt, nowMs, messages), |
| 471 | bytes: formatBytes(report.bytesFreed), |
| 472 | }) |
| 473 | : query?.failed |
| 474 | ? gt("Could not load the last run.") |
| 475 | : query?.loading |
| 476 | ? gt("Loading last run…") |
| 477 | : gt("Cleanup hasn't run yet."), |
| 478 | }; |
| 479 | }); |
| 480 | const deleteNow = async () => { |
| 481 | if (pending) return; |
| 482 | setPending(true); |
| 483 | await Promise.all( |
| 484 | supported |
| 485 | .filter((environment) => |
| 486 | state.some((entry) => entry.environmentId === environment.environmentId && entry.allowed), |
| 487 | ) |
| 488 | .map(async (environment) => { |
| 489 | const result = await run({ environmentId: environment.environmentId, input: {} }); |
| 490 | if (result._tag === "Success") { |
| 491 | const failures = result.value.entries.filter((entry) => entry.outcome === "failed"); |
| 492 | if (failures.length > 0) |
| 493 | toastManager.add({ |
| 494 | type: "error", |
| 495 | title: gt("Cleanup failed on {label}", { label: environment.label }), |
| 496 | description: failures[0]!.reason, |
| 497 | }); |
| 498 | } else if (!isAtomCommandInterrupted(result)) { |
| 499 | toastManager.add({ |
| 500 | type: "error", |
| 501 | title: gt("Could not run cleanup on {label}", { label: environment.label }), |
| 502 | description: String(squashAtomCommandFailure(result)), |
| 503 | }); |
| 504 | } |
| 505 | }), |
| 506 | ).finally(() => setPending(false)); |
| 507 | }; |
| 508 | return ( |
| 509 | <SettingsSection id="storage-cleanup" title={gt("Cleanup")} variant="plain"> |
| 510 | <SettingsGroup> |
| 511 | <SettingsRow |
| 512 | {...setting("storage-delete-now")} |
| 513 | description={ |
| 514 | <span> |
| 515 | {!hasRules |
| 516 | ? gt("Turn on a cleanup rule to use this.") |
| 517 | : summaries.map(({ environment, label, description }) => ( |
| 518 | <span key={environment.environmentId} className="block"> |
| 519 | {supported.length > 1 ? `${label}: ` : ""} |
| 520 | {description} |
| 521 | </span> |
| 522 | ))} |
| 523 | </span> |
| 524 | } |
| 525 | control={ |
| 526 | <Button |
| 527 | variant="outline" |
| 528 | size="sm" |
| 529 | disabled={pending || !hasRules || !state.some((entry) => entry.allowed)} |
| 530 | onClick={() => void deleteNow()} |
| 531 | > |
| 532 | {pending ? gt("Deleting…") : gt("Delete now")} |
| 533 | </Button> |
| 534 | } |
| 535 | /> |
| 536 | </SettingsGroup> |
| 537 | {summaries.some(({ report }) => report !== null) && ( |
| 538 | <FoldedSettingsSection |
| 539 | id="storage-cleanup-last-run" |
| 540 | title={gt("Last run")} |
| 541 | headerPlacement="inside" |
| 542 | summary={lastRunSummary( |
| 543 | summaries.filter(({ report }) => report !== null), |
| 544 | connectedEnvironments.length, |
| 545 | messages, |
| 546 | )} |
| 547 | > |
| 548 | {summaries.map( |
| 549 | ({ environment, label, report }) => |
| 550 | report && ( |
| 551 | <CleanupResults |
| 552 | key={environment.environmentId} |
| 553 | report={report} |
| 554 | environmentLabel={label} |
| 555 | /> |
| 556 | ), |
| 557 | )} |
| 558 | </FoldedSettingsSection> |
| 559 | )} |
| 560 | </SettingsSection> |
| 561 | ); |
| 562 | } |
| 563 | |
| 564 | function supportsStorageCleanup( |
| 565 | environments: ReadonlyArray<{ |
| 566 | readonly serverConfig: { |
| 567 | readonly environment: { readonly capabilities: { readonly storageCleanup?: boolean } }; |
| 568 | } | null; |
| 569 | }>, |
| 570 | ) { |
| 571 | return environments.every( |
| 572 | (environment) => environment.serverConfig?.environment.capabilities.storageCleanup === true, |
| 573 | ); |
| 574 | } |
| 575 | |
| 576 | /** Narrows a mixed selection to the machines that support cleanup. */ |
| 577 | function StorageCleanupScopeNotice() { |
| 578 | const gt = useGT(); |
| 579 | const { connectedEnvironments } = useSettingsScope(); |
| 580 | return ( |
| 581 | <SettingsScopeNotice |
| 582 | inline |
| 583 | target="environment" |
| 584 | eligibleEnvironmentIds={connectedEnvironments |
| 585 | .filter( |
| 586 | (environment) => |
| 587 | environment.serverConfig?.environment.capabilities.storageCleanup === true, |
| 588 | ) |
| 589 | .map((environment) => environment.environmentId)} |
| 590 | > |
| 591 | {gt( |
| 592 | "Update the selected environments to use storage cleanup, or choose a machine that supports it.", |
| 593 | )} |
| 594 | </SettingsScopeNotice> |
| 595 | ); |
| 596 | } |
| 597 | |
| 598 | export function WorktreeCleanupSection() { |
| 599 | const messages = useMessages(); |
| 600 | const setting = useSearchableSetting(); |
| 601 | const gt = useGT(); |
| 602 | const { scope, environments, connectedEnvironments, targets, target } = useSettingsScope(); |
| 603 | const scopedSettings = useScopedSettings(); |
| 604 | const isProjectScope = scope.kind === "project" || scope.kind === "checkout"; |
| 605 | const settings = { |
| 606 | ...scopedSettings.storageCleanup, |
| 607 | ...resolveWorktreeCleanup(scopedSettings, null), |
| 608 | }; |
| 609 | const projectMode = (entry: ScopedSettingsTarget | null) => |
| 610 | entry?.sources.worktreeCleanup === "project" |
| 611 | ? (entry.settings.worktreeCleanup?.mode ?? "inherit") |
| 612 | : "inherit"; |
| 613 | const mode = projectMode(target); |
| 614 | const mixedModes = targets.some((entry) => projectMode(entry) !== mode); |
| 615 | const updateSettings = useUpdateScopedSettings(); |
| 616 | const clearSettings = useClearScopedSettings(); |
| 617 | const ruleStatus = (key: keyof StorageCleanupSettings) => |
| 618 | targets.some( |
| 619 | (target) => |
| 620 | ({ ...target.settings.storageCleanup, ...resolveWorktreeCleanup(target.settings, null) })[ |
| 621 | key |
| 622 | ] !== settings[key], |
| 623 | ) |
| 624 | ? gt("Mixed across selected machines") |
| 625 | : undefined; |
| 626 | // A policy locks these through worktreeCleanup, which also reaches each project's own rules. |
| 627 | const lockablePath = (key: keyof WorktreeCleanupRules) => |
| 628 | isProjectScope ? ["worktreeCleanup"] : ["worktreeCleanup", `storageCleanup.${key}`]; |
| 629 | const update = (patch: Partial<StorageCleanupSettings>, options?: SaveOptions) => |
| 630 | updateSettings({ storageCleanup: patch }, options); |
| 631 | const updateWorktree = (patch: Partial<WorktreeCleanupRules>, options?: SaveOptions) => |
| 632 | isProjectScope |
| 633 | ? updateSettings({ worktreeCleanup: { mode: "custom", rules: patch } }, options) |
| 634 | : update(patch, options); |
| 635 | |
| 636 | if ( |
| 637 | isProjectScope && |
| 638 | connectedEnvironments.some( |
| 639 | (environment) => |
| 640 | environment.serverConfig?.environment.capabilities.projectWorktreeCleanup !== true, |
| 641 | ) |
| 642 | ) { |
| 643 | return ( |
| 644 | <SettingsSection id="storage-worktrees" title={gt("Cleanup")} variant="plain"> |
| 645 | <SettingsScopeNotice inline target="all"> |
| 646 | {gt("Update the selected machines to configure project worktree cleanup.")} |
| 647 | </SettingsScopeNotice> |
| 648 | </SettingsSection> |
| 649 | ); |
| 650 | } |
| 651 | if (!supportsStorageCleanup(connectedEnvironments)) { |
| 652 | return ( |
| 653 | <SettingsSection id="storage-worktrees" title={gt("Cleanup")} variant="plain"> |
| 654 | <StorageCleanupScopeNotice /> |
| 655 | </SettingsSection> |
| 656 | ); |
| 657 | } |
| 658 | |
| 659 | return ( |
| 660 | <SettingsSection id="storage-worktrees" title={gt("Cleanup")}> |
| 661 | <> |
| 662 | {isProjectScope && ( |
| 663 | <SettingsRow |
| 664 | title={gt("Automatic worktree cleanup")} |
| 665 | description={ |
| 666 | mode === "off" |
| 667 | ? gt("Keep this project's worktrees until you delete them manually.") |
| 668 | : mode === "custom" |
| 669 | ? gt("Use these rules for this project.") |
| 670 | : gt("Use each machine's worktree cleanup settings.") |
| 671 | } |
| 672 | serverScoped |
| 673 | settingKeys={["worktreeCleanup"]} |
| 674 | mixed={mixedModes} |
| 675 | control={ |
| 676 | <Select |
| 677 | value={mixedModes ? null : mode} |
| 678 | onValueChange={(next) => { |
| 679 | if (next === "inherit") clearSettings(["worktreeCleanup"]); |
| 680 | else if (next === "off") updateSettings({ worktreeCleanup: { mode: "off" } }); |
| 681 | else if (next === "custom") |
| 682 | updateSettings({ worktreeCleanup: { mode: "custom", rules: {} } }); |
| 683 | }} |
| 684 | > |
| 685 | <SelectTrigger size="sm" aria-label={gt("Automatic worktree cleanup")}> |
| 686 | <SelectValue> |
| 687 | {mixedModes |
| 688 | ? gt("Mixed") |
| 689 | : mode === "inherit" |
| 690 | ? gt("Inherit") |
| 691 | : mode === "off" |
| 692 | ? gt("Off") |
| 693 | : gt("Custom")} |
| 694 | </SelectValue> |
| 695 | </SelectTrigger> |
| 696 | <SelectPopup align="end" alignItemWithTrigger={false}> |
| 697 | <SelectItem value="inherit"> |
| 698 | <T>Inherit</T> |
| 699 | </SelectItem> |
| 700 | <SelectItem value="off"> |
| 701 | <T>Off</T> |
| 702 | </SelectItem> |
| 703 | <SelectItem value="custom"> |
| 704 | <T>Custom</T> |
| 705 | </SelectItem> |
| 706 | </SelectPopup> |
| 707 | </Select> |
| 708 | } |
| 709 | /> |
| 710 | )} |
| 711 | {(!isProjectScope || (!mixedModes && mode === "custom")) && ( |
| 712 | <> |
| 713 | <SettingsRow |
| 714 | title={gt("Delete worktrees with deleted threads")} |
| 715 | status={ruleStatus("worktreeOnDelete")} |
| 716 | managedPaths={lockablePath("worktreeOnDelete")} |
| 717 | description={gt( |
| 718 | "Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept.", |
| 719 | )} |
| 720 | serverScoped={!isProjectScope} |
| 721 | control={ |
| 722 | <Switch |
| 723 | aria-label={gt("Delete worktrees with deleted threads")} |
| 724 | checked={settings.worktreeOnDelete} |
| 725 | onCheckedChange={(worktreeOnDelete) => updateWorktree({ worktreeOnDelete })} |
| 726 | /> |
| 727 | } |
| 728 | /> |
| 729 | <SettingsRow |
| 730 | title={gt("Delete merged worktrees")} |
| 731 | status={ruleStatus("worktreeOnMerge")} |
| 732 | managedPaths={lockablePath("worktreeOnMerge")} |
| 733 | description={gt( |
| 734 | "Remove worktrees whose pull request is merged and whose commits are included in the default branch.", |
| 735 | )} |
| 736 | serverScoped={!isProjectScope} |
| 737 | control={ |
| 738 | <Switch |
| 739 | aria-label={gt("Delete merged worktrees")} |
| 740 | checked={settings.worktreeOnMerge} |
| 741 | onCheckedChange={(worktreeOnMerge) => updateWorktree({ worktreeOnMerge })} |
| 742 | /> |
| 743 | } |
| 744 | /> |
| 745 | <SettingsRow |
| 746 | title={gt("Delete inactive worktrees")} |
| 747 | status={ruleStatus("worktreeAfterDays")} |
| 748 | managedPaths={lockablePath("worktreeAfterDays")} |
| 749 | description={gt( |
| 750 | "Remove worktrees after their threads have been inactive for this many days. Branches and thread history are kept.", |
| 751 | )} |
| 752 | serverScoped={!isProjectScope} |
| 753 | control={ |
| 754 | <RetentionControl |
| 755 | label={gt("Delete inactive worktrees")} |
| 756 | value={settings.worktreeAfterDays} |
| 757 | onChange={(worktreeAfterDays, onFailed) => |
| 758 | updateWorktree({ worktreeAfterDays }, { onFailed }) |
| 759 | } |
| 760 | /> |
| 761 | } |
| 762 | /> |
| 763 | <AdvancedSettings |
| 764 | // The keep-when search result lands on this section, not its row. |
| 765 | targetIds={["storage-worktrees", setting("storage-worktree-keep-when").id]} |
| 766 | > |
| 767 | {connectedEnvironments.length > 0 && |
| 768 | connectedEnvironments.every( |
| 769 | (environment) => |
| 770 | environment.serverConfig?.environment.capabilities.settledWorktreeCleanup === |
| 771 | true, |
| 772 | ) && ( |
| 773 | <SettingsRow |
| 774 | title={gt("Delete settled worktrees")} |
| 775 | managedPaths={lockablePath("worktreeSettledAfterDays")} |
| 776 | status={[ |
| 777 | ruleStatus("worktreeSettledAfterDays"), |
| 778 | environments.length > connectedEnvironments.length |
| 779 | ? gt("Offline machines will not get this setting") |
| 780 | : undefined, |
| 781 | ] |
| 782 | .filter(Boolean) |
| 783 | .join(". ")} |
| 784 | description={gt( |
| 785 | "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.", |
| 786 | )} |
| 787 | serverScoped={!isProjectScope} |
| 788 | control={ |
| 789 | <RetentionControl |
| 790 | label={gt("Delete settled worktrees")} |
| 791 | value={settings.worktreeSettledAfterDays} |
| 792 | minimum={0} |
| 793 | onChange={(worktreeSettledAfterDays, onFailed) => |
| 794 | updateWorktree({ worktreeSettledAfterDays }, { onFailed }) |
| 795 | } |
| 796 | /> |
| 797 | } |
| 798 | /> |
| 799 | )} |
| 800 | <SettingsRow |
| 801 | title={gt("Delete unchanged worktrees")} |
| 802 | status={ruleStatus("worktreeUnchanged")} |
| 803 | managedPaths={lockablePath("worktreeUnchanged")} |
| 804 | description={gt("Remove worktrees with no commits beyond the default branch.")} |
| 805 | serverScoped={!isProjectScope} |
| 806 | control={ |
| 807 | <Switch |
| 808 | aria-label={gt("Delete unchanged worktrees")} |
| 809 | checked={settings.worktreeUnchanged} |
| 810 | onCheckedChange={(worktreeUnchanged) => updateWorktree({ worktreeUnchanged })} |
| 811 | /> |
| 812 | } |
| 813 | /> |
| 814 | {connectedEnvironments.every( |
| 815 | (environment) => |
| 816 | environment.serverConfig?.environment.capabilities.storageCleanupRun === true, |
| 817 | ) && ( |
| 818 | <SettingsRow |
| 819 | {...setting("storage-worktree-keep-when")} |
| 820 | status={ruleStatus("worktreeKeepWhen")} |
| 821 | managedPaths={lockablePath("worktreeKeepWhen")} |
| 822 | description={ |
| 823 | settings.worktreeKeepWhen === "any-local-files" |
| 824 | ? gt("Includes ignored files, except node_modules.") |
| 825 | : settings.worktreeKeepWhen === "tracked-changes" |
| 826 | ? gt("Deletes untracked and ignored files, including .env.") |
| 827 | : gt( |
| 828 | "Keeps edits and untracked files. Deletes ignored files, including .env.", |
| 829 | ) |
| 830 | } |
| 831 | serverScoped={!isProjectScope} |
| 832 | control={ |
| 833 | <Select |
| 834 | value={ruleStatus("worktreeKeepWhen") ? null : settings.worktreeKeepWhen} |
| 835 | onValueChange={(next) => { |
| 836 | if ( |
| 837 | next === "any-local-files" || |
| 838 | next === "uncommitted-changes" || |
| 839 | next === "tracked-changes" |
| 840 | ) |
| 841 | updateWorktree({ worktreeKeepWhen: next }); |
| 842 | }} |
| 843 | > |
| 844 | <SelectTrigger size="sm" aria-label={gt("Keep worktrees with local changes")}> |
| 845 | <SelectValue> |
| 846 | {ruleStatus("worktreeKeepWhen") |
| 847 | ? gt("Mixed") |
| 848 | : messages(KEEP_WHEN_LABELS[settings.worktreeKeepWhen])} |
| 849 | </SelectValue> |
| 850 | </SelectTrigger> |
| 851 | <SelectPopup align="end" alignItemWithTrigger={false}> |
| 852 | <SelectItem value="any-local-files"> |
| 853 | <T>Any local files</T> |
| 854 | </SelectItem> |
| 855 | <SelectItem value="uncommitted-changes"> |
| 856 | <T>Uncommitted changes</T> |
| 857 | </SelectItem> |
| 858 | <SelectItem value="tracked-changes"> |
| 859 | <T>Edited tracked files</T> |
| 860 | </SelectItem> |
| 861 | </SelectPopup> |
| 862 | </Select> |
| 863 | } |
| 864 | /> |
| 865 | )} |
| 866 | </AdvancedSettings> |
| 867 | </> |
| 868 | )} |
| 869 | </> |
| 870 | </SettingsSection> |
| 871 | ); |
| 872 | } |
| 873 | |
| 874 | /** Retention for logs and captures, and the manual cleanup run, which covers worktrees too. */ |
| 875 | export function StorageCleanupSections() { |
| 876 | const gt = useGT(); |
| 877 | const { scope, connectedEnvironments, targets } = useSettingsScope(); |
| 878 | const scopedSettings = useScopedSettings(); |
| 879 | const updateSettings = useUpdateScopedSettings(); |
| 880 | const settings = scopedSettings.storageCleanup; |
| 881 | const targetIdsKey = environmentIdsKey(targets.map((target) => target.environmentId).sort()); |
| 882 | const artifactsMixed = |
| 883 | targets.length > 1 && |
| 884 | targets.some( |
| 885 | (target) => |
| 886 | target.settings.storageCleanup.browserArtifactsAfterDays !== |
| 887 | settings.browserArtifactsAfterDays, |
| 888 | ); |
| 889 | const logsMixed = |
| 890 | targets.length > 1 && |
| 891 | targets.some( |
| 892 | (target) => target.settings.storageCleanup.logsAfterDays !== settings.logsAfterDays, |
| 893 | ); |
| 894 | const settledArtifactsStatus = useDebouncedValue(`${targetIdsKey}:${artifactsMixed}`, 300); |
| 895 | const settledLogsStatus = useDebouncedValue(`${targetIdsKey}:${logsMixed}`, 300); |
| 896 | const artifactsStatus = |
| 897 | targets.length > 1 && settledArtifactsStatus === `${targetIdsKey}:true` |
| 898 | ? gt("Mixed across selected machines") |
| 899 | : undefined; |
| 900 | const logsStatus = |
| 901 | targets.length > 1 && settledLogsStatus === `${targetIdsKey}:true` |
| 902 | ? gt("Mixed across selected machines") |
| 903 | : undefined; |
| 904 | if (scope.kind === "project" || scope.kind === "checkout") return null; |
| 905 | const update = (patch: Partial<StorageCleanupSettings>, options: SaveOptions) => |
| 906 | updateSettings({ storageCleanup: patch }, options); |
| 907 | const databaseStorageNotice = ( |
| 908 | <DatabaseStorageNotice |
| 909 | environments={connectedEnvironments.filter( |
| 910 | (environment) => |
| 911 | environment.serverConfig?.environment.capabilities.databaseStorage === true, |
| 912 | )} |
| 913 | /> |
| 914 | ); |
| 915 | if (!supportsStorageCleanup(connectedEnvironments)) { |
| 916 | return ( |
| 917 | <> |
| 918 | {databaseStorageNotice} |
| 919 | <SettingsSection id="storage-artifacts" title={gt("Artifacts and logs")} variant="plain"> |
| 920 | <StorageCleanupScopeNotice /> |
| 921 | </SettingsSection> |
| 922 | </> |
| 923 | ); |
| 924 | } |
| 925 | |
| 926 | return ( |
| 927 | <> |
| 928 | {databaseStorageNotice} |
| 929 | <SettingsSection id="storage-artifacts" title={gt("Artifacts and logs")}> |
| 930 | <AnimatedHeight> |
| 931 | <SettingsRow |
| 932 | title={gt("Delete old browser artifacts")} |
| 933 | status={artifactsStatus} |
| 934 | managedPaths={["storageCleanup.browserArtifactsAfterDays"]} |
| 935 | description={gt( |
| 936 | "Delete saved browser captures after this many days. Older capture links will no longer open.", |
| 937 | )} |
| 938 | serverScoped |
| 939 | control={ |
| 940 | <RetentionControl |
| 941 | label={gt("Delete old browser artifacts")} |
| 942 | value={settings.browserArtifactsAfterDays} |
| 943 | onChange={(browserArtifactsAfterDays, onFailed) => |
| 944 | update({ browserArtifactsAfterDays }, { onFailed }) |
| 945 | } |
| 946 | /> |
| 947 | } |
| 948 | /> |
| 949 | </AnimatedHeight> |
| 950 | <AnimatedHeight> |
| 951 | <SettingsRow |
| 952 | title={gt("Delete old rotated logs")} |
| 953 | status={logsStatus} |
| 954 | managedPaths={["storageCleanup.logsAfterDays"]} |
| 955 | description={gt( |
| 956 | "Delete inactive rotated log files after this many days. Current logs are kept.", |
| 957 | )} |
| 958 | serverScoped |
| 959 | control={ |
| 960 | <RetentionControl |
| 961 | label={gt("Delete old rotated logs")} |
| 962 | value={settings.logsAfterDays} |
| 963 | onChange={(logsAfterDays, onFailed) => update({ logsAfterDays }, { onFailed })} |
| 964 | /> |
| 965 | } |
| 966 | /> |
| 967 | </AnimatedHeight> |
| 968 | </SettingsSection> |
| 969 | <CleanupSection /> |
| 970 | </> |
| 971 | ); |
| 972 | } |