mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 11:24:37 +00:00
feat(settings): add a Workspace Cleanup settings page with rules, run now and activity (#42039)
* feat(settings): add Workspace Cleanup settings page Adds a Settings > Workspace Cleanup page for the host that owns the repos: status with Clean up now, the rule switches, the ignored-files protection and an Activity list of past runs. Turning on a delete rule that matches workspaces right now asks first; Keep pins a workspace. The page refreshes when the host's runner finishes a run: desktop main now forwards workspaceCleanupRunFinished to its window, and remote hosts' event is no longer dropped by the client event allowlist. * feat(settings): confirm any cleanup rule change that would delete workspaces now Lowering the inactive days or turning off the ignored-files protection makes the runner delete within seconds too, so those changes get the same confirm as turning a rule on. * fix(settings): serialize cleanup rule changes and guard the confirm One rule change at a time, built from the host's rules as they are when it is saved; Esc or the close button can no longer abandon a confirm that is already saving. Local save failures surface, a host whose rules cannot be read says so with a retry, and the page follows project rules that keep the runner on. * fix(settings): keep cleanup changes bound to fresh rules and this page A change re-reads the host's rules when it is confirmed, a change still previewing when the page closes is dropped, Keep locks while saving, and each preview is kept with the rules it evaluated. The page is hidden in a paired browser, whose settings are not the host's. * refactor(settings): reuse existing helpers in the Workspace Cleanup page One row key helper, useMountedRef, SettingsSwitchRow and the shared runtime target builder; only the preview of rules about to be saved is kept as the page's matches, and the report waits for the rules. * chore(i18n): protect the cleanup confirm's copy * fix(settings): re-check the cleanup confirm when the rules moved meanwhile If another client changed the rules while the confirm was open, preview again and list any workspace the dialog had not shown before saving. * fix(settings): preview again on every cleanup confirm A workspace can age past a rule while the confirm is open, so the confirm always checks again and lists anything new before saving. * fix(settings): drop a confirmed cleanup change if the page closed while pinning * feat(workspace-cleanup): keep PR number and ignored file names on cleanup rows Run and preview rows now carry the merged PR number and up to 3 ignored file names the evidence already read, so the page can say 'Merged · #4182' and 'Ignored files · .env'. No new Git reads; older saved runs lack them. * fix(settings): say when a run's saved receipt lists fewer kept workspaces * fix(workspace-cleanup): import at-risk local files from its new home * perf(workspace-cleanup): share in-flight previews and stop re-scanning confirmed rules The host shares one evaluation between previews of the same rules, so reopened pages and several clients no longer stack full scans. The page keeps a would-be rules preview out of its matches until those rules are saved, then adopts it, and reuses its own preview for the current rules.
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import type { WorkspaceMetadataSet } from '../../../../shared/worktree/metadata/workspace-metadata-set'
|
||||
import type { WorkspaceCleanupRunFinishedEvent } from '../../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
import type {
|
||||
RuntimeEditorTabReveal,
|
||||
RuntimeFileOpenPosition
|
||||
@@ -55,6 +56,7 @@ export type RuntimeNotifier = {
|
||||
worktreeRemoteBranchConflict?(event: WorktreeRemoteBranchConflictEvent): void
|
||||
reposChanged(): void
|
||||
browserProfilesChanged?(): void
|
||||
workspaceCleanupRunFinished?(run: WorkspaceCleanupRunFinishedEvent['run']): void
|
||||
activateWorktree(
|
||||
repoId: string,
|
||||
worktreeId: string,
|
||||
|
||||
@@ -69,6 +69,7 @@ export abstract class RuntimeWorkspaceChangeEvents extends NativeChatLaunchDraft
|
||||
|
||||
/** The cleanup runner finished a run on this host; clients may toast. */
|
||||
notifyWorkspaceCleanupRunFinished(run: WorkspaceCleanupRunFinishedEvent['run']): void {
|
||||
this.notifier?.workspaceCleanupRunFinished?.(run)
|
||||
this.emitClientEvent({ type: 'workspaceCleanupRunFinished', run })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,7 @@ export function registerRuntimeWindowLifecycle(
|
||||
reposChanged: () => send('repos:changed'),
|
||||
browserProfilesChanged: () => send('browser:session:profilesChanged'),
|
||||
automationsChanged: (payload) => send('automations:changed', payload),
|
||||
workspaceCleanupRunFinished: (run) => send('workspaceCleanup:runFinished', run),
|
||||
activateWorktree: (
|
||||
repoId,
|
||||
worktreeId,
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import type { WorkspaceCleanupEvaluation } from '../../../shared/workspace-cleanup/workspace-cleanup-evaluation'
|
||||
import type {
|
||||
WorkspaceCleanupEvaluation,
|
||||
WorkspaceCleanupEvaluationInput
|
||||
} from '../../../shared/workspace-cleanup/workspace-cleanup-evaluation'
|
||||
import { hasWorktreeAtRiskLocalFiles } from '../../../shared/worktree/removal/at-risk-local-files'
|
||||
import {
|
||||
WORKSPACE_CLEANUP_REPORT_ROW_LIMIT,
|
||||
WORKSPACE_CLEANUP_ROW_IGNORED_FILE_LIMIT,
|
||||
type WorkspaceCleanupRowDetails,
|
||||
WORKSPACE_CLEANUP_UNWATCHED_CAUSES,
|
||||
type WorkspaceCleanupRun,
|
||||
type WorkspaceCleanupRunOutcome,
|
||||
@@ -12,6 +18,26 @@ export type WorkspaceCleanupKeptOutcome = Pick<
|
||||
'outcome' | 'reason' | 'keepCause' | 'waiting'
|
||||
>
|
||||
|
||||
/** What the evidence already says about a row, for its label; no new Git reads. */
|
||||
export function workspaceCleanupRowDetails(
|
||||
input: Pick<WorkspaceCleanupEvaluationInput, 'git'>
|
||||
): WorkspaceCleanupRowDetails {
|
||||
const review = input.git.merge?.mergedReview
|
||||
const files = input.git.atRiskLocalFiles
|
||||
return {
|
||||
...(review?.containsHead ? { prNumber: review.number } : {}),
|
||||
...(files && hasWorktreeAtRiskLocalFiles(files)
|
||||
? {
|
||||
ignoredFiles: {
|
||||
count: files.count,
|
||||
samplePaths: files.samplePaths.slice(0, WORKSPACE_CLEANUP_ROW_IGNORED_FILE_LIMIT),
|
||||
complete: files.complete
|
||||
}
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
|
||||
export function keptRunOutcome(
|
||||
evaluation: WorkspaceCleanupEvaluation
|
||||
): WorkspaceCleanupKeptOutcome {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { OrcaRuntimeService } from '../../runtime/orca-runtime'
|
||||
import type { RuntimeStore } from '../../runtime/construction/runtime-store-contract'
|
||||
import { getDefaultWorkspaceCleanupRules } from '../../../shared/workspace-cleanup/workspace-cleanup-policy'
|
||||
|
||||
const { collectWorkspaces } = vi.hoisted(() => ({ collectWorkspaces: vi.fn() }))
|
||||
|
||||
vi.mock('./workspace-cleanup-run-evidence', () => ({
|
||||
collectWorkspaceCleanupWorkspaces: collectWorkspaces
|
||||
}))
|
||||
vi.mock('../space-analysis/workspace-space-analysis-snapshot', () => ({
|
||||
readWorkspaceSpaceAnalysisSnapshot: () => Promise.resolve(null)
|
||||
}))
|
||||
|
||||
const { WorkspaceCleanupRunner } = await import('./workspace-cleanup-runner')
|
||||
|
||||
function createRunner(): InstanceType<typeof WorkspaceCleanupRunner> {
|
||||
const store = {
|
||||
getSettings: () => ({ workspaceCleanupPolicy: getDefaultWorkspaceCleanupRules() })
|
||||
}
|
||||
return new WorkspaceCleanupRunner({
|
||||
// SAFETY: preview only reads settings from the store and passes the runtime through to mocked evidence.
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: see above
|
||||
store: store as unknown as RuntimeStore,
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: see above
|
||||
runtime: {} as OrcaRuntimeService,
|
||||
historyDirectory: '/unused'
|
||||
})
|
||||
}
|
||||
|
||||
describe('workspace cleanup runner preview', () => {
|
||||
afterEach(() => {
|
||||
collectWorkspaces.mockReset()
|
||||
})
|
||||
|
||||
it('shares one evaluation between concurrent previews of the same rules', async () => {
|
||||
let finish: (value: []) => void = () => {}
|
||||
collectWorkspaces.mockReturnValue(new Promise<[]>((resolve) => (finish = resolve)))
|
||||
const runner = createRunner()
|
||||
|
||||
const first = runner.preview()
|
||||
const second = runner.preview(getDefaultWorkspaceCleanupRules())
|
||||
finish([])
|
||||
await Promise.all([first, second])
|
||||
|
||||
expect(collectWorkspaces).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
WorkspaceCleanupReport,
|
||||
WorkspaceCleanupRun,
|
||||
WorkspaceCleanupRunRow,
|
||||
WorkspaceCleanupRowDetails,
|
||||
WorkspaceCleanupRunTrigger,
|
||||
WorkspaceCleanupWorkspaceRef
|
||||
} from '../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
@@ -24,7 +25,11 @@ import {
|
||||
type WorkspaceCleanupWorkspace
|
||||
} from './workspace-cleanup-run-evidence'
|
||||
import { decideWorkspaceCleanup, removeWorkspaceForCleanup } from './workspace-cleanup-removal-step'
|
||||
import { keptRunOutcome, summarizeWorkspaceCleanupRun } from './workspace-cleanup-run-summary'
|
||||
import {
|
||||
keptRunOutcome,
|
||||
summarizeWorkspaceCleanupRun,
|
||||
workspaceCleanupRowDetails
|
||||
} from './workspace-cleanup-run-summary'
|
||||
import {
|
||||
appendWorkspaceCleanupRun,
|
||||
readWorkspaceCleanupRunHistory
|
||||
@@ -39,7 +44,7 @@ const SETTINGS_DEBOUNCE_MS = 10 * 1000
|
||||
|
||||
type DecidedWorkspace = {
|
||||
workspace: WorkspaceCleanupWorkspace
|
||||
ref: WorkspaceCleanupWorkspaceRef & { sizeBytes?: number }
|
||||
ref: WorkspaceCleanupWorkspaceRef & WorkspaceCleanupRowDetails & { sizeBytes?: number }
|
||||
evaluation: WorkspaceCleanupEvaluation
|
||||
}
|
||||
|
||||
@@ -54,6 +59,8 @@ export type WorkspaceCleanupRunnerDeps = {
|
||||
export class WorkspaceCleanupRunner {
|
||||
private readonly deps: WorkspaceCleanupRunnerDeps
|
||||
private current: Promise<WorkspaceCleanupRun> | null = null
|
||||
// Every caller asking for the same rules while one evaluation runs shares it: reopened pages, several clients.
|
||||
private readonly previews = new Map<string, Promise<WorkspaceCleanupPreview>>()
|
||||
private timer: ReturnType<typeof setTimeout> | null = null
|
||||
private nextRunAt: number | null = null
|
||||
private enabledRules = new Set<string>()
|
||||
@@ -107,9 +114,28 @@ export class WorkspaceCleanupRunner {
|
||||
}
|
||||
|
||||
/** What a run would do now, removing nothing; `rules` previews other global rules. */
|
||||
async preview(rules?: WorkspaceCleanupRules): Promise<WorkspaceCleanupPreview> {
|
||||
preview(rules?: WorkspaceCleanupRules): Promise<WorkspaceCleanupPreview> {
|
||||
const effective = rules ?? this.globalRules()
|
||||
const key = JSON.stringify(effective)
|
||||
const shared = this.previews.get(key)
|
||||
if (shared) {
|
||||
return shared
|
||||
}
|
||||
const evaluation = this.evaluatePreview(effective)
|
||||
this.previews.set(key, evaluation)
|
||||
void evaluation
|
||||
.catch(() => undefined)
|
||||
.finally(() => {
|
||||
if (this.previews.get(key) === evaluation) {
|
||||
this.previews.delete(key)
|
||||
}
|
||||
})
|
||||
return evaluation
|
||||
}
|
||||
|
||||
private async evaluatePreview(rules: WorkspaceCleanupRules): Promise<WorkspaceCleanupPreview> {
|
||||
const evaluatedAt = Date.now()
|
||||
const decided = await this.evaluate(rules ?? this.globalRules(), evaluatedAt)
|
||||
const decided = await this.evaluate(rules, evaluatedAt)
|
||||
return { evaluatedAt, rows: decided.map(({ ref, evaluation }) => ({ ...ref, evaluation })) }
|
||||
}
|
||||
|
||||
@@ -193,7 +219,11 @@ export class WorkspaceCleanupRunner {
|
||||
const sizeBytes = sizes.get(workspace.ref.worktreeId)
|
||||
decided.push({
|
||||
workspace,
|
||||
ref: { ...workspace.ref, ...(sizeBytes !== undefined ? { sizeBytes } : {}) },
|
||||
ref: {
|
||||
...workspace.ref,
|
||||
...workspaceCleanupRowDetails(workspace.input),
|
||||
...(sizeBytes !== undefined ? { sizeBytes } : {})
|
||||
},
|
||||
evaluation: await decideWorkspaceCleanup(this.deps.runtime, workspace, now)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
WorkspaceSpaceScanProgress
|
||||
} from '../../../shared/workspace-disk-space/workspace-space-types'
|
||||
import type { ExecutionHostId } from '../../../shared/execution-host'
|
||||
import type { WorkspaceCleanupRunFinishedEvent } from '../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
import type { WorkspaceSpaceChange } from '../../../shared/workspace-disk-space/workspace-space-change'
|
||||
|
||||
export type WorkspaceCleanupApi = {
|
||||
@@ -27,6 +28,8 @@ export type WorkspaceCleanupApi = {
|
||||
beginRemovalSnapshotPruneBatch?: (args: WorkspaceCleanupSnapshotPruneBatchArgs) => Promise<void>
|
||||
recordRemovalSnapshotPrune?: (args: WorkspaceCleanupSnapshotPruneRecordArgs) => Promise<void>
|
||||
finishRemovalSnapshotPruneBatch?: (args: WorkspaceCleanupSnapshotPruneBatchArgs) => Promise<void>
|
||||
/** This app's own cleanup runner finished a run. */
|
||||
onRunFinished: (callback: (run: WorkspaceCleanupRunFinishedEvent['run']) => void) => () => void
|
||||
}
|
||||
|
||||
export type WorkspaceSpaceApi = {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { ipcRenderer } from 'electron'
|
||||
import type { WorkspaceCleanupScanProgress } from '../../../shared/workspace-cleanup/workspace-cleanup'
|
||||
import type { WorkspaceCleanupRunFinishedEvent } from '../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
import type { PreloadApi } from '../../api-types'
|
||||
|
||||
export const workspaceCleanupApi = {
|
||||
@@ -30,5 +31,13 @@ export const workspaceCleanupApi = {
|
||||
recordRemovalSnapshotPrune: (args) =>
|
||||
ipcRenderer.invoke('workspaceCleanup:recordRemovalSnapshotPrune', args),
|
||||
finishRemovalSnapshotPruneBatch: (args) =>
|
||||
ipcRenderer.invoke('workspaceCleanup:finishRemovalSnapshotPruneBatch', args)
|
||||
ipcRenderer.invoke('workspaceCleanup:finishRemovalSnapshotPruneBatch', args),
|
||||
onRunFinished: (callback) => {
|
||||
const listener = (
|
||||
_event: Electron.IpcRendererEvent,
|
||||
run: WorkspaceCleanupRunFinishedEvent['run']
|
||||
): void => callback(run)
|
||||
ipcRenderer.on('workspaceCleanup:runFinished', listener)
|
||||
return () => ipcRenderer.removeListener('workspaceCleanup:runFinished', listener)
|
||||
}
|
||||
} satisfies PreloadApi['workspaceCleanup']
|
||||
|
||||
@@ -253,7 +253,7 @@ type ColorFieldProps = {
|
||||
|
||||
type NumberFieldProps = {
|
||||
label: string
|
||||
description: string
|
||||
description?: string
|
||||
/** undefined renders the field empty — pair it with `placeholder` and `onClear` for an unset state. */
|
||||
value: number | undefined
|
||||
defaultValue?: number
|
||||
@@ -369,15 +369,17 @@ export function NumberField({
|
||||
className={className}
|
||||
label={label}
|
||||
description={
|
||||
<>
|
||||
{description}
|
||||
{defaultValue !== undefined ? (
|
||||
<span className="ml-1 text-muted-foreground/70">
|
||||
{t('auto.components.settings.SettingsFormControls.b661b034ec', '· Default:')}{' '}
|
||||
{defaultValue}
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
description || defaultValue !== undefined ? (
|
||||
<>
|
||||
{description}
|
||||
{defaultValue !== undefined ? (
|
||||
<span className="ml-1 text-muted-foreground/70">
|
||||
{t('auto.components.settings.SettingsFormControls.b661b034ec', '· Default:')}{' '}
|
||||
{defaultValue}
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
) : undefined
|
||||
}
|
||||
control={
|
||||
<div className="flex items-center gap-2">
|
||||
|
||||
@@ -15,6 +15,7 @@ export type SettingsNavInstallStatus =
|
||||
|
||||
const SETTINGS_NAV_TARGETS = [
|
||||
'general',
|
||||
'workspace-cleanup',
|
||||
'integrations',
|
||||
'accounts',
|
||||
'browser',
|
||||
|
||||
@@ -25,7 +25,8 @@ import {
|
||||
renderMobileSettingsSection,
|
||||
renderOrcaAccountSettingsSection,
|
||||
renderSetupGuideSettingsSection,
|
||||
renderShareSkillsSettingsSection
|
||||
renderShareSkillsSettingsSection,
|
||||
renderWorkspaceCleanupSettingsSection
|
||||
} from './settings-setup-workflow-section-renderers'
|
||||
import {
|
||||
renderGitSettingsSection,
|
||||
@@ -169,6 +170,7 @@ export function renderSettingsPage(
|
||||
{renderOrcaAccountSettingsSection(context, t)}
|
||||
{renderSetupGuideSettingsSection(context, t)}
|
||||
{renderGeneralSettingsSection(context, t)}
|
||||
{renderWorkspaceCleanupSettingsSection(context, t)}
|
||||
{renderIntegrationsSettingsSection(context, t)}
|
||||
{renderMobileSettingsSection(context, t)}
|
||||
{renderAutomationsSettingsSection(context, t)}
|
||||
|
||||
+31
@@ -13,6 +13,8 @@ import { translate } from '@/i18n/i18n'
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import type { SettingsRenderContext } from './settings-render-context'
|
||||
import { SettingsGroup } from '../section-layout/SettingsGroup'
|
||||
import { WorkspaceCleanupSettingsPane } from '../workspace-cleanup/WorkspaceCleanupSettingsPane'
|
||||
import { runtimeTargetEnvironmentId } from '@/runtime/rpc/targets/runtime-client-target'
|
||||
|
||||
export function renderOrcaAccountSettingsSection(
|
||||
context: SettingsRenderContext,
|
||||
@@ -236,3 +238,32 @@ export function renderSessionHistorySettingsSection(
|
||||
</SettingsSection>
|
||||
)
|
||||
}
|
||||
|
||||
export function renderWorkspaceCleanupSettingsSection(
|
||||
context: SettingsRenderContext,
|
||||
t: Translate = translate
|
||||
): React.JSX.Element | null {
|
||||
const { model, navigation, view } = context
|
||||
// A paired browser's settings are its own; the cleanup rules live on the host it pairs with.
|
||||
return model.showDesktopOnlySettings ? (
|
||||
<SettingsSection
|
||||
id="workspace-cleanup"
|
||||
title={t('components.settings.workspaceCleanup.title', 'Workspace Cleanup')}
|
||||
description={t(
|
||||
'components.settings.workspaceCleanup.description',
|
||||
"Remove workspaces you're done with. Before removing anything, Orca checks again for unsaved work."
|
||||
)}
|
||||
searchEntries={navigation.getSectionSearchEntries('workspace-cleanup')}
|
||||
>
|
||||
{view.isSectionMounted('workspace-cleanup') ? (
|
||||
<WorkspaceCleanupSettingsPane
|
||||
// A change waiting on its preview belongs to the host it was made for.
|
||||
key={runtimeTargetEnvironmentId(model.settingsHostScope.target) ?? 'local'}
|
||||
hostScope={model.settingsHostScope}
|
||||
settings={model.settings}
|
||||
updateSettings={model.updateSettingsOrThrow}
|
||||
/>
|
||||
) : null}
|
||||
</SettingsSection>
|
||||
) : null
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import { SETTINGS_GROUP_NESTED_INSET_CLASS } from './SettingsGroup'
|
||||
|
||||
type SettingsGroupDisclosureProps = {
|
||||
label?: string
|
||||
/** A muted hint after the label naming what the disclosure holds. */
|
||||
description?: string
|
||||
forceOpen?: boolean
|
||||
children: React.ReactNode
|
||||
}
|
||||
@@ -15,6 +17,7 @@ type SettingsGroupDisclosureProps = {
|
||||
/** Collapsible rows inside a SettingsGroup card, one fixed step in from the card's rows. Search force-opens it so matches remain reachable. */
|
||||
export function SettingsGroupDisclosure({
|
||||
label,
|
||||
description,
|
||||
forceOpen = false,
|
||||
children
|
||||
}: SettingsGroupDisclosureProps): React.JSX.Element {
|
||||
@@ -40,6 +43,9 @@ export function SettingsGroupDisclosure({
|
||||
)}
|
||||
/>
|
||||
{label ?? t('auto.components.settings.AppearanceAdvancedDisclosure.advanced', 'Advanced')}
|
||||
{description ? (
|
||||
<span className="truncate text-xs font-normal text-muted-foreground">{description}</span>
|
||||
) : null}
|
||||
</button>
|
||||
{/* Stays mounted while collapsed so a settings jump can find and reveal its rows. */}
|
||||
<div hidden={!expanded} className={SETTINGS_GROUP_NESTED_INSET_CLASS}>
|
||||
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
import { useMemo, useRef, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { useAppStore } from '@/store'
|
||||
import { useAppStateValue } from '@/store/retained-views/app-state-view'
|
||||
import { getRuntimeTargetHostId } from '@/runtime/rpc/targets/runtime-client-target'
|
||||
import type { GlobalSettings } from '../../../../../shared/global-settings-types'
|
||||
import { LOCAL_EXECUTION_HOST_ID } from '../../../../../shared/execution-host'
|
||||
import { errorMessage } from '../../../../../shared/error-message'
|
||||
import {
|
||||
WORKSPACE_CLEANUP_RULE_KEYS,
|
||||
hasEnabledWorkspaceCleanupRule,
|
||||
type WorkspaceCleanupRules
|
||||
} from '../../../../../shared/workspace-cleanup/workspace-cleanup-policy'
|
||||
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 {
|
||||
WorkspaceCleanupRuleRows,
|
||||
type WorkspaceCleanupRuleMatches
|
||||
} from './workspace-cleanup-rule-rows'
|
||||
import {
|
||||
WORKSPACE_CLEANUP_RULE_REASON,
|
||||
setWorkspaceCleanupRuleEnabled,
|
||||
type WorkspaceCleanupRuleKey
|
||||
} from './workspace-cleanup-rule-keys'
|
||||
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<Record<WorkspaceCleanupRuleKey, WorkspaceCleanupRuleMatches>> | undefined {
|
||||
if (!preview) {
|
||||
return undefined
|
||||
}
|
||||
const matches: Partial<Record<WorkspaceCleanupRuleKey, WorkspaceCleanupRuleMatches>> = {}
|
||||
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
|
||||
}
|
||||
|
||||
type RulesChange = (rules: WorkspaceCleanupRules) => WorkspaceCleanupRules
|
||||
|
||||
type PendingChange = WorkspaceCleanupRuleChangeRequest & { change: RulesChange }
|
||||
|
||||
export function WorkspaceCleanupSettingsPane({
|
||||
hostScope,
|
||||
settings,
|
||||
updateSettings
|
||||
}: {
|
||||
hostScope: SettingsHostScope
|
||||
settings: GlobalSettings | null
|
||||
updateSettings: (updates: Partial<GlobalSettings>) => Promise<void> | void
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const owner = hostScope.target
|
||||
const query = useAppStateValue((state) => state.settingsSearchQuery)
|
||||
const updateWorktreeMeta = useAppStore((state) => state.updateWorktreeMeta)
|
||||
const { hostRules, readLatest, reload, update } = useWorkspaceCleanupHostRules(
|
||||
owner,
|
||||
settings,
|
||||
updateSettings
|
||||
)
|
||||
const rules = hostRules.state === 'ready' ? hostRules.rules : null
|
||||
const { hostReport, preview, cleaningUp, cleanUpNow, previewRules, cachedPreview, adoptPreview } =
|
||||
useWorkspaceCleanupHostActivity(owner, rules)
|
||||
const matches = useMemo(() => summarizeMatches(preview), [preview])
|
||||
const [pendingRule, setPendingRule] = useState<WorkspaceCleanupRuleKey | null>(null)
|
||||
const [pendingChange, setPendingChange] = useState<PendingChange | null>(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 [unsavedChanges, setUnsavedChanges] = useState(0)
|
||||
const search = getWorkspaceCleanupSettingsSearchParts()
|
||||
|
||||
if (!hostScope.available) {
|
||||
return <SettingsHostScopeUnavailableNotice />
|
||||
}
|
||||
if (hostRules.state === 'unsupported' || hostReport.state === 'unsupported') {
|
||||
return (
|
||||
<p className="px-1 text-sm text-muted-foreground">
|
||||
{t(
|
||||
'components.settings.workspaceCleanup.unsupportedHost',
|
||||
'This host runs an Orca version without automatic cleanup. Update Orca on it to use these settings.'
|
||||
)}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
if (hostRules.state === 'error') {
|
||||
return (
|
||||
<p className="px-1 text-sm text-muted-foreground">
|
||||
{t(
|
||||
'components.settings.workspaceCleanup.rulesLoadFailed',
|
||||
"Couldn't load this host's cleanup rules: {{error}}",
|
||||
{ error: hostRules.message }
|
||||
)}{' '}
|
||||
<button
|
||||
type="button"
|
||||
onClick={reload}
|
||||
className="underline decoration-muted-foreground/50 underline-offset-4 hover:text-foreground"
|
||||
>
|
||||
{t('components.settings.workspaceCleanup.retry', 'Try again')}
|
||||
</button>
|
||||
</p>
|
||||
)
|
||||
}
|
||||
if (!rules) {
|
||||
return null
|
||||
}
|
||||
const currentRules = rules
|
||||
|
||||
const finishChange = (saved: boolean): void => {
|
||||
busyRef.current = false
|
||||
setBusy(false)
|
||||
setPendingRule(null)
|
||||
if (!saved) {
|
||||
setUnsavedChanges((count) => count + 1)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The runner acts within seconds of a rule change, so a change that would delete more asks first.
|
||||
* `request` is null for a change that can only delete less, such as turning a rule off.
|
||||
*/
|
||||
const applyRules = async (
|
||||
change: RulesChange,
|
||||
request: Omit<WorkspaceCleanupRuleChangeRequest, 'rows'> | null,
|
||||
pendingKey: WorkspaceCleanupRuleKey | null = null
|
||||
): Promise<void> => {
|
||||
if (busyRef.current) {
|
||||
return
|
||||
}
|
||||
busyRef.current = true
|
||||
setBusy(true)
|
||||
setPendingRule(pendingKey)
|
||||
// Another client may have changed the rules since this page read them.
|
||||
const latest = await readLatest()
|
||||
if (!mountedRef.current) {
|
||||
return
|
||||
}
|
||||
if (!latest) {
|
||||
finishChange(false)
|
||||
return
|
||||
}
|
||||
const nextRules = change(latest)
|
||||
const checked =
|
||||
request && hasEnabledWorkspaceCleanupRule(nextRules)
|
||||
? await previewNewRemovals(latest, nextRules)
|
||||
: { rows: [], nextPreview: null }
|
||||
if (!mountedRef.current) {
|
||||
return
|
||||
}
|
||||
if (!checked) {
|
||||
finishChange(false)
|
||||
return
|
||||
}
|
||||
if (request && checked.rows.length > 0) {
|
||||
setPendingRule(null)
|
||||
setPendingChange({ ...request, rows: checked.rows, change })
|
||||
return
|
||||
}
|
||||
finishChange(await saveRules(nextRules, checked.nextPreview))
|
||||
}
|
||||
|
||||
// The would-be rules' preview becomes the page's matches only once those rules are saved.
|
||||
const saveRules = async (
|
||||
nextRules: WorkspaceCleanupRules,
|
||||
nextPreview: WorkspaceCleanupPreview | null
|
||||
): Promise<boolean> => {
|
||||
const saved = await update(nextRules)
|
||||
if (saved && nextPreview) {
|
||||
adoptPreview(nextRules, nextPreview)
|
||||
}
|
||||
return saved
|
||||
}
|
||||
|
||||
/** Null when the preview failed; the toast says so. */
|
||||
const previewNewRemovals = async (
|
||||
latest: WorkspaceCleanupRules,
|
||||
nextRules: WorkspaceCleanupRules
|
||||
): Promise<{
|
||||
rows: WorkspaceCleanupPreviewRow[]
|
||||
nextPreview: WorkspaceCleanupPreview
|
||||
} | null> => {
|
||||
// Project rules can delete with every global rule off, so the current rules are always read,
|
||||
// from the page's own preview when it already covers them.
|
||||
const previews = await Promise.all([
|
||||
previewRules(nextRules),
|
||||
cachedPreview(latest) ?? previewRules(latest)
|
||||
]).catch((error: unknown) => {
|
||||
toast.error(
|
||||
t(
|
||||
'components.settings.workspaceCleanup.previewFailed',
|
||||
"Couldn't check which workspaces this change matches."
|
||||
),
|
||||
{ description: errorMessage(error) }
|
||||
)
|
||||
return null
|
||||
})
|
||||
return previews
|
||||
? { rows: newRemovals(previews[0], previews[1]), nextPreview: previews[0] }
|
||||
: null
|
||||
}
|
||||
|
||||
const toggleRule = (key: WorkspaceCleanupRuleKey): void => {
|
||||
const enabled = !currentRules[key].enabled
|
||||
void applyRules(
|
||||
(latest) => setWorkspaceCleanupRuleEnabled(latest, key, enabled),
|
||||
enabled ? { kind: 'enable', ruleTitle: search[key].title } : null,
|
||||
key
|
||||
)
|
||||
}
|
||||
|
||||
const cancelChange = (): void => {
|
||||
setPendingChange(null)
|
||||
finishChange(false)
|
||||
}
|
||||
|
||||
const confirmChange = async (keep: WorkspaceCleanupPreviewRow[]): Promise<void> => {
|
||||
const change = pendingChange
|
||||
if (!change) {
|
||||
return
|
||||
}
|
||||
// The dialog can stay open a while: the rules may have moved, or a workspace aged past a rule.
|
||||
const latest = await readLatest()
|
||||
if (!latest || !mountedRef.current) {
|
||||
return
|
||||
}
|
||||
const nextRules = change.change(latest)
|
||||
const checked = await previewNewRemovals(latest, nextRules)
|
||||
if (!checked || !mountedRef.current) {
|
||||
return
|
||||
}
|
||||
const listed = new Set(change.rows.map(workspaceCleanupRowKey))
|
||||
if (checked.rows.some((row) => !listed.has(workspaceCleanupRowKey(row)))) {
|
||||
setPendingChange({ ...change, rows: checked.rows })
|
||||
return
|
||||
}
|
||||
// Pinned workspaces are always kept, so Keep is a pin rather than a second keep list.
|
||||
for (const row of keep) {
|
||||
const result = await updateWorktreeMeta(
|
||||
row.worktreeId,
|
||||
{ isPinned: true },
|
||||
{
|
||||
executionHostId:
|
||||
owner.kind === 'environment'
|
||||
? getRuntimeTargetHostId(owner)
|
||||
: (row.executionHostId ?? LOCAL_EXECUTION_HOST_ID)
|
||||
}
|
||||
)
|
||||
if (!result.ok) {
|
||||
toast.error(
|
||||
t('components.settings.workspaceCleanup.pinFailed', "Couldn't keep {{name}}.", {
|
||||
name: row.displayName
|
||||
}),
|
||||
{ description: result.error }
|
||||
)
|
||||
return
|
||||
}
|
||||
}
|
||||
if (!mountedRef.current) {
|
||||
return
|
||||
}
|
||||
if (await saveRules(nextRules, checked.nextPreview)) {
|
||||
setPendingChange(null)
|
||||
finishChange(true)
|
||||
}
|
||||
}
|
||||
|
||||
const hasQuery = query.trim() !== ''
|
||||
const showRules = matchesSettingsSearch(query, [
|
||||
search.merged,
|
||||
search.unchanged,
|
||||
search.inactive,
|
||||
search.automationRuns,
|
||||
search.orchestrationWorkers
|
||||
])
|
||||
const showProtection = matchesSettingsSearch(query, [search.keepIgnoredFiles])
|
||||
const showActivity = matchesSettingsSearch(query, [search.activity])
|
||||
const report = hostReport.state === 'ready' ? hostReport.report : null
|
||||
|
||||
return (
|
||||
<>
|
||||
<WorkspaceCleanupSettingsStatus
|
||||
// A project's own rules can keep the runner scheduled while every global rule is off.
|
||||
anyRuleOn={hasEnabledWorkspaceCleanupRule(currentRules) || Boolean(report?.nextRunAt)}
|
||||
report={report}
|
||||
readAt={hostReport.state === 'ready' ? hostReport.readAt : 0}
|
||||
cleaningUp={cleaningUp}
|
||||
onCleanUpNow={() => void cleanUpNow()}
|
||||
/>
|
||||
{showRules ? (
|
||||
<div className="space-y-3">
|
||||
<SettingsGroup title={t('components.settings.workspaceCleanup.rules.title', 'Rules')}>
|
||||
<WorkspaceCleanupRuleRows
|
||||
key={unsavedChanges}
|
||||
rules={currentRules}
|
||||
matches={matches}
|
||||
pendingRule={pendingRule}
|
||||
disabled={busy}
|
||||
onToggle={toggleRule}
|
||||
onChange={(change) =>
|
||||
void applyRules(
|
||||
change,
|
||||
{ kind: 'change', ruleTitle: search.inactive.title },
|
||||
'inactive'
|
||||
)
|
||||
}
|
||||
/>
|
||||
</SettingsGroup>
|
||||
{hasQuery ? null : (
|
||||
<p className="px-1 text-xs text-muted-foreground">
|
||||
{t(
|
||||
'components.settings.workspaceCleanup.rules.branchNote',
|
||||
'Merged branches are deleted with their workspace. Unmerged branches are kept.'
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
{showProtection ? (
|
||||
<SettingsGroup
|
||||
title={t('components.settings.workspaceCleanup.protection.title', 'Protection')}
|
||||
description={t(
|
||||
'components.settings.workspaceCleanup.protection.alwaysKept',
|
||||
'Always kept: pinned workspaces, running agents or terminals, unsaved editor changes, uncommitted changes, unpushed commits.'
|
||||
)}
|
||||
>
|
||||
<SearchableSetting {...search.keepIgnoredFiles}>
|
||||
<SettingsSwitchRow
|
||||
label={search.keepIgnoredFiles.title}
|
||||
description={search.keepIgnoredFiles.description}
|
||||
checked={currentRules.keepWhen === 'any-local-files'}
|
||||
disabled={busy}
|
||||
onChange={() => {
|
||||
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: 'change', ruleTitle: search.keepIgnoredFiles.title }
|
||||
)
|
||||
}}
|
||||
/>
|
||||
</SearchableSetting>
|
||||
</SettingsGroup>
|
||||
) : null}
|
||||
{showActivity ? (
|
||||
<SettingsGroup
|
||||
title={search.activity.title}
|
||||
description={
|
||||
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."
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{report && report.runs.length > 0 ? (
|
||||
<WorkspaceCleanupActivityList runs={report.runs} />
|
||||
) : null}
|
||||
</SettingsGroup>
|
||||
) : null}
|
||||
<WorkspaceCleanupRuleChangeDialog
|
||||
request={pendingChange}
|
||||
onCancel={cancelChange}
|
||||
onConfirm={confirmChange}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call'
|
||||
import {
|
||||
runtimeTargetEnvironmentId,
|
||||
runtimeTargetForOwnerEnvironment
|
||||
} from '@/runtime/rpc/targets/runtime-client-target'
|
||||
import { onWorkspaceCleanupRunFinished } from '@/components/workspace-cleanup/events/workspace-cleanup-run-finished-window-event'
|
||||
import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target'
|
||||
import { hasRuntimeRpcErrorCode } from '../../../../../shared/runtime-rpc-error-code'
|
||||
import { errorMessage } from '../../../../../shared/error-message'
|
||||
import {
|
||||
hasEnabledWorkspaceCleanupRule,
|
||||
type WorkspaceCleanupRules
|
||||
} from '../../../../../shared/workspace-cleanup/workspace-cleanup-policy'
|
||||
import type {
|
||||
WorkspaceCleanupPreview,
|
||||
WorkspaceCleanupReport
|
||||
} from '../../../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
|
||||
// The host reads Git state for every workspace before it answers; matches the CLI's wait.
|
||||
const EVALUATE_TIMEOUT_MS = 10 * 60 * 1000
|
||||
const REPORT_TIMEOUT_MS = 30_000
|
||||
|
||||
export type WorkspaceCleanupHostReport =
|
||||
| { state: 'loading' }
|
||||
| { state: 'unsupported' }
|
||||
| { state: 'error'; message: string }
|
||||
/** `readAt` is when the report was read; relative times are shown as of then. */
|
||||
| { state: 'ready'; report: WorkspaceCleanupReport; readAt: number }
|
||||
|
||||
/** What the selected host's runner did and would do now; refreshed when it finishes a run. */
|
||||
export function useWorkspaceCleanupHostActivity(
|
||||
owner: RuntimeClientTarget,
|
||||
rules: WorkspaceCleanupRules | null
|
||||
): {
|
||||
hostReport: WorkspaceCleanupHostReport
|
||||
/** What the host's current rules match now; null until read or while no rule is on. */
|
||||
preview: WorkspaceCleanupPreview | null
|
||||
cleaningUp: boolean
|
||||
cleanUpNow: () => Promise<void>
|
||||
previewRules: (rules: WorkspaceCleanupRules) => Promise<WorkspaceCleanupPreview>
|
||||
/** The page's own preview when it already evaluated exactly these rules, so callers skip a host scan. */
|
||||
cachedPreview: (rules: WorkspaceCleanupRules) => WorkspaceCleanupPreview | null
|
||||
/** Makes a preview of rules that were just saved the page's matches, instead of scanning them again. */
|
||||
adoptPreview: (rules: WorkspaceCleanupRules, preview: WorkspaceCleanupPreview) => void
|
||||
} {
|
||||
const t = useTranslate()
|
||||
const environmentId = runtimeTargetEnvironmentId(owner)
|
||||
const ownerKey = environmentId ?? 'local'
|
||||
const rulesKey = rules ? JSON.stringify(rules) : null
|
||||
const anyRuleOn = rules ? hasEnabledWorkspaceCleanupRule(rules) : false
|
||||
const [reportState, setReportState] = useState<{
|
||||
ownerKey: string
|
||||
hostReport: WorkspaceCleanupHostReport
|
||||
} | null>(null)
|
||||
// Keyed by the rules it evaluated, so a rule change never shows the old rules' matches.
|
||||
const [previewState, setPreviewState] = useState<{
|
||||
ownerKey: string
|
||||
rulesKey: string
|
||||
revision: number
|
||||
preview: WorkspaceCleanupPreview
|
||||
} | null>(null)
|
||||
const [cleaningUp, setCleaningUp] = useState(false)
|
||||
const [revision, setRevision] = useState(0)
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
onWorkspaceCleanupRunFinished((detail) => {
|
||||
if ((detail.environmentId ?? 'local') === ownerKey) {
|
||||
setRevision((value) => value + 1)
|
||||
}
|
||||
}),
|
||||
[ownerKey]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
// Read once the rules are in: their arrival would otherwise read the report a second time.
|
||||
if (!rulesKey) {
|
||||
return
|
||||
}
|
||||
let current = true
|
||||
const target = runtimeTargetForOwnerEnvironment(environmentId)
|
||||
void callRuntimeRpc<WorkspaceCleanupReport>(target, 'workspaceCleanup.report', undefined, {
|
||||
timeoutMs: REPORT_TIMEOUT_MS
|
||||
}).then(
|
||||
(report) => {
|
||||
if (current) {
|
||||
setReportState({ ownerKey, hostReport: { state: 'ready', report, readAt: Date.now() } })
|
||||
}
|
||||
},
|
||||
(error: unknown) => {
|
||||
if (current) {
|
||||
setReportState({
|
||||
ownerKey,
|
||||
hostReport: hasRuntimeRpcErrorCode(error, 'method_not_found')
|
||||
? { state: 'unsupported' }
|
||||
: { state: 'error', message: errorMessage(error) }
|
||||
})
|
||||
}
|
||||
}
|
||||
)
|
||||
return () => {
|
||||
current = false
|
||||
}
|
||||
// A rule change reschedules the next run, so the report is read again with the rules.
|
||||
}, [environmentId, ownerKey, rulesKey, revision])
|
||||
|
||||
const previewIsCurrent =
|
||||
previewState?.ownerKey === ownerKey &&
|
||||
previewState.rulesKey === rulesKey &&
|
||||
previewState.revision === revision
|
||||
useEffect(() => {
|
||||
// A rule change already previewed its rules before saving them.
|
||||
if (!anyRuleOn || !rulesKey || previewIsCurrent) {
|
||||
return
|
||||
}
|
||||
let current = true
|
||||
const target = runtimeTargetForOwnerEnvironment(environmentId)
|
||||
void callRuntimeRpc<WorkspaceCleanupPreview>(
|
||||
target,
|
||||
'workspaceCleanup.preview',
|
||||
{},
|
||||
{
|
||||
timeoutMs: EVALUATE_TIMEOUT_MS
|
||||
}
|
||||
).then(
|
||||
(preview) => {
|
||||
if (current) {
|
||||
setPreviewState({ ownerKey, rulesKey, revision, preview })
|
||||
}
|
||||
},
|
||||
(error: unknown) => console.warn('[workspace-cleanup] preview failed', error)
|
||||
)
|
||||
return () => {
|
||||
current = false
|
||||
}
|
||||
}, [anyRuleOn, environmentId, ownerKey, rulesKey, revision, previewIsCurrent])
|
||||
|
||||
const cleanUpNow = useCallback(async () => {
|
||||
setCleaningUp(true)
|
||||
try {
|
||||
await callRuntimeRpc(
|
||||
owner,
|
||||
'workspaceCleanup.runNow',
|
||||
{ trigger: 'run-now' },
|
||||
{
|
||||
timeoutMs: EVALUATE_TIMEOUT_MS
|
||||
}
|
||||
)
|
||||
} catch (error) {
|
||||
toast.error(t('components.settings.workspaceCleanup.runFailed', "Couldn't run cleanup."), {
|
||||
description: errorMessage(error)
|
||||
})
|
||||
}
|
||||
// The host's finished-run event refreshes the report and the matches.
|
||||
setCleaningUp(false)
|
||||
}, [owner, t])
|
||||
|
||||
const previewRules = useCallback(
|
||||
(nextRules: WorkspaceCleanupRules): Promise<WorkspaceCleanupPreview> =>
|
||||
callRuntimeRpc<WorkspaceCleanupPreview>(
|
||||
owner,
|
||||
'workspaceCleanup.preview',
|
||||
{ rules: nextRules },
|
||||
{ timeoutMs: EVALUATE_TIMEOUT_MS }
|
||||
),
|
||||
[owner]
|
||||
)
|
||||
|
||||
return {
|
||||
hostReport: reportState?.ownerKey === ownerKey ? reportState.hostReport : { state: 'loading' },
|
||||
preview:
|
||||
anyRuleOn && previewState?.ownerKey === ownerKey && previewState.rulesKey === rulesKey
|
||||
? previewState.preview
|
||||
: null,
|
||||
cleaningUp,
|
||||
cleanUpNow,
|
||||
previewRules,
|
||||
cachedPreview: (candidate) =>
|
||||
previewIsCurrent && previewState?.rulesKey === JSON.stringify(candidate)
|
||||
? previewState.preview
|
||||
: null,
|
||||
adoptPreview: (savedRules, preview) =>
|
||||
setPreviewState({ ownerKey, rulesKey: JSON.stringify(savedRules), revision, preview })
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { callRuntimeRpc } from '@/runtime/rpc/calls/runtime-rpc-call'
|
||||
import type { GlobalSettings } from '../../../../../shared/global-settings-types'
|
||||
import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target'
|
||||
import {
|
||||
getDefaultWorkspaceCleanupRules,
|
||||
normalizeWorkspaceCleanupRules,
|
||||
type WorkspaceCleanupRules
|
||||
} from '../../../../../shared/workspace-cleanup/workspace-cleanup-policy'
|
||||
import { errorMessage } from '../../../../../shared/error-message'
|
||||
|
||||
/** `unsupported`: a host from before automatic cleanup, which neither reports nor accepts the rules. */
|
||||
export type WorkspaceCleanupHostRules =
|
||||
| { state: 'loading' }
|
||||
| { state: 'unsupported' }
|
||||
| { state: 'error'; message: string }
|
||||
| { state: 'ready'; rules: WorkspaceCleanupRules }
|
||||
|
||||
type HostSettings = { settings: Partial<GlobalSettings> }
|
||||
|
||||
const HOST_SETTINGS_TIMEOUT_MS = 15_000
|
||||
|
||||
function readHostRules(settings: Partial<GlobalSettings>): WorkspaceCleanupHostRules {
|
||||
// Newer hosts always report the key; an older one would reject the strict settings.update.
|
||||
return settings.workspaceCleanupPolicy
|
||||
? { state: 'ready', rules: normalizeWorkspaceCleanupRules(settings.workspaceCleanupPolicy) }
|
||||
: { state: 'unsupported' }
|
||||
}
|
||||
|
||||
function readEnvironmentRules(environmentId: string): Promise<WorkspaceCleanupHostRules> {
|
||||
return callRuntimeRpc<HostSettings>(
|
||||
{ kind: 'environment', environmentId },
|
||||
'settings.get',
|
||||
undefined,
|
||||
{
|
||||
timeoutMs: HOST_SETTINGS_TIMEOUT_MS
|
||||
}
|
||||
).then(
|
||||
(result) => readHostRules(result.settings),
|
||||
(error: unknown): WorkspaceCleanupHostRules => ({
|
||||
state: 'error',
|
||||
message: errorMessage(error)
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
/** The rules belong to the host that owns the repos, so this reads and writes that host's settings. */
|
||||
export function useWorkspaceCleanupHostRules(
|
||||
owner: RuntimeClientTarget,
|
||||
localSettings: Pick<GlobalSettings, 'workspaceCleanupPolicy'> | null,
|
||||
updateLocalSettings: (updates: Partial<GlobalSettings>) => Promise<void> | void
|
||||
): {
|
||||
hostRules: WorkspaceCleanupHostRules
|
||||
/** The host's rules as they are now; another client may have changed them since the last read. */
|
||||
readLatest: () => Promise<WorkspaceCleanupRules | null>
|
||||
reload: () => void
|
||||
update: (rules: WorkspaceCleanupRules) => Promise<boolean>
|
||||
} {
|
||||
const t = useTranslate()
|
||||
const environmentId = owner.kind === 'environment' ? owner.environmentId : null
|
||||
const [remote, setRemote] = useState<{
|
||||
environmentId: string
|
||||
hostRules: WorkspaceCleanupHostRules
|
||||
} | null>(null)
|
||||
const [attempt, setAttempt] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
if (!environmentId) {
|
||||
return
|
||||
}
|
||||
let current = true
|
||||
void readEnvironmentRules(environmentId).then((hostRules) => {
|
||||
if (current) {
|
||||
setRemote({ environmentId, hostRules })
|
||||
}
|
||||
})
|
||||
return () => {
|
||||
current = false
|
||||
}
|
||||
}, [environmentId, attempt])
|
||||
|
||||
const reportFailure = (error: unknown): void => {
|
||||
toast.error(
|
||||
t('components.settings.workspaceCleanup.updateFailed', "Couldn't save the cleanup rules."),
|
||||
{ description: errorMessage(error) }
|
||||
)
|
||||
}
|
||||
const reload = (): void => setAttempt((value) => value + 1)
|
||||
|
||||
if (!environmentId) {
|
||||
const localRules = localSettings
|
||||
? (localSettings.workspaceCleanupPolicy ?? getDefaultWorkspaceCleanupRules())
|
||||
: null
|
||||
return {
|
||||
hostRules: localRules ? { state: 'ready', rules: localRules } : { state: 'loading' },
|
||||
// The store follows this app's settings as they change, so its copy is current.
|
||||
readLatest: () => Promise.resolve(localRules),
|
||||
reload,
|
||||
update: async (rules) => {
|
||||
try {
|
||||
await updateLocalSettings({ workspaceCleanupPolicy: rules })
|
||||
return true
|
||||
} catch (error) {
|
||||
reportFailure(error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
hostRules: remote?.environmentId === environmentId ? remote.hostRules : { state: 'loading' },
|
||||
readLatest: async () => {
|
||||
const hostRules = await readEnvironmentRules(environmentId)
|
||||
setRemote({ environmentId, hostRules })
|
||||
return hostRules.state === 'ready' ? hostRules.rules : null
|
||||
},
|
||||
reload,
|
||||
update: async (rules) => {
|
||||
try {
|
||||
const result = await callRuntimeRpc<HostSettings>(
|
||||
{ kind: 'environment', environmentId },
|
||||
'settings.update',
|
||||
{ workspaceCleanupPolicy: rules },
|
||||
{ timeoutMs: HOST_SETTINGS_TIMEOUT_MS }
|
||||
)
|
||||
setRemote({ environmentId, hostRules: readHostRules(result.settings) })
|
||||
return true
|
||||
} catch (error) {
|
||||
reportFailure(error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+334
@@ -0,0 +1,334 @@
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
Archive,
|
||||
ArrowUpFromLine,
|
||||
Bot,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
CircleHelp,
|
||||
CircleMinus,
|
||||
Clock,
|
||||
Eye,
|
||||
FileDiff,
|
||||
FileLock,
|
||||
FilePen,
|
||||
Loader,
|
||||
Pin,
|
||||
SquareTerminal,
|
||||
TriangleAlert,
|
||||
type LucideIcon
|
||||
} from 'lucide-react'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { uiDateTimeFormat } from '@/i18n/ui-intl-formatters'
|
||||
import { formatBytes } from '../../../../../shared/format-bytes'
|
||||
import type {
|
||||
WorkspaceCleanupRun,
|
||||
WorkspaceCleanupRunRow
|
||||
} from '../../../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
import { Button } from '../../ui/button'
|
||||
import { formatAtRiskLocalFileNames } from '@/lib/workspace/display/at-risk-local-files-label'
|
||||
import { WorkspaceCleanupMetadataText } from '@/components/workspace-cleanup/candidate-list/workspace-cleanup-metadata-chip'
|
||||
import type { WorkspaceCleanupKeepCause } from '../../../../../shared/workspace-cleanup/workspace-cleanup-evaluation'
|
||||
import { formatCleanupKeepCause, formatCleanupRunTrigger } from './workspace-cleanup-run-labels'
|
||||
import { WorkspaceCleanupReasonChip } from './workspace-cleanup-reason-chip'
|
||||
import {
|
||||
WorkspaceCleanupWorkspaceLine,
|
||||
workspaceCleanupRowKey
|
||||
} from './workspace-cleanup-workspace-line'
|
||||
|
||||
const KEPT_PREVIEW_COUNT = 4
|
||||
|
||||
const KEEP_CAUSE_ICONS: Partial<Record<WorkspaceCleanupKeepCause, LucideIcon>> = {
|
||||
pinned: Pin,
|
||||
'recently-active': Clock,
|
||||
'active-workspace': Eye,
|
||||
'agent-running': Bot,
|
||||
'terminal-running': SquareTerminal,
|
||||
'terminal-unknown': SquareTerminal,
|
||||
'unsaved-editor-changes': FilePen,
|
||||
'uncommitted-changes': FileDiff,
|
||||
'unpushed-commits': ArrowUpFromLine,
|
||||
'ignored-files': FileLock,
|
||||
'git-unknown': CircleHelp,
|
||||
'archive-unavailable': Archive,
|
||||
'archive-script': Archive,
|
||||
removing: Loader
|
||||
}
|
||||
const REMOVED_GRID = 'grid grid-cols-[minmax(0,1fr)_9rem_4.5rem_4rem] items-center gap-x-4'
|
||||
|
||||
/** Each run's receipt, newest first; the newest opens expanded. */
|
||||
export function WorkspaceCleanupActivityList({
|
||||
runs
|
||||
}: {
|
||||
runs: WorkspaceCleanupRun[]
|
||||
}): React.JSX.Element {
|
||||
// Only the newest run opens by default; a run the viewer toggled keeps its state.
|
||||
const [toggled, setToggled] = useState<ReadonlyMap<string, boolean>>(new Map())
|
||||
return (
|
||||
<>
|
||||
{runs.map((run, index) => (
|
||||
<ActivityRun
|
||||
key={run.id}
|
||||
run={run}
|
||||
open={toggled.get(run.id) ?? index === 0}
|
||||
onToggle={() =>
|
||||
setToggled((previous) =>
|
||||
new Map(previous).set(run.id, !(previous.get(run.id) ?? index === 0))
|
||||
)
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function ActivityRun({
|
||||
run,
|
||||
open,
|
||||
onToggle
|
||||
}: {
|
||||
run: WorkspaceCleanupRun
|
||||
open: boolean
|
||||
onToggle: () => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const removed = run.rows.filter((row) => row.outcome === 'removed' || row.outcome === 'archived')
|
||||
const kept = run.rows.filter((row) => row.outcome === 'kept')
|
||||
const failed = run.rows.filter((row) => row.outcome === 'failed')
|
||||
const removedCount = run.counts.removed + run.counts.archived
|
||||
const when = uiDateTimeFormat({
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit'
|
||||
}).format(run.startedAt)
|
||||
const Chevron = open ? ChevronDown : ChevronRight
|
||||
|
||||
return (
|
||||
<div data-settings-row="" className="py-3">
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={open}
|
||||
onClick={onToggle}
|
||||
className="flex w-full items-center gap-2 text-left"
|
||||
>
|
||||
<span className="flex size-4 shrink-0 items-center justify-center text-muted-foreground">
|
||||
<Chevron className="size-3.5" />
|
||||
</span>
|
||||
<span className="text-sm font-medium tabular-nums">{when}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatCleanupRunTrigger(run.trigger, t)}
|
||||
</span>
|
||||
<span className="ml-auto text-xs tabular-nums text-muted-foreground">
|
||||
{run.error ? (
|
||||
<span className="text-destructive">
|
||||
{t('components.settings.workspaceCleanup.activity.unfinished', "Couldn't finish")}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{removedCount === 0
|
||||
? t(
|
||||
'components.settings.workspaceCleanup.activity.nothingRemoved',
|
||||
'Nothing to clean'
|
||||
)
|
||||
: t(
|
||||
'components.settings.workspaceCleanup.activity.removedCount',
|
||||
'{{count}} removed',
|
||||
{
|
||||
count: removedCount
|
||||
}
|
||||
)}
|
||||
{', '}
|
||||
{t('components.settings.workspaceCleanup.activity.keptCount', '{{count}} kept', {
|
||||
count: run.counts.kept
|
||||
})}
|
||||
{run.counts.failed > 0 ? (
|
||||
<>
|
||||
{', '}
|
||||
<span className="text-destructive">
|
||||
{t(
|
||||
'components.settings.workspaceCleanup.activity.failedCount',
|
||||
'{{count}} failed',
|
||||
{
|
||||
count: run.counts.failed
|
||||
}
|
||||
)}
|
||||
</span>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="mt-1 pl-6">
|
||||
{run.error ? <ErrorLine message={run.error} /> : null}
|
||||
{removed.length > 0 ? (
|
||||
<>
|
||||
<GroupLabel>
|
||||
{t('components.settings.workspaceCleanup.activity.removed', 'Removed · {{count}}', {
|
||||
count: removedCount
|
||||
})}
|
||||
</GroupLabel>
|
||||
{removed.map((row) => (
|
||||
<RemovedRow key={workspaceCleanupRowKey(row)} row={row} />
|
||||
))}
|
||||
</>
|
||||
) : null}
|
||||
{kept.length > 0 ? <KeptRows rows={kept} total={run.counts.kept} /> : null}
|
||||
{failed.length > 0 ? (
|
||||
<>
|
||||
<GroupLabel>
|
||||
{t('components.settings.workspaceCleanup.activity.failed', 'Failed · {{count}}', {
|
||||
count: run.counts.failed
|
||||
})}
|
||||
</GroupLabel>
|
||||
{failed.map((row) => (
|
||||
<div key={workspaceCleanupRowKey(row)} className="min-w-0 py-1.5">
|
||||
<WorkspaceCleanupWorkspaceLine workspace={row} />
|
||||
{row.error ? <ErrorLine message={row.error} /> : null}
|
||||
</div>
|
||||
))}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function GroupLabel({ children }: { children: React.ReactNode }): React.JSX.Element {
|
||||
return <p className="pt-2 pb-0.5 text-xs font-medium text-muted-foreground">{children}</p>
|
||||
}
|
||||
|
||||
function ErrorLine({ message }: { message: string }): React.JSX.Element {
|
||||
return (
|
||||
<p className="mt-0.5 flex items-center gap-1.5 text-xs text-destructive">
|
||||
<TriangleAlert className="size-3.5 shrink-0" aria-hidden="true" />
|
||||
{message}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
function RemovedRow({ row }: { row: WorkspaceCleanupRunRow }): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
return (
|
||||
<div className={`${REMOVED_GRID} py-1.5`}>
|
||||
<WorkspaceCleanupWorkspaceLine workspace={row} />
|
||||
<div className="justify-self-start">
|
||||
{row.reason ? (
|
||||
<WorkspaceCleanupReasonChip reason={row.reason} prNumber={row.prNumber} />
|
||||
) : null}
|
||||
</div>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{row.outcome === 'archived'
|
||||
? t('components.settings.workspaceCleanup.activity.archived', 'Archived')
|
||||
: t('components.settings.workspaceCleanup.activity.deleted', 'Deleted')}
|
||||
</span>
|
||||
<span className="text-right text-xs tabular-nums text-muted-foreground">
|
||||
{row.sizeBytes !== undefined ? formatBytes(row.sizeBytes) : null}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function KeptRows({
|
||||
rows,
|
||||
total
|
||||
}: {
|
||||
rows: WorkspaceCleanupRunRow[]
|
||||
total: number
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const [showAll, setShowAll] = useState(false)
|
||||
const visible = showAll ? rows : rows.slice(0, KEPT_PREVIEW_COUNT)
|
||||
const hidden = rows.length - visible.length
|
||||
return (
|
||||
<>
|
||||
<GroupLabel>
|
||||
{t('components.settings.workspaceCleanup.activity.kept', 'Kept · {{count}}', {
|
||||
count: total
|
||||
})}
|
||||
</GroupLabel>
|
||||
{visible.map((row) => (
|
||||
<div
|
||||
key={workspaceCleanupRowKey(row)}
|
||||
className="grid grid-cols-[minmax(0,1fr)_minmax(0,auto)] items-center gap-x-4 py-1.5"
|
||||
>
|
||||
<WorkspaceCleanupWorkspaceLine workspace={row} />
|
||||
<KeptReason row={row} />
|
||||
</div>
|
||||
))}
|
||||
{hidden > 0 ? (
|
||||
<div className="py-1">
|
||||
<Button variant="ghost" size="xs" className="-ml-2" onClick={() => setShowAll(true)}>
|
||||
{t('components.settings.workspaceCleanup.activity.showMore', 'Show {{count}} more', {
|
||||
count: hidden
|
||||
})}
|
||||
<ChevronDown className="size-3" />
|
||||
</Button>
|
||||
</div>
|
||||
) : total > rows.length ? (
|
||||
// The host saves a capped receipt, so a busy run lists fewer rows than it kept.
|
||||
<p className="py-1 text-xs text-muted-foreground">
|
||||
{t(
|
||||
'components.settings.workspaceCleanup.activity.notListed',
|
||||
'{{count}} more kept workspaces are not listed.',
|
||||
{
|
||||
count: total - rows.length,
|
||||
defaultValue_one: '1 more kept workspace is not listed.'
|
||||
}
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function KeptReason({ row }: { row: WorkspaceCleanupRunRow }): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
if (row.keepCause === 'waiting' && row.waiting) {
|
||||
const { elapsedDays, afterDays } = row.waiting
|
||||
return (
|
||||
<span className="flex items-center gap-2 justify-self-end">
|
||||
<span className="relative h-1 w-16 shrink-0 overflow-hidden rounded-full bg-muted">
|
||||
<span
|
||||
className="absolute inset-y-0 left-0 rounded-full bg-muted-foreground"
|
||||
style={{
|
||||
width: `${Math.round((Math.min(elapsedDays, afterDays) / afterDays) * 100)}%`
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
<span className="text-xs tabular-nums text-muted-foreground">
|
||||
{t(
|
||||
'components.settings.workspaceCleanup.activity.waiting',
|
||||
'Inactive {{elapsed}} of {{after}} days',
|
||||
{ elapsed: elapsedDays, after: afterDays }
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
if (!row.keepCause) {
|
||||
return null
|
||||
}
|
||||
const names =
|
||||
row.keepCause === 'ignored-files' && row.ignoredFiles
|
||||
? formatAtRiskLocalFileNames(row.ignoredFiles, t)
|
||||
: null
|
||||
const cause = formatCleanupKeepCause(row.keepCause, t)
|
||||
const label = names
|
||||
? t('components.settings.workspaceCleanup.keep.withDetail', '{{cause}} · {{detail}}', {
|
||||
cause,
|
||||
detail: names
|
||||
})
|
||||
: cause
|
||||
return (
|
||||
<WorkspaceCleanupMetadataText
|
||||
icon={KEEP_CAUSE_ICONS[row.keepCause] ?? CircleMinus}
|
||||
label={label}
|
||||
value={label}
|
||||
className="justify-self-end"
|
||||
/>
|
||||
)
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
CalendarClock,
|
||||
Clock,
|
||||
GitCommitHorizontal,
|
||||
GitMerge,
|
||||
Network,
|
||||
type LucideIcon
|
||||
} from 'lucide-react'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { getReviewStateTone } from '@/components/github/review-state-presentation'
|
||||
import { WorkspaceCleanupMetadataChip } from '@/components/workspace-cleanup/candidate-list/workspace-cleanup-metadata-chip'
|
||||
import type { WorkspaceCleanupRuleReason } from '../../../../../shared/workspace-cleanup/workspace-cleanup-evaluation'
|
||||
import { formatCleanupRuleReasonBadge } from './workspace-cleanup-run-labels'
|
||||
|
||||
const REASON_ICONS: Record<WorkspaceCleanupRuleReason, LucideIcon> = {
|
||||
merged: GitMerge,
|
||||
unchanged: GitCommitHorizontal,
|
||||
inactive: Clock,
|
||||
'automation-run': CalendarClock,
|
||||
'orchestration-worker': Network
|
||||
}
|
||||
|
||||
/** The rule that removes, or would remove, a workspace. */
|
||||
export function WorkspaceCleanupReasonChip({
|
||||
reason,
|
||||
prNumber
|
||||
}: {
|
||||
reason: WorkspaceCleanupRuleReason
|
||||
/** The merged pull request, when the host read one. */
|
||||
prNumber?: number
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const badge = formatCleanupRuleReasonBadge(reason, t)
|
||||
const label =
|
||||
reason === 'merged' && prNumber !== undefined
|
||||
? t('components.settings.workspaceCleanup.reason.mergedNumber', '{{label}} · #{{number}}', {
|
||||
label: badge,
|
||||
number: prNumber
|
||||
})
|
||||
: badge
|
||||
return (
|
||||
<WorkspaceCleanupMetadataChip
|
||||
icon={REASON_ICONS[reason] ?? Clock}
|
||||
label={label}
|
||||
value={label}
|
||||
toneClassName={reason === 'merged' ? getReviewStateTone('merged') : undefined}
|
||||
/>
|
||||
)
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
import { useState } from 'react'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { cn } from '@/lib/class-names'
|
||||
import { formatBytes } from '../../../../../shared/format-bytes'
|
||||
import type { WorkspaceCleanupPreviewRow } from '../../../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
import { Button } from '../../ui/button'
|
||||
import { Checkbox } from '../../ui/checkbox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle
|
||||
} from '../../ui/dialog'
|
||||
import {
|
||||
WorkspaceCleanupWorkspaceLine,
|
||||
workspaceCleanupRowKey
|
||||
} from './workspace-cleanup-workspace-line'
|
||||
import { WorkspaceCleanupReasonChip } from './workspace-cleanup-reason-chip'
|
||||
|
||||
export type WorkspaceCleanupRuleChangeRequest = {
|
||||
/** `change`: a setting other than a rule switch, such as the inactive days, widened what is deleted. */
|
||||
kind: 'enable' | 'change'
|
||||
ruleTitle: string
|
||||
rows: WorkspaceCleanupPreviewRow[]
|
||||
}
|
||||
|
||||
/** Shown before a rule change that would delete workspaces right now; Keep pins a workspace so it is never removed. */
|
||||
export function WorkspaceCleanupRuleChangeDialog({
|
||||
request,
|
||||
onCancel,
|
||||
onConfirm
|
||||
}: {
|
||||
request: WorkspaceCleanupRuleChangeRequest | null
|
||||
onCancel: () => void
|
||||
onConfirm: (keep: WorkspaceCleanupPreviewRow[]) => Promise<void>
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const [kept, setKept] = useState<ReadonlySet<string>>(new Set())
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
// The last request stays on screen while the dialog animates out.
|
||||
const [shownRequest, setShownRequest] = useState(request)
|
||||
if (request && request !== shownRequest) {
|
||||
setShownRequest(request)
|
||||
setKept(new Set())
|
||||
}
|
||||
const rows = shownRequest?.rows ?? []
|
||||
const enabling = shownRequest?.kind !== 'change'
|
||||
const deleted = rows.filter((row) => !kept.has(workspaceCleanupRowKey(row)))
|
||||
const deletedBytes = deleted.reduce((sum, row) => sum + (row.sizeBytes ?? 0), 0)
|
||||
|
||||
const toggleKeep = (row: WorkspaceCleanupPreviewRow): void => {
|
||||
setKept((previous) => {
|
||||
const next = new Set(previous)
|
||||
if (!next.delete(workspaceCleanupRowKey(row))) {
|
||||
next.add(workspaceCleanupRowKey(row))
|
||||
}
|
||||
return next
|
||||
})
|
||||
}
|
||||
|
||||
const confirm = (): void => {
|
||||
setConfirming(true)
|
||||
void onConfirm(rows.filter((row) => kept.has(workspaceCleanupRowKey(row)))).finally(() =>
|
||||
setConfirming(false)
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={request !== null}
|
||||
// Pins may already be written; backing out mid-confirm would leave the change half done.
|
||||
onOpenChange={(open) => (!open && !confirming ? onCancel() : undefined)}
|
||||
>
|
||||
<DialogContent surface="security" showCloseButton={!confirming} className="sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{enabling
|
||||
? t('components.settings.workspaceCleanup.enable.title', 'Turn on {{rule}}?', {
|
||||
rule: shownRequest?.ruleTitle ?? ''
|
||||
})
|
||||
: t('components.settings.workspaceCleanup.change.title', 'Change {{rule}}?', {
|
||||
rule: shownRequest?.ruleTitle ?? ''
|
||||
})}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{enabling
|
||||
? t(
|
||||
'components.settings.workspaceCleanup.enable.description',
|
||||
"{{count}} workspaces match right now. They'll be deleted a few seconds after you turn this on.",
|
||||
{
|
||||
count: rows.length,
|
||||
defaultValue_one:
|
||||
"1 workspace matches right now. It'll be deleted a few seconds after you turn this on."
|
||||
}
|
||||
)
|
||||
: t(
|
||||
'components.settings.workspaceCleanup.change.description',
|
||||
"This change makes {{count}} more workspaces match right now. They'll be deleted a few seconds after you apply it.",
|
||||
{
|
||||
count: rows.length,
|
||||
defaultValue_one:
|
||||
"This change makes 1 more workspace match right now. It'll be deleted a few seconds after you apply it."
|
||||
}
|
||||
)}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div
|
||||
role="list"
|
||||
className="max-h-72 overflow-y-auto rounded-md border border-border/70 bg-muted/35 px-3 scrollbar-sleek"
|
||||
>
|
||||
{rows.map((row, index) => {
|
||||
const keep = kept.has(workspaceCleanupRowKey(row))
|
||||
return (
|
||||
<div
|
||||
key={workspaceCleanupRowKey(row)}
|
||||
role="listitem"
|
||||
className={cn(
|
||||
'flex min-w-0 items-center gap-3 py-2',
|
||||
index < rows.length - 1 && 'border-b border-border/50'
|
||||
)}
|
||||
>
|
||||
<WorkspaceCleanupWorkspaceLine workspace={row} className="flex-1" />
|
||||
{row.evaluation.action !== 'keep' ? (
|
||||
<WorkspaceCleanupReasonChip
|
||||
reason={row.evaluation.reason}
|
||||
prNumber={row.prNumber}
|
||||
/>
|
||||
) : null}
|
||||
<span
|
||||
className={cn(
|
||||
'w-14 shrink-0 text-right text-xs tabular-nums text-muted-foreground',
|
||||
keep && 'line-through decoration-muted-foreground/70'
|
||||
)}
|
||||
>
|
||||
{row.sizeBytes !== undefined ? formatBytes(row.sizeBytes) : null}
|
||||
</span>
|
||||
<label className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Checkbox
|
||||
checked={keep}
|
||||
disabled={confirming}
|
||||
onCheckedChange={() => toggleKeep(row)}
|
||||
aria-label={t(
|
||||
'components.settings.workspaceCleanup.enable.keepNamed',
|
||||
'Keep {{name}}',
|
||||
{
|
||||
name: row.displayName
|
||||
}
|
||||
)}
|
||||
/>
|
||||
{t('components.settings.workspaceCleanup.enable.keep', 'Keep')}
|
||||
</label>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<DialogFooter className="items-center">
|
||||
<p className="mr-auto whitespace-nowrap text-xs tabular-nums text-muted-foreground">
|
||||
{t('components.settings.workspaceCleanup.enable.summary', '{{count}} will be deleted', {
|
||||
count: deleted.length
|
||||
})}
|
||||
{deletedBytes > 0 ? ` · ${formatBytes(deletedBytes)}` : null}
|
||||
</p>
|
||||
<Button variant="ghost" onClick={onCancel} disabled={confirming}>
|
||||
{t('components.settings.workspaceCleanup.enable.cancel', 'Cancel')}
|
||||
</Button>
|
||||
<Button onClick={confirm} disabled={confirming}>
|
||||
{enabling
|
||||
? t('components.settings.workspaceCleanup.enable.turnOn', 'Turn on')
|
||||
: t('components.settings.workspaceCleanup.change.apply', 'Apply')}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
WORKSPACE_ARCHIVE_SUPPORTED,
|
||||
type WORKSPACE_CLEANUP_RULE_KEYS,
|
||||
type WorkspaceCleanupRules
|
||||
} from '../../../../../shared/workspace-cleanup/workspace-cleanup-policy'
|
||||
import type { WorkspaceCleanupRuleReason } from '../../../../../shared/workspace-cleanup/workspace-cleanup-evaluation'
|
||||
|
||||
export type WorkspaceCleanupRuleKey = (typeof WORKSPACE_CLEANUP_RULE_KEYS)[number]
|
||||
|
||||
export const WORKSPACE_CLEANUP_RULE_REASON: Record<
|
||||
WorkspaceCleanupRuleKey,
|
||||
WorkspaceCleanupRuleReason
|
||||
> = {
|
||||
merged: 'merged',
|
||||
unchanged: 'unchanged',
|
||||
inactive: 'inactive',
|
||||
automationRuns: 'automation-run',
|
||||
orchestrationWorkers: 'orchestration-worker'
|
||||
}
|
||||
|
||||
/** Turns one rule on or off; turning the inactive rule on picks delete while Orca cannot archive. */
|
||||
export function setWorkspaceCleanupRuleEnabled(
|
||||
rules: WorkspaceCleanupRules,
|
||||
key: WorkspaceCleanupRuleKey,
|
||||
enabled: boolean
|
||||
): WorkspaceCleanupRules {
|
||||
if (key === 'inactive') {
|
||||
return {
|
||||
...rules,
|
||||
inactive: {
|
||||
...rules.inactive,
|
||||
enabled,
|
||||
...(enabled && !WORKSPACE_ARCHIVE_SUPPORTED ? { action: 'delete' as const } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
return { ...rules, [key]: { ...rules[key], enabled } }
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
import { useState } from 'react'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { useAppStateValue } from '@/store/retained-views/app-state-view'
|
||||
import { formatBytes } from '../../../../../shared/format-bytes'
|
||||
import {
|
||||
WORKSPACE_ARCHIVE_SUPPORTED,
|
||||
WORKSPACE_CLEANUP_POLICY_MAX_DAYS,
|
||||
WORKSPACE_CLEANUP_POLICY_MIN_DAYS,
|
||||
type WorkspaceCleanupInactiveAction,
|
||||
type WorkspaceCleanupRules
|
||||
} from '../../../../../shared/workspace-cleanup/workspace-cleanup-policy'
|
||||
import type { WorkspaceCleanupPreviewRow } from '../../../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
import {
|
||||
NumberField,
|
||||
SettingsBadge,
|
||||
SettingsRow,
|
||||
SettingsSegmentedControl,
|
||||
SettingsSwitchRow
|
||||
} from '../form-controls/SettingsFormControls'
|
||||
import { SearchableSetting } from '../section-layout/SearchableSetting'
|
||||
import { SettingsGroupDisclosure } from '../section-layout/SettingsGroupDisclosure'
|
||||
import { matchesSettingsSearch } from '../search/settings-search'
|
||||
import { getWorkspaceCleanupSettingsSearchParts } from './workspace-cleanup-settings-search'
|
||||
import {
|
||||
WorkspaceCleanupWorkspaceLine,
|
||||
workspaceCleanupRowKey
|
||||
} from './workspace-cleanup-workspace-line'
|
||||
import type { WorkspaceCleanupRuleKey } from './workspace-cleanup-rule-keys'
|
||||
|
||||
export type WorkspaceCleanupRuleMatches = {
|
||||
rows: WorkspaceCleanupPreviewRow[]
|
||||
sizeBytes: number
|
||||
}
|
||||
|
||||
type RuleRowsProps = {
|
||||
rules: WorkspaceCleanupRules
|
||||
onToggle: (key: WorkspaceCleanupRuleKey) => void
|
||||
/** Gets a change as a function so it applies to the rules as they are when it is saved. */
|
||||
onChange: (change: (rules: WorkspaceCleanupRules) => WorkspaceCleanupRules) => void
|
||||
/** What each rule that is on would remove now; omitted where no preview is read. */
|
||||
matches?: Partial<Record<WorkspaceCleanupRuleKey, WorkspaceCleanupRuleMatches>>
|
||||
/** 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. */
|
||||
disabled?: boolean
|
||||
forceVisible?: boolean
|
||||
}
|
||||
|
||||
/** The rule switches, shared by the Workspace Cleanup page and a project's custom rules. */
|
||||
export function WorkspaceCleanupRuleRows({
|
||||
rules,
|
||||
onToggle,
|
||||
onChange,
|
||||
matches,
|
||||
pendingRule,
|
||||
disabled = false,
|
||||
forceVisible = false
|
||||
}: RuleRowsProps): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
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) => (
|
||||
<SearchableSetting {...search[key]} forceVisible={forceVisible}>
|
||||
<SettingsSwitchRow
|
||||
label={
|
||||
<span className="inline-flex items-center gap-2">
|
||||
{search[key].title}
|
||||
{badge ? <SettingsBadge>{badge}</SettingsBadge> : null}
|
||||
</span>
|
||||
}
|
||||
description={
|
||||
<>
|
||||
{description}
|
||||
{pendingRule === key ? (
|
||||
<span className="mt-1 block">
|
||||
{t(
|
||||
'components.settings.workspaceCleanup.rules.checking',
|
||||
'Checking which workspaces match…'
|
||||
)}
|
||||
</span>
|
||||
) : matches?.[key] && rules[key].enabled ? (
|
||||
<RuleMatchesLine matches={matches[key]} />
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
checked={rules[key].enabled}
|
||||
disabled={disabled}
|
||||
onChange={() => onToggle(key)}
|
||||
ariaLabel={search[key].title}
|
||||
/>
|
||||
{key === 'inactive' && rules.inactive.enabled ? (
|
||||
<InactiveRuleOptions rules={rules} onChange={onChange} disabled={disabled} />
|
||||
) : null}
|
||||
</SearchableSetting>
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
{ruleRow(
|
||||
'merged',
|
||||
search.merged.description,
|
||||
t('components.settings.workspaceCleanup.rules.recommended', 'Recommended')
|
||||
)}
|
||||
{ruleRow('unchanged', search.unchanged.description)}
|
||||
{ruleRow(
|
||||
'inactive',
|
||||
t(
|
||||
'components.settings.workspaceCleanup.rules.inactiveDescription',
|
||||
'No activity for {{count}} days.',
|
||||
{ count: rules.inactive.afterDays, defaultValue_one: 'No activity for 1 day.' }
|
||||
)
|
||||
)}
|
||||
<SettingsGroupDisclosure
|
||||
description={t(
|
||||
'components.settings.workspaceCleanup.rules.advancedDescription',
|
||||
'Automation and orchestration worker workspaces'
|
||||
)}
|
||||
forceOpen={advancedMatches}
|
||||
>
|
||||
{ruleRow('automationRuns', search.automationRuns.description)}
|
||||
{ruleRow('orchestrationWorkers', search.orchestrationWorkers.description)}
|
||||
</SettingsGroupDisclosure>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function InactiveRuleOptions({
|
||||
rules,
|
||||
onChange,
|
||||
disabled
|
||||
}: {
|
||||
rules: WorkspaceCleanupRules
|
||||
onChange: RuleRowsProps['onChange']
|
||||
disabled: boolean
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const setInactive = (patch: Partial<WorkspaceCleanupRules['inactive']>): void =>
|
||||
onChange((latest) => ({ ...latest, inactive: { ...latest.inactive, ...patch } }))
|
||||
return (
|
||||
<div className="mb-2 ml-4 border-l border-border pl-4">
|
||||
<NumberField
|
||||
label={t('components.settings.workspaceCleanup.rules.inactiveFor', 'Inactive for')}
|
||||
value={rules.inactive.afterDays}
|
||||
min={WORKSPACE_CLEANUP_POLICY_MIN_DAYS}
|
||||
max={WORKSPACE_CLEANUP_POLICY_MAX_DAYS}
|
||||
integer
|
||||
suffix={t('components.settings.workspaceCleanup.rules.days', 'days')}
|
||||
disabled={disabled}
|
||||
onChange={(afterDays) => setInactive({ afterDays })}
|
||||
/>
|
||||
{WORKSPACE_ARCHIVE_SUPPORTED ? (
|
||||
<SettingsRow
|
||||
label={t('components.settings.workspaceCleanup.rules.then', 'Then')}
|
||||
description={
|
||||
rules.inactive.action === 'archive'
|
||||
? t(
|
||||
'components.settings.workspaceCleanup.rules.archiveDescription',
|
||||
'Archive frees disk space and keeps the workspace in the sidebar.'
|
||||
)
|
||||
: t(
|
||||
'components.settings.workspaceCleanup.rules.deleteDescription',
|
||||
'Delete removes the workspace and its folder.'
|
||||
)
|
||||
}
|
||||
control={
|
||||
<SettingsSegmentedControl<WorkspaceCleanupInactiveAction>
|
||||
size="sm"
|
||||
value={rules.inactive.action}
|
||||
onChange={(action) => setInactive({ action })}
|
||||
ariaLabel={t('components.settings.workspaceCleanup.rules.then', 'Then')}
|
||||
options={[
|
||||
{
|
||||
value: 'archive',
|
||||
disabled,
|
||||
label: t('components.settings.workspaceCleanup.rules.archive', 'Archive')
|
||||
},
|
||||
{
|
||||
value: 'delete',
|
||||
disabled,
|
||||
label: t('components.settings.workspaceCleanup.rules.delete', 'Delete')
|
||||
}
|
||||
]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function RuleMatchesLine({
|
||||
matches
|
||||
}: {
|
||||
matches: WorkspaceCleanupRuleMatches
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const [open, setOpen] = useState(false)
|
||||
if (matches.rows.length === 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<span className="mt-1 block tabular-nums">
|
||||
{t(
|
||||
'components.settings.workspaceCleanup.rules.matchesCount',
|
||||
'Matches {{count}} workspaces now',
|
||||
{ count: matches.rows.length, defaultValue_one: 'Matches 1 workspace now' }
|
||||
)}
|
||||
{matches.sizeBytes > 0 ? ` · ${formatBytes(matches.sizeBytes)}` : null}
|
||||
{' · '}
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen((value) => !value)}
|
||||
className="underline decoration-muted-foreground/50 underline-offset-4 hover:text-foreground"
|
||||
>
|
||||
{open
|
||||
? t('components.settings.workspaceCleanup.rules.hideMatches', 'Hide')
|
||||
: t('components.settings.workspaceCleanup.rules.showMatches', 'Show')}
|
||||
</button>
|
||||
</span>
|
||||
{open ? (
|
||||
<span className="mt-1 block space-y-0.5">
|
||||
{matches.rows.map((row) => (
|
||||
<WorkspaceCleanupWorkspaceLine
|
||||
key={workspaceCleanupRowKey(row)}
|
||||
workspace={row}
|
||||
trailing={row.sizeBytes !== undefined ? formatBytes(row.sizeBytes) : undefined}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import type {
|
||||
WorkspaceCleanupKeepCause,
|
||||
WorkspaceCleanupRuleReason
|
||||
} from '../../../../../shared/workspace-cleanup/workspace-cleanup-evaluation'
|
||||
import type { WorkspaceCleanupRunTrigger } from '../../../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
import {
|
||||
formatWorkspaceCleanupKeepCause,
|
||||
formatWorkspaceCleanupRuleReason
|
||||
} from '../../../../../shared/workspace-cleanup/workspace-cleanup-verdict-labels'
|
||||
|
||||
// Localized counterparts of the CLI's verdict labels; a value from a newer host falls back to the CLI's words.
|
||||
|
||||
export function formatCleanupRuleReasonBadge(
|
||||
reason: WorkspaceCleanupRuleReason,
|
||||
t: Translate = translate
|
||||
): string {
|
||||
switch (reason) {
|
||||
case 'merged':
|
||||
return t('components.settings.workspaceCleanup.reason.merged', 'Merged')
|
||||
case 'unchanged':
|
||||
return t('components.settings.workspaceCleanup.reason.unchanged', 'Unchanged')
|
||||
case 'inactive':
|
||||
return t('components.settings.workspaceCleanup.reason.inactive', 'Inactive')
|
||||
case 'automation-run':
|
||||
return t('components.settings.workspaceCleanup.reason.automationRun', 'Automation run')
|
||||
case 'orchestration-worker':
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.reason.orchestrationWorker',
|
||||
'Orchestration worker'
|
||||
)
|
||||
}
|
||||
// A newer host can send a reason this build has no label for; the CLI's words beat nothing.
|
||||
return formatWorkspaceCleanupRuleReason(reason)
|
||||
}
|
||||
|
||||
export function formatCleanupKeepCause(
|
||||
cause: WorkspaceCleanupKeepCause,
|
||||
t: Translate = translate
|
||||
): string {
|
||||
switch (cause) {
|
||||
case 'pinned':
|
||||
return t('components.settings.workspaceCleanup.keep.pinned', 'Pinned')
|
||||
case 'no-rule-matched':
|
||||
return t('components.settings.workspaceCleanup.keep.noRuleMatched', 'No rule matched')
|
||||
case 'recently-active':
|
||||
return t('components.settings.workspaceCleanup.keep.recentlyActive', 'Used in the last hour')
|
||||
case 'active-workspace':
|
||||
return t('components.settings.workspaceCleanup.keep.activeWorkspace', 'Open right now')
|
||||
case 'agent-running':
|
||||
return t('components.settings.workspaceCleanup.keep.agentRunning', 'Agent running')
|
||||
case 'terminal-running':
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.keep.terminalRunning',
|
||||
'Terminal running a process'
|
||||
)
|
||||
case 'terminal-unknown':
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.keep.terminalUnknown',
|
||||
'Terminal state unknown'
|
||||
)
|
||||
case 'unsaved-editor-changes':
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.keep.unsavedEditorChanges',
|
||||
'Unsaved editor changes'
|
||||
)
|
||||
case 'uncommitted-changes':
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.keep.uncommittedChanges',
|
||||
'Uncommitted changes'
|
||||
)
|
||||
case 'unpushed-commits':
|
||||
return t('components.settings.workspaceCleanup.keep.unpushedCommits', 'Unpushed commits')
|
||||
case 'ignored-files':
|
||||
return t('components.settings.workspaceCleanup.keep.ignoredFiles', 'Ignored files')
|
||||
case 'git-unknown':
|
||||
return t('components.settings.workspaceCleanup.keep.gitUnknown', "Couldn't read Git status")
|
||||
case 'archive-unavailable':
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.keep.archiveUnavailable',
|
||||
'Archive not available'
|
||||
)
|
||||
case 'archive-script':
|
||||
return t('components.settings.workspaceCleanup.keep.archiveScript', 'Has an archive script')
|
||||
case 'removing':
|
||||
return t('components.settings.workspaceCleanup.keep.removing', 'Already being removed')
|
||||
case 'waiting':
|
||||
return t('components.settings.workspaceCleanup.keep.waiting', 'Waiting')
|
||||
case 'not-removable':
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.keep.notRemovable',
|
||||
'Main workspace or folder project'
|
||||
)
|
||||
case 'project-off':
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.keep.projectOff',
|
||||
'Cleanup off for this project'
|
||||
)
|
||||
case 'rules-off':
|
||||
return t('components.settings.workspaceCleanup.keep.rulesOff', 'No rule on')
|
||||
}
|
||||
// A newer host can send a cause this build has no label for; the CLI's words beat nothing.
|
||||
return formatWorkspaceCleanupKeepCause(cause)
|
||||
}
|
||||
|
||||
export function formatCleanupRunTrigger(
|
||||
trigger: WorkspaceCleanupRunTrigger,
|
||||
t: Translate = translate
|
||||
): string {
|
||||
switch (trigger) {
|
||||
case 'startup':
|
||||
return t('components.settings.workspaceCleanup.trigger.startup', 'On startup')
|
||||
case 'hourly':
|
||||
return t('components.settings.workspaceCleanup.trigger.hourly', 'Hourly')
|
||||
case 'settings':
|
||||
return t('components.settings.workspaceCleanup.trigger.settings', 'After a rule change')
|
||||
case 'run-now':
|
||||
return t('components.settings.workspaceCleanup.trigger.runNow', 'Clean up now')
|
||||
case 'cli':
|
||||
return t('components.settings.workspaceCleanup.trigger.cli', 'From the CLI')
|
||||
}
|
||||
return String(trigger)
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
import { createLocalizedCatalog } from '@/i18n/localized-catalog'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { WORKSPACE_ARCHIVE_SUPPORTED } from '../../../../../shared/workspace-cleanup/workspace-cleanup-policy'
|
||||
import type { SettingsSearchEntry } from '../search/settings-search'
|
||||
import { translateSearchKeyword } from '../search/settings-search-keywords'
|
||||
|
||||
function cleanupKeywords(): string[] {
|
||||
return [
|
||||
...translateSearchKeyword('components.settings.workspaceCleanup.search.cleanup', 'cleanup'),
|
||||
...translateSearchKeyword('components.settings.workspaceCleanup.search.cleanUp', 'clean up'),
|
||||
...translateSearchKeyword('components.settings.workspaceCleanup.search.delete', 'delete')
|
||||
]
|
||||
}
|
||||
|
||||
/** One entry per searchable row; each row's SearchableSetting uses the same title. */
|
||||
export const getWorkspaceCleanupSettingsSearchParts = createLocalizedCatalog(
|
||||
() =>
|
||||
({
|
||||
status: {
|
||||
title: translate('components.settings.workspaceCleanup.cleanUpNow', 'Clean up now'),
|
||||
description: translate(
|
||||
'components.settings.workspaceCleanup.search.statusDescription',
|
||||
'Run the cleanup rules now, or review workspaces yourself.'
|
||||
),
|
||||
keywords: [
|
||||
...translateSearchKeyword(
|
||||
'components.settings.workspaceCleanup.search.reviewWorkspaces',
|
||||
'review workspaces'
|
||||
),
|
||||
...translateSearchKeyword(
|
||||
'components.settings.workspaceCleanup.search.automatic',
|
||||
'automatic'
|
||||
)
|
||||
]
|
||||
},
|
||||
merged: {
|
||||
title: translate(
|
||||
'components.settings.workspaceCleanup.rules.merged',
|
||||
'Delete merged workspaces'
|
||||
),
|
||||
description: translate(
|
||||
'components.settings.workspaceCleanup.rules.mergedDescription',
|
||||
'The pull request is merged and everything in the workspace is in it.'
|
||||
),
|
||||
keywords: [
|
||||
...cleanupKeywords(),
|
||||
...translateSearchKeyword('components.settings.workspaceCleanup.search.pullRequest', 'PR')
|
||||
]
|
||||
},
|
||||
unchanged: {
|
||||
title: translate(
|
||||
'components.settings.workspaceCleanup.rules.unchanged',
|
||||
'Delete unchanged workspaces'
|
||||
),
|
||||
description: translate(
|
||||
'components.settings.workspaceCleanup.rules.unchangedDescription',
|
||||
'No commits beyond the default branch and no edits.'
|
||||
),
|
||||
keywords: cleanupKeywords()
|
||||
},
|
||||
inactive: {
|
||||
// Until archiving exists the rule deletes, so it says so.
|
||||
title: WORKSPACE_ARCHIVE_SUPPORTED
|
||||
? translate(
|
||||
'components.settings.workspaceCleanup.rules.inactiveCleanUp',
|
||||
'Clean up inactive workspaces'
|
||||
)
|
||||
: translate(
|
||||
'components.settings.workspaceCleanup.rules.inactive',
|
||||
'Delete inactive workspaces'
|
||||
),
|
||||
description: translate(
|
||||
'components.settings.workspaceCleanup.search.inactiveDescription',
|
||||
'No activity for a number of days.'
|
||||
),
|
||||
keywords: [
|
||||
...cleanupKeywords(),
|
||||
...translateSearchKeyword('components.settings.workspaceCleanup.search.stale', 'stale'),
|
||||
...translateSearchKeyword('components.settings.workspaceCleanup.search.days', 'days')
|
||||
]
|
||||
},
|
||||
automationRuns: {
|
||||
title: translate(
|
||||
'components.settings.workspaceCleanup.rules.automationRuns',
|
||||
'Delete finished automation workspaces'
|
||||
),
|
||||
description: translate(
|
||||
'components.settings.workspaceCleanup.rules.automationRunsDescription',
|
||||
'Workspaces an automation run created, once the run has finished.'
|
||||
),
|
||||
keywords: [
|
||||
...translateSearchKeyword(
|
||||
'components.settings.workspaceCleanup.search.automations',
|
||||
'automations'
|
||||
)
|
||||
]
|
||||
},
|
||||
orchestrationWorkers: {
|
||||
title: translate(
|
||||
'components.settings.workspaceCleanup.rules.orchestrationWorkers',
|
||||
'Delete released orchestration worker workspaces'
|
||||
),
|
||||
description: translate(
|
||||
'components.settings.workspaceCleanup.rules.orchestrationWorkersDescription',
|
||||
'Workspaces an orchestration worker used, once the coordinator has released it.'
|
||||
),
|
||||
keywords: [
|
||||
...translateSearchKeyword(
|
||||
'components.settings.workspaceCleanup.search.orchestration',
|
||||
'orchestration'
|
||||
)
|
||||
]
|
||||
},
|
||||
keepIgnoredFiles: {
|
||||
title: translate(
|
||||
'components.settings.workspaceCleanup.protection.keepIgnoredFiles',
|
||||
'Keep workspaces with ignored files'
|
||||
),
|
||||
description: translate(
|
||||
'components.settings.workspaceCleanup.protection.keepIgnoredFilesDescription',
|
||||
"Files like .env and local config can't be recovered. node_modules and build output don't count."
|
||||
),
|
||||
keywords: [
|
||||
...translateSearchKeyword(
|
||||
'components.settings.workspaceCleanup.search.protection',
|
||||
'protection'
|
||||
),
|
||||
...translateSearchKeyword('components.settings.workspaceCleanup.search.envFile', '.env', {
|
||||
englishOnly: true
|
||||
})
|
||||
]
|
||||
},
|
||||
activity: {
|
||||
title: translate('components.settings.workspaceCleanup.activity.title', 'Activity'),
|
||||
description: translate(
|
||||
'components.settings.workspaceCleanup.search.activityDescription',
|
||||
'What each cleanup run removed and kept.'
|
||||
),
|
||||
keywords: [
|
||||
...translateSearchKeyword(
|
||||
'components.settings.workspaceCleanup.search.history',
|
||||
'history'
|
||||
),
|
||||
...translateSearchKeyword('components.settings.workspaceCleanup.search.runs', 'runs')
|
||||
]
|
||||
}
|
||||
}) satisfies Record<string, SettingsSearchEntry>
|
||||
)
|
||||
|
||||
export function getWorkspaceCleanupSettingsSearchEntries(): SettingsSearchEntry[] {
|
||||
return Object.values(getWorkspaceCleanupSettingsSearchParts())
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import { useTranslate, type Translate } from '@/i18n/use-translate'
|
||||
import { formatUiRelativeTime } from '@/i18n/relative-time-format'
|
||||
import { useAppStore } from '@/store'
|
||||
import { formatBytes } from '../../../../../shared/format-bytes'
|
||||
import type { WorkspaceCleanupReport } from '../../../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
import { Button } from '../../ui/button'
|
||||
import { SearchableSetting } from '../section-layout/SearchableSetting'
|
||||
import { getWorkspaceCleanupSettingsSearchParts } from './workspace-cleanup-settings-search'
|
||||
|
||||
// Intl says "this minute" for both directions under a minute, which reads oddly in a sentence.
|
||||
function formatRunTime(diffMs: number, t: Translate): string {
|
||||
// Callers pass a past time as negative and a future one as zero or more.
|
||||
if (Math.abs(diffMs) >= 60_000) {
|
||||
return formatUiRelativeTime(diffMs)
|
||||
}
|
||||
return diffMs < 0
|
||||
? t('components.settings.workspaceCleanup.status.justNow', 'just now')
|
||||
: t('components.settings.workspaceCleanup.status.inUnderAMinute', 'in under a minute')
|
||||
}
|
||||
|
||||
function formatLastRun(
|
||||
run: WorkspaceCleanupReport['runs'][number],
|
||||
now: number,
|
||||
t: Translate
|
||||
): string {
|
||||
const when = formatRunTime(Math.min(-1, run.finishedAt - now), t)
|
||||
if (run.error) {
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.status.lastRunFailed',
|
||||
"Last run {{when}} couldn't finish: {{error}}",
|
||||
{
|
||||
when,
|
||||
error: run.error
|
||||
}
|
||||
)
|
||||
}
|
||||
const removed = run.counts.removed + run.counts.archived
|
||||
if (removed === 0) {
|
||||
return t(
|
||||
'components.settings.workspaceCleanup.status.lastRunNothing',
|
||||
'Last run {{when}} removed nothing.',
|
||||
{
|
||||
when
|
||||
}
|
||||
)
|
||||
}
|
||||
return run.freedBytes > 0
|
||||
? t(
|
||||
'components.settings.workspaceCleanup.status.lastRunFreed',
|
||||
'Last run {{when}} removed {{count}} workspaces and freed {{size}}.',
|
||||
{
|
||||
when,
|
||||
count: removed,
|
||||
size: formatBytes(run.freedBytes),
|
||||
defaultValue_one: 'Last run {{when}} removed 1 workspace and freed {{size}}.'
|
||||
}
|
||||
)
|
||||
: t(
|
||||
'components.settings.workspaceCleanup.status.lastRunRemoved',
|
||||
'Last run {{when}} removed {{count}} workspaces.',
|
||||
{ when, count: removed, defaultValue_one: 'Last run {{when}} removed 1 workspace.' }
|
||||
)
|
||||
}
|
||||
|
||||
/** Whether automatic cleanup is on, what it last did, and the two ways to act now. */
|
||||
export function WorkspaceCleanupSettingsStatus({
|
||||
anyRuleOn,
|
||||
report,
|
||||
readAt,
|
||||
cleaningUp,
|
||||
onCleanUpNow
|
||||
}: {
|
||||
anyRuleOn: boolean
|
||||
report: WorkspaceCleanupReport | null
|
||||
/** When `report` was read. */
|
||||
readAt: number
|
||||
cleaningUp: boolean
|
||||
onCleanUpNow: () => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const openModal = useAppStore((state) => state.openModal)
|
||||
const search = getWorkspaceCleanupSettingsSearchParts()
|
||||
const lastRun = report?.runs[0]
|
||||
const running = cleaningUp || report?.running === true
|
||||
const details: string[] = []
|
||||
if (!anyRuleOn) {
|
||||
details.push(
|
||||
t(
|
||||
'components.settings.workspaceCleanup.status.offDetail',
|
||||
'Nothing is removed until you turn on a rule.'
|
||||
)
|
||||
)
|
||||
} else {
|
||||
if (running) {
|
||||
details.push(t('components.settings.workspaceCleanup.status.running', 'Cleaning up now…'))
|
||||
} else if (lastRun) {
|
||||
details.push(formatLastRun(lastRun, readAt, t))
|
||||
}
|
||||
if (!running && report?.nextRunAt) {
|
||||
details.push(
|
||||
t('components.settings.workspaceCleanup.status.nextRun', 'Next run {{when}}.', {
|
||||
when: formatRunTime(Math.max(0, report.nextRunAt - readAt), t)
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<SearchableSetting {...search.status} className="flex items-start justify-between gap-6 px-1">
|
||||
<div className="min-w-0 space-y-1">
|
||||
<p className="text-sm font-semibold">
|
||||
{anyRuleOn
|
||||
? t('components.settings.workspaceCleanup.status.on', 'Automatic cleanup is on.')
|
||||
: t('components.settings.workspaceCleanup.status.off', 'Automatic cleanup is off.')}
|
||||
</p>
|
||||
{details.map((line) => (
|
||||
<p key={line} className="text-xs tabular-nums text-muted-foreground">
|
||||
{line}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex shrink-0 flex-col items-end gap-1.5">
|
||||
<div className="flex items-center gap-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => openModal('workspace-cleanup')}
|
||||
className="text-xs text-muted-foreground underline decoration-muted-foreground/50 underline-offset-4 hover:text-foreground"
|
||||
>
|
||||
{t('components.settings.workspaceCleanup.status.review', 'Review workspaces')}
|
||||
</button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={!anyRuleOn || running}
|
||||
onClick={onCleanUpNow}
|
||||
>
|
||||
{search.status.title}
|
||||
</Button>
|
||||
</div>
|
||||
{anyRuleOn ? null : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
'components.settings.workspaceCleanup.status.turnOnHint',
|
||||
'Turn on a rule to use this.'
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</SearchableSetting>
|
||||
)
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
import { Folder } from 'lucide-react'
|
||||
import { cn } from '@/lib/class-names'
|
||||
import type { WorkspaceCleanupWorkspaceRef } from '../../../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
|
||||
/** A workspace's name and project in one line; spans only, so it can sit inside a row description. */
|
||||
export function WorkspaceCleanupWorkspaceLine({
|
||||
workspace,
|
||||
trailing,
|
||||
className
|
||||
}: {
|
||||
workspace: Pick<WorkspaceCleanupWorkspaceRef, 'displayName' | 'repoName'>
|
||||
trailing?: React.ReactNode
|
||||
className?: string
|
||||
}): React.JSX.Element {
|
||||
return (
|
||||
<span className={cn('flex min-w-0 items-center gap-2', className)}>
|
||||
<span className="min-w-0 truncate text-sm font-medium text-foreground">
|
||||
{workspace.displayName}
|
||||
</span>
|
||||
<span className="inline-flex min-w-0 max-w-48 shrink-[4] items-center gap-1 text-xs text-muted-foreground">
|
||||
<Folder className="size-3 shrink-0" aria-hidden="true" />
|
||||
<span className="truncate">{workspace.repoName}</span>
|
||||
</span>
|
||||
{trailing ? (
|
||||
<span className="ml-auto shrink-0 text-xs tabular-nums text-muted-foreground">
|
||||
{trailing}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** One key per workspace across hosts; a bare id can repeat on two hosts. */
|
||||
export function workspaceCleanupRowKey(
|
||||
row: Pick<WorkspaceCleanupWorkspaceRef, 'executionHostId' | 'worktreeId'>
|
||||
): string {
|
||||
return `${row.executionHostId ?? ''}:${row.worktreeId}`
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/** Fans a host's finished cleanup run out within the renderer, whichever transport delivered it. */
|
||||
import type { WorkspaceCleanupRunFinishedEvent } from '../../../../../shared/workspace-cleanup/workspace-cleanup-run'
|
||||
|
||||
export const WORKSPACE_CLEANUP_RUN_FINISHED_EVENT = 'orca:workspace-cleanup-run-finished'
|
||||
|
||||
/** `environmentId` names the server whose runner finished; null is this app's own runner. */
|
||||
export type WorkspaceCleanupRunFinishedWindowDetail = {
|
||||
environmentId: string | null
|
||||
run: WorkspaceCleanupRunFinishedEvent['run']
|
||||
}
|
||||
|
||||
export function emitWorkspaceCleanupRunFinishedWindowEvent(
|
||||
detail: WorkspaceCleanupRunFinishedWindowDetail
|
||||
): void {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent<WorkspaceCleanupRunFinishedWindowDetail>(WORKSPACE_CLEANUP_RUN_FINISHED_EVENT, {
|
||||
detail
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
export function onWorkspaceCleanupRunFinished(
|
||||
listener: (detail: WorkspaceCleanupRunFinishedWindowDetail) => void
|
||||
): () => void {
|
||||
const handle = (event: Event): void => {
|
||||
if (event instanceof CustomEvent && isRunFinishedDetail(event.detail)) {
|
||||
listener(event.detail)
|
||||
}
|
||||
}
|
||||
window.addEventListener(WORKSPACE_CLEANUP_RUN_FINISHED_EVENT, handle)
|
||||
return () => window.removeEventListener(WORKSPACE_CLEANUP_RUN_FINISHED_EVENT, handle)
|
||||
}
|
||||
|
||||
function isRunFinishedDetail(value: unknown): value is WorkspaceCleanupRunFinishedWindowDetail {
|
||||
return typeof value === 'object' && value !== null && 'run' in value && 'environmentId' in value
|
||||
}
|
||||
@@ -24,6 +24,7 @@ export function buildWindowApi(args: {
|
||||
api: {
|
||||
repos: { onChanged: () => () => {} },
|
||||
automations: { onChanged: () => () => {} },
|
||||
workspaceCleanup: { onRunFinished: () => () => {} },
|
||||
worktrees: {
|
||||
onChanged: () => () => {},
|
||||
onBaseStatus: () => () => {},
|
||||
|
||||
@@ -152,6 +152,7 @@ export async function useIpcEventsForCloseRouting({
|
||||
api: {
|
||||
repos: { onChanged: () => () => {} },
|
||||
automations: { onChanged: () => () => {} },
|
||||
workspaceCleanup: { onRunFinished: () => () => {} },
|
||||
worktrees: {
|
||||
onChanged: () => () => {},
|
||||
onBaseStatus: () => () => {},
|
||||
|
||||
@@ -4,6 +4,7 @@ import { observeRuntimeHostStatusForPendingRemovals } from '@/store/repos/pendin
|
||||
import type { RuntimeHostStatusSnapshot } from '../../../../shared/remote-runtime/host-status/runtime-host-status'
|
||||
import { getTabIdsAwaitingHostHydrationRemount } from '@/components/terminal-pane/mounting/parked-terminal-host-hydration'
|
||||
import { emitAutomationsChangedWindowEvent } from '@/components/automations/events/automations-changed-window-event'
|
||||
import { emitWorkspaceCleanupRunFinishedWindowEvent } from '@/components/workspace-cleanup/events/workspace-cleanup-run-finished-window-event'
|
||||
import { createBackgroundSleepingAgentWakeDispatcher } from '@/lib/agent-session/resume/wake-sleeping-agents-in-background'
|
||||
import { remoteRuntimeTerminalColorPush } from '@/runtime/hosted-terminals/streams/remote-runtime-terminal-color-push'
|
||||
import { resetAgentHookCompletionNotificationCoordinators } from '../agent-hook-completion-notifications'
|
||||
@@ -65,6 +66,11 @@ export function installAppLifetimeIpcEvents(): () => void {
|
||||
unsubs.push(
|
||||
window.api.automations.onChanged((payload) => emitAutomationsChangedWindowEvent(payload))
|
||||
)
|
||||
unsubs.push(
|
||||
window.api.workspaceCleanup.onRunFinished((run) =>
|
||||
emitWorkspaceCleanupRunFinishedWindowEvent({ environmentId: null, run })
|
||||
)
|
||||
)
|
||||
|
||||
const worktreeRuntime = createWorktreeEventRuntime(unsubs, isRuntimeEnvironmentActive)
|
||||
const statusApi = window.api.runtimeEnvironments
|
||||
|
||||
@@ -3,7 +3,7 @@ import {
|
||||
refreshDefaultLinkedLinearIssue
|
||||
} from './linear-linked-issue-refresh'
|
||||
import { dispatchTerminalSideEffectBatch } from '@/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler'
|
||||
import { emitAutomationsChangedWindowEvent } from '@/components/automations/events/automations-changed-window-event'
|
||||
import { emitRuntimeClientWindowEvent } from './runtime-client-window-events'
|
||||
import { applyHostWorkspaceRowEvent } from './worktree-metadata-set-events'
|
||||
import { applyNativeChatLaunchDraftResolved } from '@/runtime/native-chat/launch-drafts/native-chat-launch-draft-runtime-resolution'
|
||||
import { getRuntimeEnvironmentRevision } from '@/runtime/rpc/environment-revisions/runtime-environment-revision'
|
||||
@@ -137,13 +137,7 @@ export function registerRuntimeClientIpcBridge(
|
||||
requestProjectRefresh(environmentId)
|
||||
return
|
||||
}
|
||||
if (event.type === 'automationsChanged') {
|
||||
// Why: without the environment the subscriber cannot attribute the changed authority.
|
||||
emitAutomationsChangedWindowEvent({
|
||||
environmentId,
|
||||
...(event.selector ? { selector: event.selector } : {}),
|
||||
...(event.reason ? { reason: event.reason } : {})
|
||||
})
|
||||
if (emitRuntimeClientWindowEvent(environmentId, event)) {
|
||||
return
|
||||
}
|
||||
if (event.type === 'browserProfilesChanged') {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { emitAutomationsChangedWindowEvent } from '@/components/automations/events/automations-changed-window-event'
|
||||
import { emitWorkspaceCleanupRunFinishedWindowEvent } from '@/components/workspace-cleanup/events/workspace-cleanup-run-finished-window-event'
|
||||
import type { RuntimeClientEvent } from '../../../../shared/runtime-client-events'
|
||||
|
||||
/** Re-emits a server's events that renderer pages listen for as window events; true when handled. */
|
||||
export function emitRuntimeClientWindowEvent(
|
||||
environmentId: string,
|
||||
event: RuntimeClientEvent
|
||||
): boolean {
|
||||
if (event.type === 'automationsChanged') {
|
||||
// Why: without the environment the subscriber cannot attribute the changed authority.
|
||||
emitAutomationsChangedWindowEvent({
|
||||
environmentId,
|
||||
...(event.selector ? { selector: event.selector } : {}),
|
||||
...(event.reason ? { reason: event.reason } : {})
|
||||
})
|
||||
return true
|
||||
}
|
||||
if (event.type === 'workspaceCleanupRunFinished') {
|
||||
emitWorkspaceCleanupRunFinishedWindowEvent({ environmentId, run: event.run })
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -10,12 +10,14 @@ import { getOrcaAccountSettingsSearchEntries } from '@/components/settings/accou
|
||||
import { OrcaLogoSettingsIcon } from '@/components/settings/page/orca-logo-settings-icon'
|
||||
import { getOrchestrationPaneSearchEntries } from '@/components/settings/orchestration/orchestration-search'
|
||||
import { getVoicePaneSearchEntries } from '@/components/settings/voice/voice-pane-search'
|
||||
import { getWorkspaceCleanupSettingsSearchEntries } from '@/components/settings/workspace-cleanup/workspace-cleanup-settings-search'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import type { Translate } from '@/i18n/use-translate'
|
||||
import type { SettingsNavSection } from '@/components/settings/navigation/settings-navigation-types'
|
||||
import {
|
||||
Blocks,
|
||||
Bot,
|
||||
BrushCleaning,
|
||||
CircleUserRound,
|
||||
Mic,
|
||||
MousePointerClick,
|
||||
@@ -175,6 +177,21 @@ export function buildSetupSettingsSections(
|
||||
searchEntries: getGeneralPaneSearchEntries({ includeProjectRuntime: isLocalWindowsHost }),
|
||||
group: 'setup'
|
||||
},
|
||||
...(showDesktopOnlySettings
|
||||
? [
|
||||
{
|
||||
id: 'workspace-cleanup',
|
||||
title: t('components.settings.workspaceCleanup.title', 'Workspace Cleanup'),
|
||||
description: t(
|
||||
'components.settings.workspaceCleanup.description',
|
||||
"Remove workspaces you're done with. Before removing anything, Orca checks again for unsaved work."
|
||||
),
|
||||
icon: BrushCleaning,
|
||||
searchEntries: getWorkspaceCleanupSettingsSearchEntries(),
|
||||
group: 'setup'
|
||||
}
|
||||
]
|
||||
: []),
|
||||
{
|
||||
id: 'integrations',
|
||||
title: t('auto.hooks.useSettingsNavigationMetadata.2b043783ef', 'Integrations'),
|
||||
|
||||
+30
@@ -2111,6 +2111,36 @@
|
||||
"workers_one": "{{count}} worker",
|
||||
"workers_other": "{{count}} workers"
|
||||
},
|
||||
"settings": {
|
||||
"workspaceCleanup": {
|
||||
"activity": {
|
||||
"notListed_one": "1 more kept workspace is not listed.",
|
||||
"notListed_other": "{{count}} more kept workspaces are not listed."
|
||||
},
|
||||
"change": {
|
||||
"description_one": "This change makes 1 more workspace match right now. It'll be deleted a few seconds after you apply it.",
|
||||
"description_other": "This change makes {{count}} more workspaces match right now. They'll be deleted a few seconds after you apply it."
|
||||
},
|
||||
"enable": {
|
||||
"description_one": "1 workspace matches right now. It'll be deleted a few seconds after you turn this on.",
|
||||
"description_other": "{{count}} workspaces match right now. They'll be deleted a few seconds after you turn this on."
|
||||
},
|
||||
"rules": {
|
||||
"inactiveDescription": "No activity for {{count}} days.",
|
||||
"inactiveDescription_one": "No activity for 1 day.",
|
||||
"inactiveDescription_other": "No activity for {{count}} days.",
|
||||
"matchesCount": "Matches {{count}} workspaces now",
|
||||
"matchesCount_one": "Matches 1 workspace now",
|
||||
"matchesCount_other": "Matches {{count}} workspaces now"
|
||||
},
|
||||
"status": {
|
||||
"lastRunFreed_one": "Last run {{when}} removed 1 workspace and freed {{size}}.",
|
||||
"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."
|
||||
}
|
||||
}
|
||||
},
|
||||
"tab": {
|
||||
"bar": {
|
||||
"bulkClose": {
|
||||
|
||||
@@ -22202,6 +22202,164 @@
|
||||
"folderArchiveDescription": "Local and shared scripts that run before a workspace is removed.",
|
||||
"folderSetupFieldDescription": "Runs after a new workspace is created; create child worktrees, install deps, copy env files.",
|
||||
"folderArchiveFieldDescription": "Runs before a workspace is removed."
|
||||
},
|
||||
"workspaceCleanup": {
|
||||
"title": "Workspace Cleanup",
|
||||
"description": "Remove workspaces you're done with. Before removing anything, Orca checks again for unsaved work.",
|
||||
"unsupportedHost": "This host runs an Orca version without automatic cleanup. Update Orca on it to use these settings.",
|
||||
"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.",
|
||||
"advancedDescription": "Automation and orchestration worker workspaces",
|
||||
"inactiveFor": "Inactive for",
|
||||
"days": "days",
|
||||
"then": "Then",
|
||||
"archiveDescription": "Archive frees disk space and keeps the workspace in the sidebar.",
|
||||
"deleteDescription": "Delete removes the workspace and its folder.",
|
||||
"archive": "Archive",
|
||||
"delete": "Delete",
|
||||
"matchesCount": "Matches {{count}} workspaces now",
|
||||
"hideMatches": "Hide",
|
||||
"showMatches": "Show",
|
||||
"merged": "Delete merged workspaces",
|
||||
"mergedDescription": "The pull request is merged and everything in the workspace is in it.",
|
||||
"unchanged": "Delete unchanged workspaces",
|
||||
"unchangedDescription": "No commits beyond the default branch and no edits.",
|
||||
"inactiveCleanUp": "Clean up inactive workspaces",
|
||||
"inactive": "Delete inactive workspaces",
|
||||
"automationRuns": "Delete finished automation workspaces",
|
||||
"automationRunsDescription": "Workspaces an automation run created, once the run has finished.",
|
||||
"orchestrationWorkers": "Delete released orchestration worker workspaces",
|
||||
"orchestrationWorkersDescription": "Workspaces an orchestration worker used, once the coordinator has released it.",
|
||||
"inactiveDescription_one": "No activity for 1 day.",
|
||||
"inactiveDescription_other": "No activity for {{count}} days.",
|
||||
"matchesCount_one": "Matches 1 workspace now",
|
||||
"matchesCount_other": "Matches {{count}} workspaces now",
|
||||
"checking": "Checking 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."
|
||||
},
|
||||
"activity": {
|
||||
"loadFailed": "Couldn't load activity: {{error}}",
|
||||
"empty": "Cleanup hasn't run yet.",
|
||||
"unfinished": "Couldn't finish",
|
||||
"nothingRemoved": "Nothing to clean",
|
||||
"removedCount": "{{count}} removed",
|
||||
"keptCount": "{{count}} kept",
|
||||
"failedCount": "{{count}} failed",
|
||||
"removed": "Removed · {{count}}",
|
||||
"failed": "Failed · {{count}}",
|
||||
"archived": "Archived",
|
||||
"deleted": "Deleted",
|
||||
"kept": "Kept · {{count}}",
|
||||
"showMore": "Show {{count}} more",
|
||||
"waiting": "Inactive {{elapsed}} of {{after}} days",
|
||||
"title": "Activity",
|
||||
"notListed_one": "1 more kept workspace is not listed.",
|
||||
"notListed_other": "{{count}} more kept workspaces are not listed."
|
||||
},
|
||||
"runFailed": "Couldn't run cleanup.",
|
||||
"updateFailed": "Couldn't save the cleanup rules.",
|
||||
"enable": {
|
||||
"title": "Turn on {{rule}}?",
|
||||
"description_one": "1 workspace matches right now. It'll be deleted a few seconds after you turn this on.",
|
||||
"description_other": "{{count}} workspaces match right now. They'll be deleted a few seconds after you turn this on.",
|
||||
"keepNamed": "Keep {{name}}",
|
||||
"keep": "Keep",
|
||||
"summary": "{{count}} will be deleted",
|
||||
"cancel": "Cancel",
|
||||
"turnOn": "Turn on"
|
||||
},
|
||||
"reason": {
|
||||
"merged": "Merged",
|
||||
"unchanged": "Unchanged",
|
||||
"inactive": "Inactive",
|
||||
"automationRun": "Automation run",
|
||||
"orchestrationWorker": "Orchestration worker",
|
||||
"mergedNumber": "{{label}} · #{{number}}"
|
||||
},
|
||||
"keep": {
|
||||
"pinned": "Pinned",
|
||||
"noRuleMatched": "No rule matched",
|
||||
"recentlyActive": "Used in the last hour",
|
||||
"activeWorkspace": "Open right now",
|
||||
"agentRunning": "Agent running",
|
||||
"terminalRunning": "Terminal running a process",
|
||||
"terminalUnknown": "Terminal state unknown",
|
||||
"unsavedEditorChanges": "Unsaved editor changes",
|
||||
"uncommittedChanges": "Uncommitted changes",
|
||||
"unpushedCommits": "Unpushed commits",
|
||||
"ignoredFiles": "Ignored files",
|
||||
"gitUnknown": "Couldn't read Git status",
|
||||
"archiveUnavailable": "Archive not available",
|
||||
"archiveScript": "Has an archive script",
|
||||
"removing": "Already being removed",
|
||||
"waiting": "Waiting",
|
||||
"notRemovable": "Main workspace or folder project",
|
||||
"projectOff": "Cleanup off for this project",
|
||||
"rulesOff": "No rule on",
|
||||
"withDetail": "{{cause}} · {{detail}}"
|
||||
},
|
||||
"trigger": {
|
||||
"startup": "On startup",
|
||||
"hourly": "Hourly",
|
||||
"settings": "After a rule change",
|
||||
"runNow": "Clean up now",
|
||||
"cli": "From the CLI"
|
||||
},
|
||||
"search": {
|
||||
"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.",
|
||||
"stale": "stale",
|
||||
"days": "days",
|
||||
"automations": "automations",
|
||||
"orchestration": "orchestration",
|
||||
"protection": "protection",
|
||||
"activityDescription": "What each cleanup run removed and kept.",
|
||||
"history": "history",
|
||||
"runs": "runs",
|
||||
"envFile": ".env"
|
||||
},
|
||||
"cleanUpNow": "Clean up now",
|
||||
"status": {
|
||||
"lastRunFailed": "Last run {{when}} couldn't finish: {{error}}",
|
||||
"lastRunNothing": "Last run {{when}} removed nothing.",
|
||||
"lastRunFreed_one": "Last run {{when}} removed 1 workspace and freed {{size}}.",
|
||||
"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"
|
||||
},
|
||||
"change": {
|
||||
"title": "Change {{rule}}?",
|
||||
"description_one": "This change makes 1 more workspace match right now. It'll be deleted a few seconds after you apply it.",
|
||||
"description_other": "This change makes {{count}} more workspaces match right now. They'll be deleted a few seconds after you apply it.",
|
||||
"apply": "Apply"
|
||||
},
|
||||
"rulesLoadFailed": "Couldn't load this host's cleanup rules: {{error}}",
|
||||
"retry": "Try again"
|
||||
}
|
||||
},
|
||||
"agentChildRow": {
|
||||
|
||||
@@ -113,6 +113,7 @@ function isRuntimeClientEvent(
|
||||
message.type === 'linearLinkedIssueUpdated' ||
|
||||
message.type === 'activateWorktree' ||
|
||||
message.type === 'worktreeTerminalSleepState' ||
|
||||
message.type === 'workspaceViewChanged'
|
||||
message.type === 'workspaceViewChanged' ||
|
||||
message.type === 'workspaceCleanupRunFinished'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -758,6 +758,17 @@
|
||||
"components.settings.voice.cleanup.consent.title",
|
||||
"components.settings.voice.cleanup.consent.wait",
|
||||
"components.settings.voice.cleanup.consent.waitLabel",
|
||||
"components.settings.workspaceCleanup.change.apply",
|
||||
"components.settings.workspaceCleanup.change.description",
|
||||
"components.settings.workspaceCleanup.change.title",
|
||||
"components.settings.workspaceCleanup.enable.cancel",
|
||||
"components.settings.workspaceCleanup.enable.description",
|
||||
"components.settings.workspaceCleanup.enable.keep",
|
||||
"components.settings.workspaceCleanup.enable.keepNamed",
|
||||
"components.settings.workspaceCleanup.enable.summary",
|
||||
"components.settings.workspaceCleanup.enable.title",
|
||||
"components.settings.workspaceCleanup.enable.turnOn",
|
||||
"components.settings.workspaceCleanup.reason.mergedNumber",
|
||||
"components.workspace.cleanup.browse.forceDeleteRisk",
|
||||
"components.workspace.cleanup.browse.gitStatusCheckFailed",
|
||||
"components.workspace.cleanup.browse.gitStatusUnverified",
|
||||
|
||||
@@ -49,7 +49,7 @@ export function hasEnabledWorkspaceCleanupRule(rules: WorkspaceCleanupRules): bo
|
||||
}
|
||||
|
||||
// Flip when workspace archiving exists.
|
||||
const WORKSPACE_ARCHIVE_SUPPORTED = false
|
||||
export const WORKSPACE_ARCHIVE_SUPPORTED = false
|
||||
|
||||
export function getDefaultWorkspaceCleanupRules(): WorkspaceCleanupRules {
|
||||
return {
|
||||
|
||||
@@ -32,21 +32,32 @@ export type WorkspaceCleanupWorkspaceRef = {
|
||||
path: string
|
||||
}
|
||||
|
||||
export type WorkspaceCleanupRunRow = WorkspaceCleanupWorkspaceRef & {
|
||||
outcome: WorkspaceCleanupRunOutcome
|
||||
reason?: WorkspaceCleanupRuleReason
|
||||
keepCause?: WorkspaceCleanupKeepCause
|
||||
waiting?: WorkspaceCleanupWaiting
|
||||
/** Kept because the re-check right before removal found something new. */
|
||||
keptOnRecheck?: true
|
||||
/** The unmerged branch Git kept after the checkout was removed. */
|
||||
branchKept?: string
|
||||
/** Last measured checkout size; absent when Orca never measured it. */
|
||||
sizeBytes?: number
|
||||
/** Plain-words failure for 'failed' rows. */
|
||||
error?: string
|
||||
// Evidence the run already read, kept so a row can say which PR or which files; older runs lack it.
|
||||
export const WORKSPACE_CLEANUP_ROW_IGNORED_FILE_LIMIT = 3
|
||||
|
||||
export type WorkspaceCleanupRowDetails = {
|
||||
/** The merged pull request that holds HEAD. */
|
||||
prNumber?: number
|
||||
/** Ignored files the main checkout lacks; `samplePaths` holds at most a few names. */
|
||||
ignoredFiles?: { count: number; samplePaths: string[]; complete: boolean }
|
||||
}
|
||||
|
||||
export type WorkspaceCleanupRunRow = WorkspaceCleanupWorkspaceRef &
|
||||
WorkspaceCleanupRowDetails & {
|
||||
outcome: WorkspaceCleanupRunOutcome
|
||||
reason?: WorkspaceCleanupRuleReason
|
||||
keepCause?: WorkspaceCleanupKeepCause
|
||||
waiting?: WorkspaceCleanupWaiting
|
||||
/** Kept because the re-check right before removal found something new. */
|
||||
keptOnRecheck?: true
|
||||
/** The unmerged branch Git kept after the checkout was removed. */
|
||||
branchKept?: string
|
||||
/** Last measured checkout size; absent when Orca never measured it. */
|
||||
sizeBytes?: number
|
||||
/** Plain-words failure for 'failed' rows. */
|
||||
error?: string
|
||||
}
|
||||
|
||||
export type WorkspaceCleanupRun = {
|
||||
id: string
|
||||
trigger: WorkspaceCleanupRunTrigger
|
||||
@@ -69,10 +80,11 @@ export type WorkspaceCleanupReport = {
|
||||
nextRunAt: number | null
|
||||
}
|
||||
|
||||
export type WorkspaceCleanupPreviewRow = WorkspaceCleanupWorkspaceRef & {
|
||||
evaluation: WorkspaceCleanupEvaluation
|
||||
sizeBytes?: number
|
||||
}
|
||||
export type WorkspaceCleanupPreviewRow = WorkspaceCleanupWorkspaceRef &
|
||||
WorkspaceCleanupRowDetails & {
|
||||
evaluation: WorkspaceCleanupEvaluation
|
||||
sizeBytes?: number
|
||||
}
|
||||
|
||||
export type WorkspaceCleanupPreview = {
|
||||
evaluatedAt: number
|
||||
|
||||
Reference in New Issue
Block a user