From 2c71e4ad315ffd7df625aa732f06e9af907b3f16 Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:07:50 -0800 Subject: [PATCH] feat(workspace-cleanup): split settings into Manual and Automatic cleanup sections Manual cleanup gets its own section with a Review workspaces button. The rules section is headed Automatic cleanup with an On/Off pill, a status line and Run rules now (only while a rule is on). Turning a rule on shows its check in the switch and under the rule, with an inline Try again when the check fails. --- .../SettingsGroupDisclosure.tsx | 21 +- .../WorkspaceCleanupSettingsPane.test.tsx | 218 ++++++++++++- .../WorkspaceCleanupSettingsPane.tsx | 303 ++++++++---------- .../use-workspace-cleanup-rule-focus.ts | 58 ++++ .../workspace-cleanup-activity-section.tsx | 38 +++ ...> workspace-cleanup-automatic-section.tsx} | 128 +++++--- .../workspace-cleanup-manual-section.tsx | 36 +++ .../workspace-cleanup-preview-matches.ts | 50 +++ .../workspace-cleanup-protection-section.tsx | 40 +++ .../workspace-cleanup-rule-change-dialog.tsx | 6 +- .../workspace-cleanup-rule-rows.tsx | 187 ++++++++--- .../workspace-cleanup-settings-search.ts | 27 +- src/renderer/src/components/ui/switch.tsx | 7 +- src/renderer/src/i18n/locales/en.json | 37 ++- 14 files changed, 861 insertions(+), 295 deletions(-) create mode 100644 src/renderer/src/components/settings/workspace-cleanup/use-workspace-cleanup-rule-focus.ts create mode 100644 src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-activity-section.tsx rename src/renderer/src/components/settings/workspace-cleanup/{workspace-cleanup-settings-status.tsx => workspace-cleanup-automatic-section.tsx} (50%) create mode 100644 src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-manual-section.tsx create mode 100644 src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-preview-matches.ts create mode 100644 src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-protection-section.tsx diff --git a/src/renderer/src/components/settings/section-layout/SettingsGroupDisclosure.tsx b/src/renderer/src/components/settings/section-layout/SettingsGroupDisclosure.tsx index 5b5e2c433b6..cccf4948426 100644 --- a/src/renderer/src/components/settings/section-layout/SettingsGroupDisclosure.tsx +++ b/src/renderer/src/components/settings/section-layout/SettingsGroupDisclosure.tsx @@ -13,6 +13,11 @@ type SettingsGroupDisclosureProps = { /** A muted line under the label, for a disclosure that stands as a card row of its own. */ summary?: React.ReactNode forceOpen?: boolean + /** Owns the open state when set; a click or a settings jump reports through onOpenChange. */ + open?: boolean + onOpenChange?: (open: boolean) => void + /** Lines its rows up with the card's other rows instead of one step in. */ + flush?: boolean children: React.ReactNode } @@ -22,10 +27,20 @@ export function SettingsGroupDisclosure({ description, summary, forceOpen = false, + open: controlledOpen, + onOpenChange, + flush = false, children }: SettingsGroupDisclosureProps): React.JSX.Element { const t = useTranslate() - const [open, setOpen] = useState(false) + const [ownOpen, setOwnOpen] = useState(false) + const open = controlledOpen ?? ownOpen + const setOpen = (next: boolean): void => { + if (controlledOpen === undefined) { + setOwnOpen(next) + } + onOpenChange?.(next) + } const expanded = open || forceOpen const revealRef = useSettingsTargetReveal(() => setOpen(true)) @@ -34,7 +49,7 @@ export function SettingsGroupDisclosure({ {/* Stays mounted while collapsed so a settings jump can find and reveal its rows. */} - diff --git a/src/renderer/src/components/settings/workspace-cleanup/WorkspaceCleanupSettingsPane.test.tsx b/src/renderer/src/components/settings/workspace-cleanup/WorkspaceCleanupSettingsPane.test.tsx index 920f2fcba8b..6281586196a 100644 --- a/src/renderer/src/components/settings/workspace-cleanup/WorkspaceCleanupSettingsPane.test.tsx +++ b/src/renderer/src/components/settings/workspace-cleanup/WorkspaceCleanupSettingsPane.test.tsx @@ -1,17 +1,51 @@ // @vitest-environment happy-dom import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { getDefaultSettings } from '../../../../../shared/orca-profiles/constants' import { getDefaultWorkspaceCleanupRules, type WorkspaceCleanupRules } from '../../../../../shared/workspace-cleanup/workspace-cleanup-policy' import type { WorkspaceCleanupPreviewRow } from '../../../../../shared/workspace-cleanup/workspace-cleanup-run' +import type { RuntimeClientTarget } from '../../../../../shared/remote-runtime/host-catalog/runtime-client-target' import { useAppStore } from '@/store' import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture' import { TooltipProvider } from '../../ui/tooltip' +import type * as RuntimeRpcCall from '@/runtime/rpc/calls/runtime-rpc-call' import { WorkspaceCleanupSettingsPane } from './WorkspaceCleanupSettingsPane' +const environmentCall = vi.hoisted(() => ({ + settingsGetFails: false, + rules: null as WorkspaceCleanupRules | null +})) + +// A remote host's calls skip the pairing transport; local calls use window.api as the app does. +vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + callRuntimeRpc: async ( + target: RuntimeClientTarget, + method: string, + params?: unknown, + options?: Parameters[3] + ) => { + if (target.kind !== 'environment') { + return actual.callRuntimeRpc(target, method, params, options) + } + if (method === 'settings.get') { + if (environmentCall.settingsGetFails) { + throw new Error('Host unreachable') + } + return { settings: { workspaceCleanupPolicy: environmentCall.rules } } + } + return method === 'workspaceCleanup.report' + ? { runs: [], running: false, nextRunAt: null } + : { evaluatedAt: 0, rows: [] } + } + } +}) + const row: WorkspaceCleanupPreviewRow = { worktreeId: 'preview::/preview/landing', repoId: 'preview', @@ -23,33 +57,40 @@ const row: WorkspaceCleanupPreviewRow = { } let failPreview = false let includeCandidate = false +let matchWhenMergedOn = false +let previewGate: Promise | null = null +let saveGate: Promise | null = null -function Pane() { +const LOCAL_TARGET: RuntimeClientTarget = { kind: 'local' } + +function Pane({ target = LOCAL_TARGET }: { target?: RuntimeClientTarget }) { const settings = useAppStore((state) => state.settings) return ( + updateSettings={async (updates) => { + await saveGate useAppStore.setState((state) => ({ settings: { ...state.settings!, ...updates } })) - } + }} /> ) } -function mount(enabled = false) { +function mount(enabled = false, target?: RuntimeClientTarget) { const settings = getDefaultSettings('/preview') settings.workspaceCleanupPolicy = { ...getDefaultWorkspaceCleanupRules(), inactive: { enabled, afterDays: 30, action: 'delete' } } + environmentCall.rules = settings.workspaceCleanupPolicy useAppStore.setState({ settings, worktreesByRepo: { preview: [makeWorktree({ id: row.worktreeId, repoId: 'preview', isPinned: false })] } }) - render(, { wrapper: TooltipProvider }) + render(, { wrapper: TooltipProvider }) } function protection() { @@ -58,6 +99,19 @@ function protection() { function confirm() { return screen.getByRole('button', { name: 'Turn off protection' }) } +// getByRole skips hidden elements, so finding a switch also proves it is shown. +function merged() { + return screen.getByRole('switch', { name: 'Delete merged workspaces' }) +} +function workers() { + return screen.getByRole('switch', { name: 'Delete released orchestration worker workspaces' }) +} +function tryAgain() { + return screen.getByRole('button', { name: 'Try again' }) +} +function search(query: string) { + act(() => useAppStore.setState({ settingsSearchQuery: query })) +} function savedRules() { const rules = useAppStore.getState().settings?.workspaceCleanupPolicy if (!rules) { @@ -69,6 +123,10 @@ function savedRules() { beforeEach(() => { failPreview = false includeCandidate = false + matchWhenMergedOn = false + previewGate = null + saveGate = null + environmentCall.settingsGetFails = false useAppStore.setState(useAppStore.getInitialState(), true) Object.assign(window, { api: { @@ -81,19 +139,22 @@ beforeEach(() => { method: string params?: { rules?: WorkspaceCleanupRules } }) => { - if (method === 'workspaceCleanup.preview' && failPreview) { - throw new Error('Preview unavailable') + if (method === 'workspaceCleanup.preview') { + await previewGate + if (failPreview) { + throw new Error('Preview unavailable') + } } + const candidate = + (includeCandidate && params?.rules?.keepWhen === 'uncommitted') || + (matchWhenMergedOn && params?.rules?.merged.enabled === true) return { id: 'preview', ok: true, result: method === 'workspaceCleanup.report' ? { runs: [], running: false, nextRunAt: null } - : { - evaluatedAt: 0, - rows: includeCandidate && params?.rules?.keepWhen === 'uncommitted' ? [row] : [] - } + : { evaluatedAt: 0, rows: candidate ? [row] : [] } } } } @@ -178,3 +239,134 @@ describe('cleanup protection consent', () => { expect(screen.queryByRole('dialog')).toBeNull() }) }) + +describe('turning a rule on', () => { + it('keeps the rule pending through its check and save while other rules stay focusable but held', async () => { + let releasePreview = (): void => {} + previewGate = new Promise((resolve) => (releasePreview = resolve)) + let releaseSave = (): void => {} + saveGate = new Promise((resolve) => (releaseSave = resolve)) + mount() + await act(async () => { + fireEvent.click(merged()) + }) + expect(screen.getByRole('status')).toBeTruthy() + expect(merged().getAttribute('aria-busy')).toBe('true') + expect(merged().getAttribute('aria-checked')).toBe('false') + const unchanged = screen.getByRole('switch', { name: 'Delete unchanged workspaces' }) + expect(unchanged.getAttribute('aria-disabled')).toBe('true') + expect(unchanged.hasAttribute('disabled')).toBe(false) + await act(async () => { + fireEvent.click(unchanged) + }) + + await act(async () => { + releasePreview() + }) + expect(screen.queryByRole('status')).toBeNull() + expect(merged().getAttribute('aria-busy')).toBe('true') + expect(merged().getAttribute('aria-checked')).toBe('false') + + await act(async () => { + releaseSave() + }) + await waitFor(() => expect(merged().getAttribute('aria-checked')).toBe('true')) + expect(merged().hasAttribute('aria-busy')).toBe(false) + expect(savedRules().unchanged.enabled).toBe(false) + }) + + it('shows a failed check under the rule and saves it on Try again with focus kept', async () => { + failPreview = true + mount() + merged().focus() + await act(async () => { + fireEvent.click(merged()) + }) + expect(screen.getByRole('alert')).toBeTruthy() + expect(merged().getAttribute('aria-describedby')).toBe(screen.getByRole('alert').id) + expect(savedRules().merged.enabled).toBe(false) + expect(document.activeElement).toBe(merged()) + + failPreview = false + await act(async () => { + fireEvent.click(tryAgain()) + }) + await waitFor(() => expect(savedRules().merged.enabled).toBe(true)) + expect(screen.queryByRole('alert')).toBeNull() + expect(document.activeElement).toBe(merged()) + }) + + it('keeps an Advanced rule shown and focused when its retry succeeds after search moves on', async () => { + failPreview = true + mount() + search('orchestration') + workers().focus() + await act(async () => { + fireEvent.click(workers()) + }) + expect(screen.getByRole('alert')).toBeTruthy() + // A status-only search unmounts the rules; clearing it brings them back with the failure. + search('Run rules now') + expect(screen.queryAllByRole('switch')).toHaveLength(0) + search('') + + failPreview = false + await act(async () => { + fireEvent.click(tryAgain()) + }) + await waitFor(() => expect(workers().getAttribute('aria-checked')).toBe('true')) + expect(savedRules().orchestrationWorkers.enabled).toBe(true) + expect(document.activeElement).toBe(workers()) + }) + + it('returns focus to the rule when the confirmation a retry opened is cancelled', async () => { + failPreview = true + mount() + merged().focus() + await act(async () => { + fireEvent.click(merged()) + }) + failPreview = false + matchWhenMergedOn = true + await act(async () => { + fireEvent.click(tryAgain()) + }) + expect(await screen.findByRole('dialog')).toBeTruthy() + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + }) + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()) + await waitFor(() => expect(document.activeElement).toBe(merged())) + expect(savedRules().merged.enabled).toBe(false) + expect(merged().getAttribute('aria-checked')).toBe('false') + }) + + it("shows the host's load error when its rules can't be read during a change", async () => { + mount(false, { kind: 'environment', environmentId: 'env-1' }) + const rule = await screen.findByRole('switch', { name: 'Delete merged workspaces' }) + environmentCall.settingsGetFails = true + await act(async () => { + fireEvent.click(rule) + }) + expect(screen.queryAllByRole('switch')).toHaveLength(0) + + environmentCall.settingsGetFails = false + await act(async () => { + fireEvent.click(tryAgain()) + }) + const reloaded = await screen.findByRole('switch', { name: 'Delete merged workspaces' }) + expect(reloaded.getAttribute('aria-checked')).toBe('false') + expect(reloaded.hasAttribute('aria-busy')).toBe(false) + expect(screen.queryByRole('alert')).toBeNull() + }) +}) + +describe('automatic cleanup search', () => { + it('shows the heading and Run rules now without the rules for a status-only search', () => { + mount(true) + search('Run rules now') + expect(screen.getByRole('button', { name: 'Run rules now' })).toBeTruthy() + expect(screen.queryAllByRole('switch')).toHaveLength(0) + expect(screen.queryByRole('button', { name: /Advanced/ })).toBeNull() + }) +}) diff --git a/src/renderer/src/components/settings/workspace-cleanup/WorkspaceCleanupSettingsPane.tsx b/src/renderer/src/components/settings/workspace-cleanup/WorkspaceCleanupSettingsPane.tsx index 29219b3f167..6af913e07c2 100644 --- a/src/renderer/src/components/settings/workspace-cleanup/WorkspaceCleanupSettingsPane.tsx +++ b/src/renderer/src/components/settings/workspace-cleanup/WorkspaceCleanupSettingsPane.tsx @@ -8,7 +8,6 @@ import type { GlobalSettings } from '../../../../../shared/settings/global-setti import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host/execution-host' import { errorMessage } from '../../../../../shared/errors/error-message' import { - WORKSPACE_CLEANUP_RULE_KEYS, hasEnabledWorkspaceCleanupRule, type WorkspaceCleanupRules } from '../../../../../shared/workspace-cleanup/workspace-cleanup-policy' @@ -16,21 +15,21 @@ import type { WorkspaceCleanupPreview, WorkspaceCleanupPreviewRow } from '../../../../../shared/workspace-cleanup/workspace-cleanup-run' -import { SettingsSwitchRow } from '../form-controls/SettingsFormControls' -import { SettingsGroup } from '../section-layout/SettingsGroup' -import { SearchableSetting } from '../section-layout/SearchableSetting' import { matchesSettingsSearch } from '../search/settings-search' import { SettingsHostScopeUnavailableNotice } from '../host-scope/SettingsHostScopePicker' import type { SettingsHostScope } from '../host-scope/settings-host-scope' import { useWorkspaceCleanupHostRules } from './use-workspace-cleanup-host-rules' import { useWorkspaceCleanupHostActivity } from './use-workspace-cleanup-host-activity' -import { WorkspaceCleanupSettingsStatus } from './workspace-cleanup-settings-status' +import { WorkspaceCleanupAutomaticSection } from './workspace-cleanup-automatic-section' +import { WorkspaceCleanupManualSection } from './workspace-cleanup-manual-section' +import { WorkspaceCleanupActivitySection } from './workspace-cleanup-activity-section' +import { WorkspaceCleanupProtectionSection } from './workspace-cleanup-protection-section' +import { newRemovals, summarizeMatches } from './workspace-cleanup-preview-matches' import { WorkspaceCleanupRuleRows, - type WorkspaceCleanupRuleMatches + type WorkspaceCleanupRulePhase } from './workspace-cleanup-rule-rows' import { - WORKSPACE_CLEANUP_RULE_REASON, setWorkspaceCleanupRuleEnabled, type WorkspaceCleanupRuleKey } from './workspace-cleanup-rule-keys' @@ -38,54 +37,23 @@ import { WorkspaceCleanupRuleChangeDialog, type WorkspaceCleanupRuleChangeRequest } from './workspace-cleanup-rule-change-dialog' -import { WorkspaceCleanupActivityList } from './workspace-cleanup-activity-list' import { getWorkspaceCleanupSettingsSearchParts } from './workspace-cleanup-settings-search' import { workspaceCleanupRowKey } from './workspace-cleanup-workspace-line' import { useMountedRef } from '@/hooks/useMountedRef' - -function removalsFor( - preview: WorkspaceCleanupPreview, - key: WorkspaceCleanupRuleKey -): WorkspaceCleanupPreviewRow[] { - const reason = WORKSPACE_CLEANUP_RULE_REASON[key] - return preview.rows.filter( - (row) => row.evaluation.action !== 'keep' && row.evaluation.reason === reason - ) -} - -/** Workspaces `next` would remove now that `current` would not. */ -function newRemovals( - next: WorkspaceCleanupPreview, - current: WorkspaceCleanupPreview | null -): WorkspaceCleanupPreviewRow[] { - const removedNow = new Set( - (current?.rows ?? []) - .filter((row) => row.evaluation.action !== 'keep') - .map(workspaceCleanupRowKey) - ) - return next.rows.filter( - (row) => row.evaluation.action !== 'keep' && !removedNow.has(workspaceCleanupRowKey(row)) - ) -} - -function summarizeMatches( - preview: WorkspaceCleanupPreview | null -): Partial> | undefined { - if (!preview) { - return undefined - } - const matches: Partial> = {} - for (const key of WORKSPACE_CLEANUP_RULE_KEYS) { - const rows = removalsFor(preview, key) - matches[key] = { rows, sizeBytes: rows.reduce((sum, row) => sum + (row.sizeBytes ?? 0), 0) } - } - return matches -} +import { + useWorkspaceCleanupRuleFocus, + type WorkspaceCleanupChangeOutcome +} from './use-workspace-cleanup-rule-focus' type RulesChange = (rules: WorkspaceCleanupRules) => WorkspaceCleanupRules +type ChangeRequest = Omit + type PendingChange = WorkspaceCleanupRuleChangeRequest & { change: RulesChange } +/** A rule turn-on whose check failed; Try again runs the same change against fresh rules. */ +type FailedCheck = { key: WorkspaceCleanupRuleKey; change: RulesChange; request: ChangeRequest } + export function WorkspaceCleanupSettingsPane({ hostScope, settings, @@ -108,16 +76,28 @@ export function WorkspaceCleanupSettingsPane({ const { hostReport, preview, cleaningUp, cleanUpNow, previewRules, adoptPreview } = useWorkspaceCleanupHostActivity(owner, rules) const matches = useMemo(() => summarizeMatches(preview), [preview]) - const [pendingRule, setPendingRule] = useState(null) + const [pending, setPending] = useState<{ + key: WorkspaceCleanupRuleKey + phase: WorkspaceCleanupRulePhase + } | null>(null) + const [failedCheck, setFailedCheck] = useState(null) const [pendingChange, setPendingChange] = useState(null) + // The rule switch that gets focus back when the confirm dialog closes. + const [returnTargetKey, setReturnTargetKey] = useState(null) // One change at a time: a second one built while the first previews would start from stale rules. const [busy, setBusy] = useState(false) const busyRef = useRef(false) // A change still previewing when the pane unmounts must not write over what came after it. const mountedRef = useMountedRef() - // Remounts the rows after a change that was not saved, so an edited field shows the saved value. + const { registerSwitch, focusRule, settleFocus } = useWorkspaceCleanupRuleFocus(mountedRef) + // Resets the Inactive fields after a change that was not saved, so they show the saved value. const [unsavedChanges, setUnsavedChanges] = useState(0) const search = getWorkspaceCleanupSettingsSearchParts() + const report = hostReport.state === 'ready' ? hostReport.report : null + // A project's own rules can keep the runner scheduled while every global rule is off. + const anyRuleOn = rules + ? hasEnabledWorkspaceCleanupRule(rules) || Boolean(report?.nextRunAt) + : false if (!hostScope.available) { return @@ -158,7 +138,7 @@ export function WorkspaceCleanupSettingsPane({ const finishChange = (saved: boolean): void => { busyRef.current = false setBusy(false) - setPendingRule(null) + setPending(null) if (!saved) { setUnsavedChanges((count) => count + 1) } @@ -170,42 +150,57 @@ export function WorkspaceCleanupSettingsPane({ */ const applyRules = async ( change: RulesChange, - request: Omit | null, + request: ChangeRequest | null, pendingKey: WorkspaceCleanupRuleKey | null = null - ): Promise => { + ): Promise => { if (busyRef.current) { - return + return 'busy' } busyRef.current = true setBusy(true) - setPendingRule(pendingKey) + setFailedCheck(null) + // Only turning a rule on shows its check; other changes show a spinner at the saved value. + const enabling = request?.kind === 'enable' && pendingKey !== null + setPending(pendingKey ? { key: pendingKey, phase: enabling ? 'checking' : 'saving' } : null) // Another client may have changed the rules since this page read them. const latest = await readLatest() if (!mountedRef.current) { - return + return 'unmounted' } if (!latest) { finishChange(false) - return + return 'host-unavailable' } const nextRules = change(latest) const checked = request && hasEnabledWorkspaceCleanupRule(nextRules) - ? await previewNewRemovals(latest, nextRules) + ? await previewNewRemovals(latest, nextRules, !enabling) : { rows: [], nextPreview: null } if (!mountedRef.current) { - return + return 'unmounted' } if (!checked) { + if (enabling && request) { + setFailedCheck({ key: pendingKey, change, request }) + } finishChange(false) - return + return 'check-failed' } if (request && (checked.rows.length > 0 || request.kind === 'disable-ignored-files')) { - setPendingRule(null) + setPending(null) + setReturnTargetKey(pendingKey) setPendingChange({ ...request, rows: checked.rows, change }) - return + return 'confirming' } - finishChange(await saveRules(nextRules, checked.nextPreview)) + if (enabling) { + setPending({ key: pendingKey, phase: 'enabling' }) + } + const saved = await saveRules(nextRules, checked.nextPreview) + if (!mountedRef.current) { + return 'unmounted' + } + finishChange(saved) + return saved ? 'saved' : 'save-failed' } // The would-be rules' preview becomes the page's matches only once those rules are saved. @@ -220,10 +215,11 @@ export function WorkspaceCleanupSettingsPane({ return saved } - /** Null when the preview failed; the toast says so. */ + /** Null when the preview failed; the toast says so unless the caller shows it inline. */ const previewNewRemovals = async ( latest: WorkspaceCleanupRules, - nextRules: WorkspaceCleanupRules + nextRules: WorkspaceCleanupRules, + toastOnFailure = true ): Promise<{ rows: WorkspaceCleanupPreviewRow[] nextPreview: WorkspaceCleanupPreview @@ -232,13 +228,15 @@ export function WorkspaceCleanupSettingsPane({ // can delete with every global rule off, so the current rules are always read. const previews = await Promise.all([previewRules(nextRules), previewRules(latest)]).catch( (error: unknown) => { - toast.error( - t( - 'components.settings.workspaceCleanup.previewFailed', - "Couldn't check which workspaces this change matches." - ), - { description: errorMessage(error) } - ) + if (toastOnFailure) { + toast.error( + t( + 'components.settings.workspaceCleanup.previewFailed', + "Couldn't check which workspaces this change matches." + ), + { description: errorMessage(error) } + ) + } return null } ) @@ -253,7 +251,30 @@ export function WorkspaceCleanupSettingsPane({ (latest) => setWorkspaceCleanupRuleEnabled(latest, key, enabled), enabled ? { kind: 'enable', ruleTitle: search[key].title } : null, key - ) + ).then((outcome) => settleFocus(key, outcome)) + } + + const retryCheck = (): void => { + if (!failedCheck || busyRef.current) { + return + } + const { key, change, request } = failedCheck + // Try again unmounts once the retry starts; the switch holds focus through it. + focusRule(key) + void applyRules(change, request, key).then((outcome) => settleFocus(key, outcome)) + } + + const returnFocusAfterDialog = (event: Event): void => { + if (returnTargetKey === null) { + return + } + if (focusRule(returnTargetKey)) { + event.preventDefault() + } + // The dialog can also close because the page swapped to a host error; keep the target then. + if (pendingChange === null) { + setReturnTargetKey(null) + } } const cancelChange = (): void => { @@ -315,8 +336,8 @@ export function WorkspaceCleanupSettingsPane({ } } - const hasQuery = query.trim() !== '' - const showRules = matchesSettingsSearch(query, [ + const showManual = matchesSettingsSearch(query, [search.review]) + const showRuleRows = matchesSettingsSearch(query, [ search.merged, search.unchanged, search.inactive, @@ -325,107 +346,65 @@ export function WorkspaceCleanupSettingsPane({ ]) const showProtection = matchesSettingsSearch(query, [search.keepIgnoredFiles]) const showActivity = matchesSettingsSearch(query, [search.activity]) - const report = hostReport.state === 'ready' ? hostReport.report : null return ( <> - : null} + void cleanUpNow()} - /> - {showRules ? ( -
- - - void applyRules( - change, - { kind: 'change', ruleTitle: search.inactive.title }, - 'inactive' - ) - } - /> - - {hasQuery ? null : ( -

- {t( - 'components.settings.workspaceCleanup.rules.branchNote', - 'Merged branches are deleted with their workspace. Unmerged branches are kept.' - )} -

- )} -
- ) : null} - {showProtection ? ( - - - { - const keepIgnored = currentRules.keepWhen !== 'any-local-files' - void applyRules( - (latest) => ({ - ...latest, - keepWhen: keepIgnored ? 'any-local-files' : 'uncommitted' - }), - // Keeping more can only delete less; letting ignored files go asks first. - keepIgnored - ? null - : { kind: 'disable-ignored-files', ruleTitle: search.keepIgnoredFiles.title } - ) - }} - /> - - - ) : null} - {showActivity ? ( - + + void applyRules( + change, + { kind: 'change', ruleTitle: search.inactive.title }, + 'inactive' + ) } - > - {report && report.runs.length > 0 ? ( - - ) : null} - + /> +
+ {showProtection ? ( + { + const keepIgnored = currentRules.keepWhen !== 'any-local-files' + void applyRules( + (latest) => ({ + ...latest, + keepWhen: keepIgnored ? 'any-local-files' : 'uncommitted' + }), + // Keeping more can only delete less; letting ignored files go asks first. + keepIgnored + ? null + : { kind: 'disable-ignored-files', ruleTitle: search.keepIgnoredFiles.title } + ) + }} + /> ) : null} + {showActivity ? : null} ) diff --git a/src/renderer/src/components/settings/workspace-cleanup/use-workspace-cleanup-rule-focus.ts b/src/renderer/src/components/settings/workspace-cleanup/use-workspace-cleanup-rule-focus.ts new file mode 100644 index 00000000000..0dabfe3e8dc --- /dev/null +++ b/src/renderer/src/components/settings/workspace-cleanup/use-workspace-cleanup-rule-focus.ts @@ -0,0 +1,58 @@ +import { useRef, type RefObject } from 'react' +import type { WorkspaceCleanupRuleKey } from './workspace-cleanup-rule-keys' + +/** + * How a rule change ended. `host-unavailable`: the host's rules could not be read, and the page + * shows that instead. `busy`: another change was in flight, so this one did nothing. + */ +export type WorkspaceCleanupChangeOutcome = + | 'saved' + | 'confirming' + | 'check-failed' + | 'save-failed' + | 'host-unavailable' + | 'busy' + | 'unmounted' + +/** Hands focus back to the rule switch that started a change, only while the page still shows it. */ +export function useWorkspaceCleanupRuleFocus(mountedRef: RefObject): { + registerSwitch: (key: WorkspaceCleanupRuleKey, element: HTMLButtonElement | null) => void + focusRule: (key: WorkspaceCleanupRuleKey) => boolean + settleFocus: (key: WorkspaceCleanupRuleKey, outcome: WorkspaceCleanupChangeOutcome) => void +} { + const switches = useRef(new Map()) + + const focusRule = (key: WorkspaceCleanupRuleKey): boolean => { + const element = switches.current.get(key) + if ( + !mountedRef.current || + !element?.isConnected || + (typeof element.checkVisibility === 'function' && !element.checkVisibility()) + ) { + return false + } + element.focus() + return true + } + + return { + registerSwitch: (key, element) => { + if (element) { + switches.current.set(key, element) + } else { + switches.current.delete(key) + } + }, + focusRule, + // Keeps focus on the switch that started the change unless the user has moved it on purpose. + settleFocus: (key, outcome) => { + if (outcome !== 'saved' && outcome !== 'check-failed' && outcome !== 'save-failed') { + return + } + const active = document.activeElement + if (!active || active === document.body || active === switches.current.get(key)) { + focusRule(key) + } + } + } +} diff --git a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-activity-section.tsx b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-activity-section.tsx new file mode 100644 index 00000000000..5a4a501df8a --- /dev/null +++ b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-activity-section.tsx @@ -0,0 +1,38 @@ +import { useTranslate } from '@/i18n/use-translate' +import { SettingsGroup } from '../section-layout/SettingsGroup' +import { WorkspaceCleanupActivityList } from './workspace-cleanup-activity-list' +import { getWorkspaceCleanupSettingsSearchParts } from './workspace-cleanup-settings-search' +import type { WorkspaceCleanupHostReport } from './use-workspace-cleanup-host-activity' + +/** What each run removed and kept, or why there is nothing to show. */ +export function WorkspaceCleanupActivitySection({ + hostReport +}: { + hostReport: WorkspaceCleanupHostReport +}): React.JSX.Element { + const t = useTranslate() + const search = getWorkspaceCleanupSettingsSearchParts() + const report = hostReport.state === 'ready' ? hostReport.report : null + const note = + hostReport.state === 'error' + ? t( + 'components.settings.workspaceCleanup.activity.loadFailed', + "Couldn't load activity: {{error}}", + { error: hostReport.message } + ) + : report && report.runs.length === 0 + ? t('components.settings.workspaceCleanup.activity.empty', "Cleanup hasn't run yet.") + : null + return ( + + {note ? ( +

+ {note} +

+ ) : null} + {report && report.runs.length > 0 ? ( + + ) : null} +
+ ) +} diff --git a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-settings-status.tsx b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-automatic-section.tsx similarity index 50% rename from src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-settings-status.tsx rename to src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-automatic-section.tsx index 8c502fae53d..7a1fb1e3fca 100644 --- a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-settings-status.tsx +++ b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-automatic-section.tsx @@ -1,10 +1,14 @@ +import { Loader2 } from 'lucide-react' import { useTranslate, type Translate } from '@/i18n/use-translate' import { formatUiRelativeTime } from '@/i18n/relative-time-format' -import { useAppStore } from '@/store' +import { cn } from '@/lib/class-names' import { formatBytes } from '../../../../../shared/text/format-bytes' import type { WorkspaceCleanupReport } from '../../../../../shared/workspace-cleanup/workspace-cleanup-run' +import { useAppStateValue } from '@/store/retained-views/app-state-view' import { Button } from '../../ui/button' +import { SettingsGroup, SettingsGroupHeader } from '../section-layout/SettingsGroup' import { SearchableSetting } from '../section-layout/SearchableSetting' +import { matchesSettingsSearch } from '../search/settings-search' import { getWorkspaceCleanupSettingsSearchParts } from './workspace-cleanup-settings-search' // Intl says "this minute" for both directions under a minute, which reads oddly in a sentence. @@ -62,13 +66,18 @@ function formatLastRun( ) } -/** Whether automatic cleanup is on, what it last did, and the two ways to act now. */ -export function WorkspaceCleanupSettingsStatus({ +/** + * The rules under a heading that says whether automatic cleanup is on, what it last did, and runs + * the rules now. A search that matches only the heading shows it without the rules. + */ +export function WorkspaceCleanupAutomaticSection({ anyRuleOn, report, readAt, cleaningUp, - onCleanUpNow + onCleanUpNow, + showRules, + children }: { anyRuleOn: boolean report: WorkspaceCleanupReport | null @@ -76,9 +85,13 @@ export function WorkspaceCleanupSettingsStatus({ readAt: number cleaningUp: boolean onCleanUpNow: () => void -}): React.JSX.Element { + /** Whether the search matches a rule. */ + showRules: boolean + /** The rule rows. */ + children: React.ReactNode +}): React.JSX.Element | null { const t = useTranslate() - const openModal = useAppStore((state) => state.openModal) + const query = useAppStateValue((state) => state.settingsSearchQuery) const search = getWorkspaceCleanupSettingsSearchParts() const lastRun = report?.runs[0] const running = cleaningUp || report?.running === true @@ -86,17 +99,19 @@ export function WorkspaceCleanupSettingsStatus({ if (!anyRuleOn) { details.push( t( - 'components.settings.workspaceCleanup.status.offDetail', - 'Nothing is removed until you turn on a rule.' + 'components.settings.workspaceCleanup.automatic.offDetail', + 'Turn on a rule to remove workspaces on a schedule.' ) ) + } else if (running) { + details.push( + t('components.settings.workspaceCleanup.automatic.running', 'Removing what your rules match…') + ) } else { - if (running) { - details.push(t('components.settings.workspaceCleanup.status.running', 'Cleaning up now…')) - } else if (lastRun) { + if (lastRun) { details.push(formatLastRun(lastRun, readAt, t)) } - if (!running && report?.nextRunAt) { + if (report?.nextRunAt) { details.push( t('components.settings.workspaceCleanup.status.nextRun', 'Next run {{when}}.', { when: formatRunTime(Math.max(0, report.nextRunAt - readAt), t) @@ -105,47 +120,56 @@ export function WorkspaceCleanupSettingsStatus({ } } + const title = ( + + {t('components.settings.workspaceCleanup.automatic.title', 'Automatic cleanup')} + + + + ) + const description = + details.length > 0 ? {details.join(' ')} : null + const action = anyRuleOn ? ( + + ) : null + + if (!showRules) { + return matchesSettingsSearch(query, [search.status]) ? ( + + + + ) : null + } return ( - -
-

- {anyRuleOn - ? t('components.settings.workspaceCleanup.status.on', 'Automatic cleanup is on.') - : t('components.settings.workspaceCleanup.status.off', 'Automatic cleanup is off.')} + + {children} + {query.trim() === '' ? ( +

+ {t( + 'components.settings.workspaceCleanup.rules.branchNote', + 'Merged branches are deleted with their workspace. Unmerged branches are kept.' + )}

- {details.map((line) => ( -

- {line} -

- ))} -
-
-
- - -
- {anyRuleOn ? null : ( -

- {t( - 'components.settings.workspaceCleanup.status.turnOnHint', - 'Turn on a rule to use this.' - )} -

- )} -
-
+ ) : null} + ) } diff --git a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-manual-section.tsx b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-manual-section.tsx new file mode 100644 index 00000000000..4735645a739 --- /dev/null +++ b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-manual-section.tsx @@ -0,0 +1,36 @@ +import { List } from 'lucide-react' +import { useTranslate } from '@/i18n/use-translate' +import { useAppStore } from '@/store' +import { Button } from '../../ui/button' +import { SettingsRow } from '../form-controls/SettingsFormControls' +import { SettingsGroup } from '../section-layout/SettingsGroup' +import { SearchableSetting } from '../section-layout/SearchableSetting' +import { getWorkspaceCleanupSettingsSearchParts } from './workspace-cleanup-settings-search' + +/** Deleting workspaces by hand, whether or not any rule is on. */ +export function WorkspaceCleanupManualSection(): React.JSX.Element { + const t = useTranslate() + const openModal = useAppStore((state) => state.openModal) + const search = getWorkspaceCleanupSettingsSearchParts() + return ( + + + openModal('workspace-cleanup')}> + + {search.review.title} + + } + /> + + + ) +} diff --git a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-preview-matches.ts b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-preview-matches.ts new file mode 100644 index 00000000000..41c9d3edc7b --- /dev/null +++ b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-preview-matches.ts @@ -0,0 +1,50 @@ +import { WORKSPACE_CLEANUP_RULE_KEYS } from '../../../../../shared/workspace-cleanup/workspace-cleanup-policy' +import type { + WorkspaceCleanupPreview, + WorkspaceCleanupPreviewRow +} from '../../../../../shared/workspace-cleanup/workspace-cleanup-run' +import type { WorkspaceCleanupRuleMatches } from './workspace-cleanup-rule-rows' +import { + WORKSPACE_CLEANUP_RULE_REASON, + type WorkspaceCleanupRuleKey +} from './workspace-cleanup-rule-keys' +import { workspaceCleanupRowKey } from './workspace-cleanup-workspace-line' + +function removalsFor( + preview: WorkspaceCleanupPreview, + key: WorkspaceCleanupRuleKey +): WorkspaceCleanupPreviewRow[] { + const reason = WORKSPACE_CLEANUP_RULE_REASON[key] + return preview.rows.filter( + (row) => row.evaluation.action !== 'keep' && row.evaluation.reason === reason + ) +} + +/** Workspaces `next` would remove now that `current` would not. */ +export function newRemovals( + next: WorkspaceCleanupPreview, + current: WorkspaceCleanupPreview | null +): WorkspaceCleanupPreviewRow[] { + const removedNow = new Set( + (current?.rows ?? []) + .filter((row) => row.evaluation.action !== 'keep') + .map(workspaceCleanupRowKey) + ) + return next.rows.filter( + (row) => row.evaluation.action !== 'keep' && !removedNow.has(workspaceCleanupRowKey(row)) + ) +} + +export function summarizeMatches( + preview: WorkspaceCleanupPreview | null +): Partial> | undefined { + if (!preview) { + return undefined + } + const matches: Partial> = {} + for (const key of WORKSPACE_CLEANUP_RULE_KEYS) { + const rows = removalsFor(preview, key) + matches[key] = { rows, sizeBytes: rows.reduce((sum, row) => sum + (row.sizeBytes ?? 0), 0) } + } + return matches +} diff --git a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-protection-section.tsx b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-protection-section.tsx new file mode 100644 index 00000000000..606be251ff3 --- /dev/null +++ b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-protection-section.tsx @@ -0,0 +1,40 @@ +import { useTranslate } from '@/i18n/use-translate' +import { SettingsRow, SettingsSwitchRow } from '../form-controls/SettingsFormControls' +import { SettingsGroup } from '../section-layout/SettingsGroup' +import { SearchableSetting } from '../section-layout/SearchableSetting' +import { getWorkspaceCleanupSettingsSearchParts } from './workspace-cleanup-settings-search' + +/** What cleanup never removes, and whether ignored files also keep a workspace. */ +export function WorkspaceCleanupProtectionSection({ + keepIgnoredFiles, + disabled, + onToggleKeepIgnoredFiles +}: { + keepIgnoredFiles: boolean + disabled: boolean + onToggleKeepIgnoredFiles: () => void +}): React.JSX.Element { + const t = useTranslate() + const search = getWorkspaceCleanupSettingsSearchParts() + return ( + + + + + + + ) +} diff --git a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-rule-change-dialog.tsx b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-rule-change-dialog.tsx index a779ec37bcf..7643d8306d9 100644 --- a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-rule-change-dialog.tsx +++ b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-rule-change-dialog.tsx @@ -30,11 +30,14 @@ export type WorkspaceCleanupRuleChangeRequest = { export function WorkspaceCleanupRuleChangeDialog({ request, onCancel, - onConfirm + onConfirm, + onCloseAutoFocus }: { request: WorkspaceCleanupRuleChangeRequest | null onCancel: () => void onConfirm: (keep: WorkspaceCleanupPreviewRow[]) => Promise + /** Lets the page hand focus back to the control that started the change. */ + onCloseAutoFocus?: (event: Event) => void }): React.JSX.Element { const t = useTranslate() const [kept, setKept] = useState>(new Set()) @@ -76,6 +79,7 @@ export function WorkspaceCleanupRuleChangeDialog({ > void + switchRef: (key: WorkspaceCleanupRuleKey, element: HTMLButtonElement | null) => void +} + type RuleRowsProps = { rules: WorkspaceCleanupRules onToggle: (key: WorkspaceCleanupRuleKey) => void @@ -39,64 +60,144 @@ type RuleRowsProps = { onChange: (change: (rules: WorkspaceCleanupRules) => WorkspaceCleanupRules) => void /** What each rule that is on would remove now; omitted where no preview is read. */ matches?: Partial> - /** A rule whose change is waiting on a preview or a write. */ - pendingRule?: WorkspaceCleanupRuleKey | null - /** Set while any change is in flight, so a second change cannot start from stale rules. */ + operation?: WorkspaceCleanupRuleOperation + /** Changes after a change that was not saved, so the Inactive fields show the saved values. */ + inactiveDraftKey?: number + /** Natively disables every control while a change is in flight. */ disabled?: boolean forceVisible?: boolean } +const ADVANCED_RULES: ReadonlySet = new Set([ + 'automationRuns', + 'orchestrationWorkers' +]) + +function isAdvancedRule(key: WorkspaceCleanupRuleKey | null): boolean { + return key !== null && ADVANCED_RULES.has(key) +} + +const PENDING_ON_TRACK_CLASS = + 'data-[state=checked]:bg-[color-mix(in_srgb,var(--foreground)_45%,color-mix(in_srgb,var(--muted-foreground)_30%,transparent))]' + /** The rule switches, shared by the Workspace Cleanup page and a project's custom rules. */ export function WorkspaceCleanupRuleRows({ rules, onToggle, onChange, matches, - pendingRule, + operation, + inactiveDraftKey, disabled = false, forceVisible = false }: RuleRowsProps): React.JSX.Element { const t = useTranslate() + const idPrefix = useId() const query = useAppStateValue((state) => state.settingsSearchQuery) const search = getWorkspaceCleanupSettingsSearchParts() const advancedMatches = query.trim() !== '' && matchesSettingsSearch(query, [search.automationRuns, search.orchestrationWorkers]) - const ruleRow = (key: WorkspaceCleanupRuleKey, description: string, badge?: string) => ( - - - {search[key].title} - {badge ? {badge} : null} -
- } - description={ - <> - {description} - {pendingRule === key ? ( - - {t( - 'components.settings.workspaceCleanup.rules.checking', - 'Checking which workspaces match…' - )} - - ) : matches?.[key] && rules[key].enabled ? ( - - ) : null} - - } - checked={rules[key].enabled} - disabled={disabled} - onChange={() => onToggle(key)} - ariaLabel={search[key].title} - /> - {key === 'inactive' && rules.inactive.enabled ? ( - - ) : null} - - ) + // Advanced opens for a rule being changed and stays open once the change settles, so the switch + // that gets focus back is visible; only the user closes it again. + const target = operation + ? (operation.pending?.key ?? operation.failedKey ?? operation.returnTargetKey) + : null + const [advancedOpen, setAdvancedOpen] = useState(() => isAdvancedRule(target)) + const [revealedFor, setRevealedFor] = useState(target) + if (target !== revealedFor) { + setRevealedFor(target) + if (isAdvancedRule(target)) { + setAdvancedOpen(true) + } + } + + const ruleRow = (key: WorkspaceCleanupRuleKey, description: string, badge?: string) => { + const phase = operation?.pending?.key === key ? operation.pending.phase : null + const failed = operation?.failedKey === key && !rules[key].enabled + const errorId = `${idPrefix}-${key}-check-failed` + const shownOn = phase === 'checking' || phase === 'enabling' ? true : rules[key].enabled + const blocked = Boolean(operation?.busy) && phase === null + return ( + + + {search[key].title} + {badge ? {badge} : null} + + } + description={ + <> + {description} + {phase === 'checking' ? ( + + + {t( + 'components.settings.workspaceCleanup.rules.checking', + 'Checking which workspaces match…' + )} + + ) : failed ? ( + + {t( + 'components.settings.workspaceCleanup.rules.checkFailed', + "Couldn't check which workspaces match." + )}{' '} + + + ) : matches?.[key] && rules[key].enabled ? ( + + ) : null} + + } + control={ + operation.switchRef(key, element) : undefined} + // Shown On while its turn-on is checked or saved; screen readers hear the saved value. + checked={shownOn} + aria-checked={rules[key].enabled} + aria-busy={phase ? true : undefined} + aria-disabled={blocked ? true : undefined} + aria-describedby={failed ? errorId : undefined} + disabled={disabled} + className={cn( + phase && shownOn && !rules[key].enabled && PENDING_ON_TRACK_CLASS, + blocked && 'cursor-not-allowed opacity-50' + )} + thumbClassName={phase ? 'flex items-center justify-center' : undefined} + thumbContent={ + phase ? ( + + ) : null + } + onCheckedChange={() => { + if (!operation?.busy) { + onToggle(key) + } + }} + aria-label={search[key].title} + /> + } + /> + {key === 'inactive' && rules.inactive.enabled ? ( + + ) : null} + + ) + } return ( <> @@ -120,6 +221,10 @@ export function WorkspaceCleanupRuleRows({ 'Automation and orchestration worker workspaces' )} forceOpen={advancedMatches} + // The page lines Advanced rows up with the others and keeps them open for a change. + open={operation ? advancedOpen : undefined} + onOpenChange={operation ? setAdvancedOpen : undefined} + flush={operation !== undefined} > {ruleRow('automationRuns', search.automationRuns.description)} {ruleRow('orchestrationWorkers', search.orchestrationWorkers.description)} diff --git a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-settings-search.ts b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-settings-search.ts index 27b606d9eb9..0a37de9fd12 100644 --- a/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-settings-search.ts +++ b/src/renderer/src/components/settings/workspace-cleanup/workspace-cleanup-settings-search.ts @@ -16,20 +16,31 @@ function cleanupKeywords(): string[] { export const getWorkspaceCleanupSettingsSearchParts = createLocalizedCatalog( () => ({ - status: { - title: translate('components.settings.workspaceCleanup.cleanUpNow', 'Clean up now'), + review: { + title: translate('components.settings.workspaceCleanup.manual.review', 'Review workspaces'), description: translate( - 'components.settings.workspaceCleanup.search.statusDescription', - 'Run the cleanup rules now, or review workspaces yourself.' + 'components.settings.workspaceCleanup.manual.description', + 'See every workspace and choose which to delete.' + ), + keywords: [ + ...cleanupKeywords(), + ...translateSearchKeyword('components.settings.workspaceCleanup.search.manual', 'manual') + ] + }, + status: { + title: translate('components.settings.workspaceCleanup.automatic.runNow', 'Run rules now'), + description: translate( + 'components.settings.workspaceCleanup.search.automaticDescription', + 'Whether automatic cleanup is on, when it runs next, and running the rules now.' ), keywords: [ - ...translateSearchKeyword( - 'components.settings.workspaceCleanup.search.reviewWorkspaces', - 'review workspaces' - ), ...translateSearchKeyword( 'components.settings.workspaceCleanup.search.automatic', 'automatic' + ), + ...translateSearchKeyword( + 'components.settings.workspaceCleanup.search.cleanUp', + 'clean up' ) ] }, diff --git a/src/renderer/src/components/ui/switch.tsx b/src/renderer/src/components/ui/switch.tsx index ab7651dbf5f..9d249617909 100644 --- a/src/renderer/src/components/ui/switch.tsx +++ b/src/renderer/src/components/ui/switch.tsx @@ -13,12 +13,15 @@ const compactThumbClassName = 'size-2.5 data-[state=checked]:translate-x-2.5' type SwitchProps = React.ComponentProps & { size?: 'default' | 'compact' thumbClassName?: string + /** Drawn inside the thumb, such as a pending spinner. */ + thumbContent?: React.ReactNode } function Switch({ className, size = 'default', thumbClassName: thumbClasses, + thumbContent, ...props }: SwitchProps) { return ( @@ -35,7 +38,9 @@ function Switch({ + > + {thumbContent} + ) } diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index adafd108ab1..3f9bddbfa38 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -22499,7 +22499,6 @@ "previewFailed": "Couldn't check which workspaces this change matches.", "pinFailed": "Couldn't keep {{name}}.", "rules": { - "title": "Rules", "branchNote": "Merged branches are deleted with their workspace. Unmerged branches are kept.", "recommended": "Recommended", "inactiveDescription": "No activity for {{count}} days.", @@ -22528,13 +22527,15 @@ "inactiveDescription_other": "No activity for {{count}} days.", "matchesCount_one": "Matches 1 workspace now", "matchesCount_other": "Matches {{count}} workspaces now", - "checking": "Checking which workspaces match…" + "checking": "Checking which workspaces match…", + "checkFailed": "Couldn't check which workspaces match." }, "protection": { "title": "Protection", - "alwaysKept": "Always kept: pinned workspaces, running agents or terminals, unsaved editor changes, uncommitted changes, unpushed commits.", "keepIgnoredFiles": "Keep workspaces with ignored files", - "keepIgnoredFilesDescription": "Files like .env and local config can't be recovered. node_modules and build output don't count." + "keepIgnoredFilesDescription": "Files like .env and local config can't be recovered. node_modules and build output don't count.", + "alwaysKeptLabel": "Always kept", + "alwaysKeptList": "Pinned workspaces, running agents or terminals, unsaved editor changes, uncommitted changes, unpushed commits." }, "activity": { "loadFailed": "Couldn't load activity: {{error}}", @@ -22606,8 +22607,6 @@ "cleanup": "cleanup", "cleanUp": "clean up", "delete": "delete", - "statusDescription": "Run the cleanup rules now, or review workspaces yourself.", - "reviewWorkspaces": "review workspaces", "automatic": "automatic", "pullRequest": "PR", "inactiveDescription": "No activity for a number of days.", @@ -22619,9 +22618,10 @@ "activityDescription": "What each cleanup run removed and kept.", "history": "history", "runs": "runs", - "envFile": ".env" + "envFile": ".env", + "manual": "manual", + "automaticDescription": "Whether automatic cleanup is on, when it runs next, and running the rules now." }, - "cleanUpNow": "Clean up now", "status": { "lastRunFailed": "Last run {{when}} couldn't finish: {{error}}", "lastRunNothing": "Last run {{when}} removed nothing.", @@ -22629,13 +22629,7 @@ "lastRunFreed_other": "Last run {{when}} removed {{count}} workspaces and freed {{size}}.", "lastRunRemoved_one": "Last run {{when}} removed 1 workspace.", "lastRunRemoved_other": "Last run {{when}} removed {{count}} workspaces.", - "offDetail": "Nothing is removed until you turn on a rule.", - "running": "Cleaning up now…", "nextRun": "Next run {{when}}.", - "on": "Automatic cleanup is on.", - "off": "Automatic cleanup is off.", - "review": "Review workspaces", - "turnOnHint": "Turn on a rule to use this.", "justNow": "just now", "inUnderAMinute": "in under a minute" }, @@ -22668,6 +22662,21 @@ "description": "Selected workspaces will be pinned when you confirm. Pinned workspaces are excluded from automatic cleanup until you unpin them.", "named": "Pin and keep {{name}}", "label": "Pin and keep" + }, + "manual": { + "title": "Manual cleanup", + "label": "Delete workspaces you pick", + "review": "Review workspaces", + "description": "See every workspace and choose which to delete." + }, + "automatic": { + "offDetail": "Turn on a rule to remove workspaces on a schedule.", + "running": "Removing what your rules match…", + "title": "Automatic cleanup", + "on": "On", + "off": "Off", + "runningButton": "Running…", + "runNow": "Run rules now" } }, "repository": {