Clean up old workspaces (#1873)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-05-15 14:00:23 -07:00
committed by GitHub
co-authored by Orca
parent 8fff0a08e0
commit f5cc8196f9
23 changed files with 3511 additions and 14 deletions
+418
View File
@@ -0,0 +1,418 @@
/* eslint-disable max-lines -- Why: scan and IPC process-liveness tests share
hoisted Electron/git provider mocks; splitting would duplicate brittle setup. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ipcMain } from 'electron'
import type { Store } from '../persistence'
import type { DiffComment, GitStatusResult, Repo } from '../../shared/types'
const {
listRepoWorktreesMock,
getStatusMock,
gitExecFileAsyncMock,
getSshGitProviderMock,
getSshPtyProviderMock,
listRegisteredPtysMock
} = vi.hoisted(() => ({
listRepoWorktreesMock: vi.fn(),
getStatusMock: vi.fn(),
gitExecFileAsyncMock: vi.fn(),
getSshGitProviderMock: vi.fn(),
getSshPtyProviderMock: vi.fn(),
listRegisteredPtysMock: vi.fn()
}))
vi.mock('electron', () => ({
ipcMain: {
handle: vi.fn(),
removeHandler: vi.fn()
}
}))
vi.mock('../repo-worktrees', () => ({
listRepoWorktrees: listRepoWorktreesMock,
createFolderWorktree: vi.fn()
}))
vi.mock('../git/status', () => ({
getStatus: getStatusMock
}))
vi.mock('../git/runner', () => ({
gitExecFileAsync: gitExecFileAsyncMock
}))
vi.mock('../providers/ssh-git-dispatch', () => ({
getSshGitProvider: getSshGitProviderMock
}))
vi.mock('../memory/pty-registry', () => ({
listRegisteredPtys: listRegisteredPtysMock
}))
vi.mock('./pty', () => ({
getSshPtyProvider: getSshPtyProviderMock
}))
import { registerWorkspaceCleanupHandlers, scanWorkspaceCleanup } from './workspace-cleanup'
const NOW = 1_700_000_000_000
const REPO: Repo = {
id: 'repo-1',
path: '/repo',
displayName: 'Repo',
badgeColor: '#000',
addedAt: NOW
}
function makeStore(
options: {
baseRef?: string
diffComments?: DiffComment[]
lastActivityAt?: number
linkedIssue?: number | null
repos?: Repo[]
} = {}
): Store {
const baseRef = Object.hasOwn(options, 'baseRef') ? options.baseRef : 'origin/main'
return {
getRepos: () => options.repos ?? [REPO],
getWorktreeMeta: () => ({
linkedPR: null,
linkedIssue: options.linkedIssue ?? null,
lastActivityAt: options.lastActivityAt ?? NOW - 40 * 24 * 60 * 60 * 1000,
baseRef,
diffComments: options.diffComments
}),
getAllWorktreeMeta: () => ({}),
getGitHubCache: () => ({
pr: {},
issue: {}
})
} as unknown as Store
}
describe('workspace cleanup scan', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(NOW)
listRepoWorktreesMock.mockReset()
getStatusMock.mockReset()
gitExecFileAsyncMock.mockReset()
getSshGitProviderMock.mockReset()
getSshPtyProviderMock.mockReset()
listRegisteredPtysMock.mockReset()
listRegisteredPtysMock.mockReturnValue([])
vi.mocked(ipcMain.handle).mockReset()
vi.mocked(ipcMain.removeHandler).mockReset()
listRepoWorktreesMock.mockResolvedValue([
{
path: '/repo-feature',
head: 'abc123',
branch: 'refs/heads/feature',
isBare: false,
isMainWorktree: false
}
])
getStatusMock.mockResolvedValue({
entries: [],
conflictOperation: 'unknown',
upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 }
} satisfies GitStatusResult)
gitExecFileAsyncMock.mockResolvedValue({ stdout: '0\n', stderr: '' })
getSshGitProviderMock.mockReturnValue(undefined)
})
afterEach(() => {
vi.useRealTimers()
})
it('default-selects inactive workspaces when git status is clean', async () => {
const result = await scanWorkspaceCleanup(makeStore())
expect(getStatusMock).toHaveBeenCalledTimes(1)
expect(result.candidates).toHaveLength(1)
expect(result.candidates[0]).toMatchObject({
tier: 'ready',
selectedByDefault: true,
reasons: ['idle-clean'],
git: {
clean: true,
upstreamAhead: 0
}
})
})
it('keeps raw scan errors out of renderer-facing results', async () => {
listRepoWorktreesMock.mockRejectedValue(new Error('fatal: path /Users/alice/private failed'))
const result = await scanWorkspaceCleanup(makeStore())
expect(result.errors).toEqual([
{
repoId: 'repo-1',
repoName: 'Repo',
message: 'Git could not list worktrees.'
}
])
})
it('skips disconnected remote workspaces without a scan warning', async () => {
const result = await scanWorkspaceCleanup(
makeStore({
repos: [{ ...REPO, connectionId: 'ssh-1' }]
})
)
expect(result.errors).toEqual([])
expect(result.candidates).toEqual([])
})
it('scans connected remote workspaces through the SSH git provider', async () => {
const provider = {
listWorktrees: vi.fn().mockResolvedValue([
{
path: '/remote/repo-feature',
head: 'abc123',
branch: 'refs/heads/feature',
isBare: false,
isMainWorktree: false
}
]),
getStatus: vi.fn().mockResolvedValue({
entries: [],
conflictOperation: 'unknown',
upstreamStatus: { hasUpstream: true, ahead: 0, behind: 0 }
} satisfies GitStatusResult)
}
getSshGitProviderMock.mockReturnValue(provider)
const result = await scanWorkspaceCleanup(
makeStore({
repos: [{ ...REPO, connectionId: 'ssh-1' }]
})
)
expect(provider.listWorktrees).toHaveBeenCalledWith('/repo')
expect(provider.getStatus).toHaveBeenCalledWith('/remote/repo-feature')
expect(result.errors).toEqual([])
expect(result.candidates[0]).toMatchObject({
connectionId: 'ssh-1',
tier: 'ready',
selectedByDefault: true,
reasons: ['idle-clean']
})
})
it('skips connected remote workspaces that fail during broad scans', async () => {
const provider = {
listWorktrees: vi.fn().mockRejectedValue(new Error('ssh timeout')),
getStatus: vi.fn()
}
getSshGitProviderMock.mockReturnValue(provider)
const result = await scanWorkspaceCleanup(
makeStore({
repos: [{ ...REPO, connectionId: 'ssh-1' }]
})
)
expect(provider.listWorktrees).toHaveBeenCalledWith('/repo')
expect(result.errors).toEqual([])
expect(result.candidates).toEqual([])
})
it('filters out recent workspaces before running git status', async () => {
const result = await scanWorkspaceCleanup(
makeStore({
lastActivityAt: NOW - 2 * 24 * 60 * 60 * 1000
})
)
expect(getStatusMock).not.toHaveBeenCalled()
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
expect(result.candidates).toEqual([])
})
it('includes focused remove preflight rows even when they are recent', async () => {
const result = await scanWorkspaceCleanup(
makeStore({
lastActivityAt: NOW - 2 * 24 * 60 * 60 * 1000
}),
{ worktreeId: 'repo-1::/repo-feature' }
)
expect(getStatusMock).toHaveBeenCalledTimes(1)
expect(result.candidates[0]).toMatchObject({
tier: 'review',
selectedByDefault: false,
reasons: [],
git: {
clean: true,
checkedAt: expect.any(Number)
}
})
})
it('honors renderer git deferrals without hiding the workspace', async () => {
const result = await scanWorkspaceCleanup(makeStore(), {
skipGitWorktreeIds: ['repo-1::/repo-feature']
})
expect(getStatusMock).not.toHaveBeenCalled()
expect(result.candidates[0]).toMatchObject({
tier: 'review',
selectedByDefault: false,
reasons: ['idle-clean'],
git: {
clean: null,
checkedAt: null
}
})
})
it('uses remote commit presence when a clean inactive workspace has no upstream', async () => {
getStatusMock.mockResolvedValue({
entries: [],
conflictOperation: 'unknown',
upstreamStatus: { hasUpstream: false, ahead: 0, behind: 0 }
} satisfies GitStatusResult)
const result = await scanWorkspaceCleanup(makeStore())
expect(getStatusMock).toHaveBeenCalledTimes(1)
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(
['rev-list', '--count', 'HEAD', '--not', '--remotes'],
{ cwd: '/repo-feature' }
)
expect(result.candidates[0]).toMatchObject({
tier: 'ready',
selectedByDefault: true,
git: {
clean: true,
upstreamAhead: null
}
})
})
it('protects clean inactive workspaces with local-only commits', async () => {
getStatusMock.mockResolvedValue({
entries: [],
conflictOperation: 'unknown',
upstreamStatus: { hasUpstream: false, ahead: 0, behind: 0 }
} satisfies GitStatusResult)
gitExecFileAsyncMock.mockResolvedValue({ stdout: '2\n', stderr: '' })
const result = await scanWorkspaceCleanup(makeStore())
expect(result.candidates[0]).toMatchObject({
tier: 'protected',
selectedByDefault: false,
blockers: ['unpushed-commits'],
git: {
clean: true,
upstreamAhead: null
}
})
})
it('keeps diff notes as context instead of blocking inactive cleanup', async () => {
const result = await scanWorkspaceCleanup(
makeStore({
baseRef: undefined,
diffComments: [
{
id: 'comment-1',
worktreeId: 'repo-1::/repo-feature',
filePath: 'src/file.ts',
lineNumber: 12,
body: 'Follow up before deleting',
createdAt: NOW - 1_000,
side: 'modified'
}
]
})
)
expect(result.candidates[0]).toMatchObject({
tier: 'ready',
selectedByDefault: true,
reasons: ['idle-clean'],
localContext: {
diffCommentCount: 1,
newestDiffCommentAt: NOW - 1_000
}
})
})
it('does not expose PR cache state in inactivity cleanup results', async () => {
const result = await scanWorkspaceCleanup(
makeStore({
repos: [REPO, { ...REPO, id: 'repo-2' }]
})
)
expect(result.candidates[0]).toMatchObject({
tier: 'ready',
selectedByDefault: true,
reasons: ['idle-clean']
})
expect(result.candidates[0]).not.toHaveProperty('linkedPR')
})
it('reports local processes that workspace deletion would kill', async () => {
const localProvider = {
listProcesses: vi.fn().mockResolvedValue([
{
id: 'repo-1::/repo-feature@@session-1',
cwd: '/repo-feature',
title: 'zsh'
}
])
}
registerWorkspaceCleanupHandlers(makeStore(), {
runtime: {
hasTerminalsForWorktree: vi.fn().mockResolvedValue(false)
} as never,
getLocalPtyProvider: () => localProvider as never
})
const handler = vi
.mocked(ipcMain.handle)
.mock.calls.find(([channel]) => channel === 'workspaceCleanup:hasKillableLocalProcesses')?.[1]
await expect(handler?.({} as never, { worktreeId: 'repo-1::/repo-feature' })).resolves.toEqual({
hasKillableProcesses: true
})
})
it('reports SSH processes inside the remote workspace path', async () => {
getSshPtyProviderMock.mockReturnValue({
listProcesses: vi.fn().mockResolvedValue([
{
id: 'remote-session-1',
cwd: '/remote/repo-feature/subdir',
title: 'codex'
}
])
})
registerWorkspaceCleanupHandlers(makeStore(), {
runtime: {
hasTerminalsForWorktree: vi.fn().mockResolvedValue(false)
} as never
})
const handler = vi
.mocked(ipcMain.handle)
.mock.calls.find(([channel]) => channel === 'workspaceCleanup:hasKillableLocalProcesses')?.[1]
await expect(
handler?.({} as never, {
worktreeId: 'repo-ssh::/remote/repo-feature',
connectionId: 'ssh-1',
worktreePath: '/remote/repo-feature'
})
).resolves.toEqual({
hasKillableProcesses: true
})
})
})
+700
View File
@@ -0,0 +1,700 @@
/* eslint-disable max-lines */
import { ipcMain } from 'electron'
import { basename } from 'node:path'
import type { Store } from '../persistence'
import { getStatus } from '../git/status'
import { gitExecFileAsync } from '../git/runner'
import { listRepoWorktrees, createFolderWorktree } from '../repo-worktrees'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
import type { IGitProvider, IPtyProvider } from '../providers/types'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import { listRegisteredPtys } from '../memory/pty-registry'
import { getSshPtyProvider } from './pty'
import { isFolderRepo } from '../../shared/repo-kind'
import type { GitStatusResult, GitWorktreeInfo, Repo, Worktree } from '../../shared/types'
import { mergeWorktree } from './worktree-logic'
import { splitWorktreeId } from '../../shared/worktree-id'
import {
WORKSPACE_CLEANUP_CLASSIFIER_VERSION,
applyWorkspaceCleanupPolicy,
createWorkspaceCleanupFingerprint,
getWorkspaceCleanupInactivityReasons,
isWorkspaceOldForCleanup,
type WorkspaceCleanupBlocker,
type WorkspaceCleanupCandidate,
type WorkspaceCleanupDismissArgs,
type WorkspaceCleanupLocalProcessArgs,
type WorkspaceCleanupLocalProcessResult,
type WorkspaceCleanupReason,
type WorkspaceCleanupScanError,
type WorkspaceCleanupScanArgs,
type WorkspaceCleanupScanResult
} from '../../shared/workspace-cleanup'
const GIT_READ_TIMEOUT_MS = 8_000
const WORKTREE_SCAN_CONCURRENCY = 3
type GitEvidence = {
clean: boolean | null
upstreamAhead: number | null
upstreamBehind: number | null
checkedAt: number | null
blockers: WorkspaceCleanupBlocker[]
}
type WorkspaceCleanupHandlerDeps = {
runtime?: OrcaRuntimeService
getLocalPtyProvider?: () => IPtyProvider
}
export function registerWorkspaceCleanupHandlers(
store: Store,
deps: WorkspaceCleanupHandlerDeps = {}
): void {
ipcMain.removeHandler('workspaceCleanup:scan')
ipcMain.removeHandler('workspaceCleanup:dismiss')
ipcMain.removeHandler('workspaceCleanup:clearDismissals')
ipcMain.removeHandler('workspaceCleanup:hasKillableLocalProcesses')
ipcMain.handle(
'workspaceCleanup:scan',
(_event, args?: WorkspaceCleanupScanArgs): Promise<WorkspaceCleanupScanResult> =>
scanWorkspaceCleanup(store, args ?? {})
)
ipcMain.handle('workspaceCleanup:dismiss', (_event, args: WorkspaceCleanupDismissArgs) => {
const current = store.getUI().workspaceCleanup?.dismissals ?? {}
const next = { ...current }
for (const dismissal of args.dismissals ?? []) {
if (
dismissal &&
dismissal.classifierVersion === WORKSPACE_CLEANUP_CLASSIFIER_VERSION &&
typeof dismissal.worktreeId === 'string' &&
typeof dismissal.fingerprint === 'string'
) {
next[dismissal.worktreeId] = dismissal
}
}
store.updateUI({ workspaceCleanup: { dismissals: next } })
})
ipcMain.handle('workspaceCleanup:clearDismissals', () => {
store.updateUI({ workspaceCleanup: { dismissals: {} } })
})
ipcMain.handle(
'workspaceCleanup:hasKillableLocalProcesses',
async (
_event,
args: WorkspaceCleanupLocalProcessArgs
): Promise<WorkspaceCleanupLocalProcessResult> => ({
hasKillableProcesses: await hasKillableProcesses(args, deps)
})
)
}
async function hasKillableProcesses(
args: WorkspaceCleanupLocalProcessArgs,
deps: WorkspaceCleanupHandlerDeps
): Promise<boolean | null> {
const { worktreeId } = args
if (typeof worktreeId !== 'string' || worktreeId.length === 0) {
return false
}
let livenessUnknown = false
if (deps.runtime) {
try {
if (await deps.runtime.hasTerminalsForWorktree(worktreeId)) {
return true
}
} catch {
livenessUnknown = true
}
}
if (args.connectionId) {
return hasKillableSshProcesses(args.connectionId, args.worktreePath ?? '', livenessUnknown)
}
const registryPtyIds = new Set(
listRegisteredPtys()
.filter((entry) => entry.worktreeId === worktreeId)
.map((entry) => entry.ptyId)
)
const provider = deps.getLocalPtyProvider?.()
if (!provider) {
return registryPtyIds.size > 0 ? true : null
}
try {
const prefix = `${worktreeId}@@`
const sessions = await provider.listProcesses()
if (
sessions.some((session) => session.id.startsWith(prefix) || registryPtyIds.has(session.id))
) {
return true
}
return livenessUnknown ? null : false
} catch {
return registryPtyIds.size > 0 ? true : null
}
}
async function hasKillableSshProcesses(
connectionId: string,
worktreePath: string,
livenessUnknown: boolean
): Promise<boolean | null> {
const provider = getSshPtyProvider(connectionId)
if (!provider) {
return null
}
try {
const normalizedWorktreePath = normalizeRemotePath(worktreePath)
const sessions = await provider.listProcesses()
if (
sessions.some((session) => {
if (session.id.startsWith(`${worktreePath}@@`)) {
return true
}
return (
normalizedWorktreePath.length > 0 &&
isPathWithin(normalizeRemotePath(session.cwd), normalizedWorktreePath)
)
})
) {
return true
}
return livenessUnknown ? null : false
} catch {
return null
}
}
function normalizeRemotePath(path: string): string {
return path.replace(/\\/g, '/').replace(/\/+$/, '')
}
function isPathWithin(candidatePath: string, parentPath: string): boolean {
return candidatePath === parentPath || candidatePath.startsWith(`${parentPath}/`)
}
export async function scanWorkspaceCleanup(
store: Store,
args: WorkspaceCleanupScanArgs = {}
): Promise<WorkspaceCleanupScanResult> {
const scannedAt = Date.now()
const repos = store.getRepos()
const errors: WorkspaceCleanupScanResult['errors'] = []
const candidates: WorkspaceCleanupCandidate[] = []
for (const repo of repos) {
const result = await scanRepoWorkspaces({
store,
repo,
scannedAt,
targetWorktreeId: args.worktreeId,
skipGitWorktreeIds: new Set(args.skipGitWorktreeIds ?? [])
})
candidates.push(...result.candidates)
errors.push(...result.errors)
}
return { scannedAt, candidates, errors }
}
async function scanRepoWorkspaces(args: {
store: Store
repo: Repo
scannedAt: number
targetWorktreeId?: string
skipGitWorktreeIds: Set<string>
}): Promise<WorkspaceCleanupScanResult> {
const { store, repo, scannedAt, targetWorktreeId, skipGitWorktreeIds } = args
const errors: WorkspaceCleanupScanResult['errors'] = []
let provider: IGitProvider | null = null
let gitWorktrees: GitWorktreeInfo[] = []
const repoIsFolder = isFolderRepo(repo)
try {
if (repoIsFolder) {
gitWorktrees = [createFolderWorktree(repo)]
} else if (repo.connectionId) {
provider = getSshGitProvider(repo.connectionId) ?? null
if (!provider) {
// Why: cleanup should reflect only workspaces Orca can currently
// inspect. Disconnected SSH repos are skipped in broad scans.
return {
scannedAt,
candidates: targetWorktreeId
? synthesizeDisconnectedSshCandidates(store, repo, scannedAt, targetWorktreeId)
: [],
errors: []
}
}
gitWorktrees = await withTimeout(
provider.listWorktrees(repo.path),
GIT_READ_TIMEOUT_MS,
'Timed out listing SSH worktrees.'
)
} else {
gitWorktrees = await withTimeout(
listRepoWorktrees(repo),
GIT_READ_TIMEOUT_MS,
'Timed out listing worktrees.'
)
}
} catch (error) {
console.error('Workspace cleanup repo scan failed', error)
if (repo.connectionId && !targetWorktreeId) {
// Why: broad cleanup only shows remote workspaces Orca can inspect now.
// A connected SSH repo that fails mid-scan is omitted, not bannered.
return { scannedAt, candidates: [], errors: [] }
}
errors.push(createScanError(repo, toSafeRepoScanError(error)))
return { scannedAt, candidates: [], errors }
}
const worktrees = gitWorktrees
.map((gitWorktree) => {
const worktreeId = `${repo.id}::${gitWorktree.path}`
const meta = store.getWorktreeMeta(worktreeId)
return mergeWorktree(repo.id, gitWorktree, meta, repo.displayName)
})
.filter((worktree) => {
if (targetWorktreeId) {
return worktree.id === targetWorktreeId
}
return (
!repoIsFolder &&
!worktree.isMainWorktree &&
isWorkspaceInactiveForCleanup(worktree, scannedAt)
)
})
const candidates = await mapWithConcurrency(worktrees, WORKTREE_SCAN_CONCURRENCY, (worktree) =>
buildCandidate({
repo,
worktree,
scannedAt,
provider,
skipGit: skipGitWorktreeIds.has(worktree.id),
forceGitCheck: Boolean(targetWorktreeId)
}).catch((error) => {
console.error('Workspace cleanup candidate scan failed', error)
return buildCandidateFromError(repo, worktree, scannedAt, toErrorMessage(error))
})
)
return { scannedAt, candidates, errors }
}
async function buildCandidate(args: {
repo: Repo
worktree: Worktree
scannedAt: number
provider: IGitProvider | null
skipGit: boolean
forceGitCheck: boolean
}): Promise<WorkspaceCleanupCandidate> {
const { repo, worktree, scannedAt, provider, skipGit, forceGitCheck } = args
const blockers: WorkspaceCleanupBlocker[] = []
const reasons = getInactivityReasons(worktree, scannedAt)
const repoIsFolder = isFolderRepo(repo)
if (worktree.isMainWorktree) {
blockers.push('main-worktree')
}
if (repoIsFolder) {
blockers.push('folder-repo')
}
if (worktree.isPinned) {
blockers.push('pinned')
}
const localContext = buildLocalContext(worktree)
const shouldReadGit = shouldReadGitEvidence({
repoIsFolder,
blockers,
worktree,
skipGit,
forceGitCheck
})
const gitEvidence = !shouldReadGit
? createEmptyGitEvidence()
: await readGitEvidence(worktree, repo, provider)
blockers.push(...gitEvidence.blockers)
const candidateWithoutFingerprint: WorkspaceCleanupCandidate = {
worktreeId: worktree.id,
repoId: repo.id,
repoName: repo.displayName,
connectionId: repo.connectionId ?? null,
displayName: worktree.displayName,
branch: shortBranchName(worktree.branch),
path: worktree.path,
tier: 'review',
selectedByDefault: false,
reasons,
blockers: uniqueBlockers(blockers),
lastActivityAt: worktree.lastActivityAt,
...(worktree.createdAt !== undefined ? { createdAt: worktree.createdAt } : {}),
localContext,
git: {
clean: gitEvidence.clean,
upstreamAhead: gitEvidence.upstreamAhead,
upstreamBehind: gitEvidence.upstreamBehind,
checkedAt: gitEvidence.checkedAt
},
fingerprint: ''
}
const fingerprint = createWorkspaceCleanupFingerprint({
branch: candidateWithoutFingerprint.branch,
head: worktree.head,
gitClean: gitEvidence.clean,
lastActivityAt: worktree.lastActivityAt
})
return applyWorkspaceCleanupPolicy({
...candidateWithoutFingerprint,
reasons: uniqueReasons(reasons),
blockers: uniqueBlockers(blockers),
fingerprint
})
}
function shouldReadGitEvidence(args: {
repoIsFolder: boolean
blockers: WorkspaceCleanupBlocker[]
worktree: Worktree
skipGit: boolean
forceGitCheck: boolean
}): boolean {
const { repoIsFolder, blockers, worktree, skipGit, forceGitCheck } = args
if ((skipGit && !forceGitCheck) || repoIsFolder || worktree.isMainWorktree) {
return false
}
if (
blockers.includes('pinned') ||
blockers.includes('main-worktree') ||
blockers.includes('folder-repo')
) {
return false
}
// Why: inactivity is the only recommendation signal now. Git is read only
// to keep the destructive path from deleting dirty or local-only branch work.
return true
}
async function readGitEvidence(
worktree: Worktree,
repo: Repo,
provider: IGitProvider | null
): Promise<GitEvidence> {
const blockers: WorkspaceCleanupBlocker[] = []
let status: GitStatusResult
const checkedAt = Date.now()
try {
status = await withTimeout(
repo.connectionId ? provider!.getStatus(worktree.path) : getStatus(worktree.path),
GIT_READ_TIMEOUT_MS,
'Timed out reading git status.'
)
} catch {
return {
...createEmptyGitEvidence(),
blockers: ['git-status-error']
}
}
if (status.upstreamStatus === undefined) {
return {
...createEmptyGitEvidence(),
blockers: ['git-status-error']
}
}
const clean = status.entries.length === 0
if (!clean) {
blockers.push('dirty-files')
}
const upstreamAhead = status.upstreamStatus.hasUpstream ? status.upstreamStatus.ahead : null
const upstreamBehind = status.upstreamStatus.hasUpstream ? status.upstreamStatus.behind : null
if (upstreamAhead !== null && upstreamAhead > 0) {
blockers.push('unpushed-commits')
}
if (clean && upstreamAhead === null) {
const unpushedCommitCount = await readUnpushedCommitCount(worktree, repo, provider)
if (unpushedCommitCount === null) {
blockers.push('unknown-base')
} else if (unpushedCommitCount > 0) {
blockers.push('unpushed-commits')
}
}
const evidence: GitEvidence = {
clean,
upstreamAhead,
upstreamBehind,
checkedAt,
blockers
}
return { ...evidence, blockers: uniqueBlockers(blockers) }
}
async function readUnpushedCommitCount(
worktree: Worktree,
repo: Repo,
provider: IGitProvider | null
): Promise<number | null> {
try {
const result = await withTimeout(
repo.connectionId
? provider!.exec(['rev-list', '--count', 'HEAD', '--not', '--remotes'], worktree.path)
: gitExecFileAsync(['rev-list', '--count', 'HEAD', '--not', '--remotes'], {
cwd: worktree.path
}),
GIT_READ_TIMEOUT_MS,
'Timed out checking unpushed commits.'
)
const count = Number.parseInt(result.stdout.trim(), 10)
return Number.isFinite(count) ? count : null
} catch {
return null
}
}
function buildCandidateFromError(
repo: Repo,
worktree: Worktree,
scannedAt: number,
_message: string
): WorkspaceCleanupCandidate {
return applyWorkspaceCleanupPolicy({
worktreeId: worktree.id,
repoId: repo.id,
repoName: repo.displayName,
connectionId: repo.connectionId ?? null,
displayName: worktree.displayName,
branch: shortBranchName(worktree.branch),
path: worktree.path,
tier: 'protected',
selectedByDefault: false,
reasons: getInactivityReasons(worktree, scannedAt),
blockers: ['git-status-error'],
lastActivityAt: worktree.lastActivityAt,
...(worktree.createdAt !== undefined ? { createdAt: worktree.createdAt } : {}),
localContext: buildLocalContext(worktree),
git: {
clean: null,
upstreamAhead: null,
upstreamBehind: null,
checkedAt: scannedAt
},
fingerprint: createWorkspaceCleanupFingerprint({
branch: shortBranchName(worktree.branch),
head: worktree.head,
gitClean: null,
lastActivityAt: worktree.lastActivityAt
})
})
}
function synthesizeDisconnectedSshCandidates(
store: Store,
repo: Repo,
scannedAt: number,
targetWorktreeId?: string
): WorkspaceCleanupCandidate[] {
return Object.entries(store.getAllWorktreeMeta())
.filter(([worktreeId, meta]) => {
if (!worktreeId.startsWith(`${repo.id}::`)) {
return false
}
if (targetWorktreeId) {
return targetWorktreeId === worktreeId
}
return isWorkspaceInactiveForCleanup(meta, scannedAt)
})
.map(([worktreeId, meta]) => {
const parsed = splitWorktreeId(worktreeId)
const path = parsed?.worktreePath ?? worktreeId
const reasons = getInactivityReasons(meta, scannedAt)
return applyWorkspaceCleanupPolicy({
worktreeId,
repoId: repo.id,
repoName: repo.displayName,
connectionId: repo.connectionId ?? null,
displayName: meta.displayName || basename(path),
branch: basename(path),
path,
tier: 'protected',
selectedByDefault: false,
reasons,
blockers: ['ssh-disconnected'],
lastActivityAt: meta.lastActivityAt,
...(meta.createdAt !== undefined ? { createdAt: meta.createdAt } : {}),
localContext: {
terminalTabCount: 0,
cleanEditorTabCount: 0,
browserTabCount: 0,
diffCommentCount: meta.diffComments?.length ?? 0,
newestDiffCommentAt: getNewestDiffCommentAt(meta.diffComments),
retainedDoneAgentCount: 0
},
git: {
clean: null,
upstreamAhead: null,
upstreamBehind: null,
checkedAt: null
},
fingerprint: createWorkspaceCleanupFingerprint({
branch: basename(path),
head: '',
gitClean: null,
lastActivityAt: meta.lastActivityAt
})
})
})
}
function buildLocalContext(worktree: Worktree): WorkspaceCleanupCandidate['localContext'] {
return {
terminalTabCount: 0,
cleanEditorTabCount: 0,
browserTabCount: 0,
diffCommentCount: worktree.diffComments?.length ?? 0,
newestDiffCommentAt: getNewestDiffCommentAt(worktree.diffComments),
retainedDoneAgentCount: 0
}
}
function getNewestDiffCommentAt(diffComments: Worktree['diffComments'] | undefined): number | null {
if (!diffComments || diffComments.length === 0) {
return null
}
return Math.max(...diffComments.map((comment) => comment.createdAt))
}
function createEmptyGitEvidence(): GitEvidence {
return {
clean: null,
upstreamAhead: null,
upstreamBehind: null,
checkedAt: null,
blockers: []
}
}
function shortBranchName(branch: string): string {
return branch.replace(/^refs\/heads\//, '') || 'HEAD'
}
function uniqueBlockers(blockers: WorkspaceCleanupBlocker[]): WorkspaceCleanupBlocker[] {
return [...new Set(blockers)]
}
function uniqueReasons(reasons: WorkspaceCleanupReason[]): WorkspaceCleanupReason[] {
return [...new Set(reasons)]
}
function isWorkspaceInactiveForCleanup(
workspace: Pick<Worktree, 'isArchived' | 'lastActivityAt'>,
scannedAt: number
): boolean {
return isWorkspaceOldForCleanup(workspace, scannedAt)
}
function getInactivityReasons(
workspace: Pick<Worktree, 'isArchived' | 'lastActivityAt'>,
scannedAt: number
): WorkspaceCleanupReason[] {
return getWorkspaceCleanupInactivityReasons(workspace, scannedAt)
}
async function mapWithConcurrency<T, R>(
items: readonly T[],
limit: number,
fn: (item: T) => Promise<R>
): Promise<R[]> {
const results: R[] = []
let nextIndex = 0
const workerCount = Math.min(limit, items.length)
await Promise.all(
Array.from({ length: workerCount }, async () => {
while (nextIndex < items.length) {
const index = nextIndex
nextIndex += 1
results[index] = await fn(items[index])
}
})
)
return results
}
async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, message: string): Promise<T> {
let timeoutId: NodeJS.Timeout | undefined
const timeoutPromise = new Promise<T>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error(message)), timeoutMs)
})
try {
return await Promise.race([promise, timeoutPromise])
} finally {
if (timeoutId) {
clearTimeout(timeoutId)
}
}
}
function toErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error)
}
function createScanError(repo: Repo, message: string): WorkspaceCleanupScanError {
return {
repoId: repo.id,
repoName: repo.displayName || basename(repo.path),
message
}
}
// Why: git errors often include absolute paths or command output. Keep the
// cause useful without leaking raw local/remote filesystem details to the UI.
function toSafeRepoScanError(error: unknown): string {
const message = toErrorMessage(error)
if (message === 'Timed out listing SSH worktrees.') {
return 'Timed out listing remote worktrees.'
}
if (message === 'Timed out listing worktrees.') {
return 'Timed out listing worktrees.'
}
if (message.startsWith('Timed out ')) {
return message.replace(/\.$/, '')
}
const lower = message.toLowerCase()
if (lower.includes('not a git repository') || lower.includes('not a git worktree')) {
return 'Repository is not a git checkout.'
}
if (
lower.includes('enoent') ||
lower.includes('no such file') ||
lower.includes('cannot find') ||
lower.includes('does not exist')
) {
return 'Repository folder was not found.'
}
if (lower.includes('eacces') || lower.includes('eperm') || lower.includes('permission denied')) {
return 'Repository folder is not accessible.'
}
return 'Git could not list worktrees.'
}
+17
View File
@@ -6466,6 +6466,23 @@ export class OrcaRuntimeService {
return { stopped }
}
async hasTerminalsForWorktree(worktreeSelector: string): Promise<boolean> {
const graphEpoch = this.captureReadyGraphEpoch()
const worktree = await this.resolveWorktreeSelector(worktreeSelector)
this.assertStableReadyGraph(graphEpoch)
for (const leaf of this.leaves.values()) {
if (leaf.worktreeId === worktree.id && leaf.ptyId) {
return true
}
}
for (const pty of this.ptysById.values()) {
if (pty.worktreeId === worktree.id && pty.connected) {
return true
}
}
return false
}
markRendererReloading(windowId: number): void {
if (windowId !== this.authoritativeWindowId) {
return
@@ -61,6 +61,7 @@ vi.mock('../ipc/worktrees', () => ({
}))
vi.mock('../ipc/pty', () => ({
getLocalPtyProvider: vi.fn(),
registerPtyHandlers: registerPtyHandlersMock
}))
@@ -10,7 +10,8 @@ import type { CreateWorktreeResult, WorktreeStartupLaunch } from '../../shared/t
import { ORCA_BROWSER_PARTITION } from '../../shared/constants'
import { registerRepoHandlers } from '../ipc/repos'
import { registerWorktreeHandlers } from '../ipc/worktrees'
import { registerPtyHandlers } from '../ipc/pty'
import { registerWorkspaceCleanupHandlers } from '../ipc/workspace-cleanup'
import { getLocalPtyProvider, registerPtyHandlers } from '../ipc/pty'
import { registerDaemonManagementHandlers } from '../ipc/pty-management'
import { registerSshHandlers } from '../ipc/ssh'
import { registerRemoteWorkspaceHandlers } from '../ipc/remote-workspace'
@@ -44,6 +45,7 @@ export function attachMainWindowServices(
): void {
registerRepoHandlers(mainWindow, store)
registerWorktreeHandlers(mainWindow, store, runtime)
registerWorkspaceCleanupHandlers(store, { runtime, getLocalPtyProvider })
registerPtyHandlers(
mainWindow,
runtime,
+15
View File
@@ -229,6 +229,13 @@ import type {
AutomationRun,
AutomationUpdateInput
} from '../shared/automations-types'
import type {
WorkspaceCleanupDismissArgs,
WorkspaceCleanupLocalProcessArgs,
WorkspaceCleanupLocalProcessResult,
WorkspaceCleanupScanArgs,
WorkspaceCleanupScanResult
} from '../shared/workspace-cleanup'
export type BrowserApi = {
registerGuest: (args: {
@@ -552,6 +559,14 @@ export type PreloadApi = {
callback: (data: WorktreeRemoteBranchConflictEvent) => void
) => () => void
}
workspaceCleanup: {
scan: (args?: WorkspaceCleanupScanArgs) => Promise<WorkspaceCleanupScanResult>
dismiss: (args: WorkspaceCleanupDismissArgs) => Promise<void>
clearDismissals: () => Promise<void>
hasKillableLocalProcesses: (
args: WorkspaceCleanupLocalProcessArgs
) => Promise<WorkspaceCleanupLocalProcessResult>
}
workspaceSpace: {
analyze: () => Promise<WorkspaceSpaceAnalyzeResult>
cancel: () => Promise<boolean>
+13
View File
@@ -494,6 +494,19 @@ const api = {
}
},
workspaceCleanup: {
scan: (args?: { worktreeId?: string; skipGitWorktreeIds?: string[] }): Promise<unknown> =>
ipcRenderer.invoke('workspaceCleanup:scan', args),
dismiss: (args: { dismissals: unknown[] }): Promise<void> =>
ipcRenderer.invoke('workspaceCleanup:dismiss', args),
clearDismissals: (): Promise<void> => ipcRenderer.invoke('workspaceCleanup:clearDismissals'),
hasKillableLocalProcesses: (args: {
worktreeId: string
connectionId?: string | null
worktreePath?: string
}): Promise<unknown> => ipcRenderer.invoke('workspaceCleanup:hasKillableLocalProcesses', args)
},
workspaceSpace: {
analyze: (): Promise<WorkspaceSpaceAnalyzeResult> =>
ipcRenderer.invoke('workspaceSpace:analyze'),
+5
View File
@@ -165,6 +165,9 @@ const WorkspaceSpacePage = lazy(() => import('./components/workspace-space/Works
const QuickOpen = lazy(() => import('./components/QuickOpen'))
const WorktreeJumpPalette = lazy(() => import('./components/WorktreeJumpPalette'))
const NewWorkspaceComposerModal = lazy(() => import('./components/NewWorkspaceComposerModal'))
const WorkspaceCleanupDialog = lazy(
() => import('./components/workspace-cleanup/WorkspaceCleanupDialog')
)
const FeatureWallModal = lazy(() => import('./components/feature-wall/FeatureWallModal'))
// Why: lazy-loaded so the WebP asset + overlay module aren't fetched unless
// the user opts into the experimental flag.
@@ -1045,6 +1048,7 @@ function App(): React.JSX.Element {
activeModal !== 'quick-open' &&
activeModal !== 'worktree-palette' &&
activeModal !== 'new-workspace-composer' &&
activeModal !== 'workspace-cleanup' &&
activeModal !== 'feature-wall'
) {
return
@@ -1408,6 +1412,7 @@ function App(): React.JSX.Element {
whether triggered from Cmd+J or any future entry point. */}
<Suspense fallback={null}>
{mountedLazyModalIds.has('new-workspace-composer') ? <NewWorkspaceComposerModal /> : null}
{mountedLazyModalIds.has('workspace-cleanup') ? <WorkspaceCleanupDialog /> : null}
</Suspense>
</TooltipProvider>
<Suspense fallback={null}>
@@ -7,6 +7,7 @@
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
AlertTriangle,
ArchiveX,
ChevronDown,
ChevronRight,
LoaderCircle,
@@ -32,12 +33,14 @@ import { cn } from '@/lib/utils'
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
import { activateTabAndFocusPane } from '@/lib/activate-tab-and-focus-pane'
import { useAppStore } from '../../store'
import { useWorktreeMap } from '../../store/selectors'
import { useAllWorktrees, useWorktreeMap } from '../../store/selectors'
import { runWorktreeDelete } from '../sidebar/delete-worktree-flow'
import { runSleepWorktree } from '../sidebar/sleep-worktree-flow'
import { useDaemonActions, DaemonActionDialog } from '../shared/useDaemonActions'
import type { AppMemory, UsageValues, Worktree } from '../../../../shared/types'
import { ORPHAN_WORKTREE_ID } from '../../../../shared/constants'
import { isFolderRepo } from '../../../../shared/repo-kind'
import { isWorkspaceOldForCleanup } from '../../../../shared/workspace-cleanup'
import { parsePaneKey } from '../../../../shared/stable-pane-id'
import {
mergeSnapshotAndSessions,
@@ -656,8 +659,10 @@ export function ResourceUsageStatusSegment({
const tabsByWorktree = useAppStore((s) => s.tabsByWorktree)
const runtimePaneTitlesByTabId = useAppStore((s) => s.runtimePaneTitlesByTabId)
const setActiveView = useAppStore((s) => s.setActiveView)
const openModal = useAppStore((s) => s.openModal)
const openSpacePage = useAppStore((s) => s.openSpacePage)
const repos = useAppStore((s) => s.repos)
const allWorktrees = useAllWorktrees()
const activeRuntimeEnvironmentId = useAppStore(
(s) => s.settings?.activeRuntimeEnvironmentId ?? null
)
@@ -778,6 +783,23 @@ export function ResourceUsageStatusSegment({
return map
}, [repos])
const repoById = useMemo(() => new Map(repos.map((repo) => [repo.id, repo])), [repos])
const oldWorkspaceCount = useMemo(() => {
const now = Date.now()
let count = 0
for (const worktree of allWorktrees) {
const repo = repoById.get(worktree.repoId)
if (!repo || isFolderRepo(repo) || worktree.isMainWorktree) {
continue
}
if (isWorkspaceOldForCleanup(worktree, now)) {
count += 1
}
}
return count
}, [allWorktrees, repoById])
// Why: skip the merge entirely when the popover is closed. The merged
// tree is only ever displayed inside <PopoverContent>; computing it on
// every store mutation (e.g. runtimePaneTitlesByTabId, which changes on
@@ -926,6 +948,11 @@ export function ResourceUsageStatusSegment({
void runSleepWorktree(id)
}, [])
const handleOpenWorkspaceCleanup = useCallback((): void => {
setOpen(false)
queueMicrotask(() => openModal('workspace-cleanup'))
}, [openModal])
const handleKillSession = useCallback(
(session: UnifiedSessionRow): void => {
// Why: orphan sessions have no tab in this Orca instance, so there's
@@ -1294,17 +1321,28 @@ export function ResourceUsageStatusSegment({
</div>
</div>
{orphanCount > 0 && (
<div className="border-t border-border/50 px-3 py-2 shrink-0">
<div className="border-t border-border/50 px-3 py-2 shrink-0">
<button
type="button"
onClick={handleOpenWorkspaceCleanup}
className="inline-flex w-full items-center justify-between gap-2 rounded-md border border-border/70 px-2.5 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent/60"
>
<span className="inline-flex min-w-0 items-center gap-1.5">
<ArchiveX className="size-3.5 shrink-0" />
<span className="truncate">Clean up old workspaces ({oldWorkspaceCount})</span>
</span>
<ChevronRight className="size-3.5 shrink-0 text-muted-foreground" aria-hidden />
</button>
{orphanCount > 0 ? (
<button
type="button"
onClick={() => void handleKillOrphans()}
className="inline-flex w-full items-center justify-center rounded-md border border-border/70 px-2.5 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent/60"
className="mt-2 inline-flex w-full items-center justify-center rounded-md border border-border/70 px-2.5 py-1.5 text-xs font-medium text-foreground transition-colors hover:bg-accent/60"
>
Kill {orphanCount} orphan terminal{orphanCount === 1 ? '' : 's'}
</button>
</div>
)}
) : null}
</div>
<WorkspaceSpaceCompactPanel onOpenFullPage={openSpaceResults} />
</PopoverContent>
@@ -0,0 +1,980 @@
/* eslint-disable max-lines */
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import {
AlertTriangle,
Check,
EyeOff,
Loader2,
Minus,
RefreshCcw,
Search,
Trash2,
X
} from 'lucide-react'
import { toast } from 'sonner'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { useAppStore } from '@/store'
import { cn } from '@/lib/utils'
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
import {
canQueueWorkspaceCleanupCandidate,
type WorkspaceCleanupBlocker,
type WorkspaceCleanupCandidate,
type WorkspaceCleanupScanError,
type WorkspaceCleanupTier
} from '../../../../shared/workspace-cleanup'
const TIER_LABELS: Record<WorkspaceCleanupTier, string> = {
ready: 'Suggested cleanup',
review: 'Needs a closer look',
protected: 'Not suggested for cleanup'
}
type CleanupView = WorkspaceCleanupTier | 'hidden'
const BLOCKER_LABELS: Record<WorkspaceCleanupBlocker, string> = {
'main-worktree': 'Main workspace',
'folder-repo': 'Folder project',
pinned: 'Pinned',
'active-workspace': 'Active workspace',
'running-terminal': 'Running terminal process',
'terminal-liveness-unknown': 'Terminal liveness unknown',
'dirty-editor-buffer': 'Unsaved editor buffer',
'volatile-local-context': 'Volatile local context',
'recent-visible-context': 'Recently visited tabs',
'live-agent': 'Active agent',
'ssh-disconnected': 'Remote unavailable',
'git-status-error': 'Git status unavailable',
'dirty-files': 'Changed files',
'unpushed-commits': 'Unpushed commits',
'unknown-base': 'Could not verify unpushed commits',
dismissed: 'Ignored'
}
function formatRelativeTime(timestamp: number): string {
if (!timestamp) {
return 'Never'
}
const deltaMs = Date.now() - timestamp
if (deltaMs < 60_000) {
return 'Just now'
}
const minutes = Math.floor(deltaMs / 60_000)
if (minutes < 60) {
return `${minutes}m ago`
}
const hours = Math.floor(minutes / 60)
if (hours < 48) {
return `${hours}h ago`
}
return `${Math.floor(hours / 24)}d ago`
}
function isDisconnectedRemoteScanError(message: string): boolean {
return (
message === 'SSH provider is unavailable.' ||
message === 'Remote workspaces are not connected. Reconnect and refresh to check them.'
)
}
function formatScanNoticeMessage(
errors: WorkspaceCleanupScanError[],
repoNameById: Map<string, string>
): string | null {
const visibleErrors = errors.filter(
(error) => !isDisconnectedRemoteScanError(error.message ?? '')
)
if (visibleErrors.length === 0) {
return null
}
if (visibleErrors.length === 1) {
const error = visibleErrors[0]
const repoName = formatScanErrorRepoName(error, repoNameById)
return `Could not check ${repoName}: ${formatScanErrorReason(error.message)}. Some old workspaces may be missing. Refresh to try again.`
}
const repoNames = visibleErrors
.slice(0, 3)
.map((error) => formatScanErrorRepoName(error, repoNameById))
.join(', ')
const moreCount = visibleErrors.length - 3
const suffix = moreCount > 0 ? `, +${moreCount} more` : ''
return `Could not check ${visibleErrors.length} repositories (${repoNames}${suffix}). Some old workspaces may be missing. Refresh to try again.`
}
function formatScanErrorRepoName(
error: Partial<WorkspaceCleanupScanError>,
repoNameById: Map<string, string>
): string {
const repoName = error.repoName?.trim()
if (repoName) {
return repoName
}
const fallback = error.repoId ? repoNameById.get(error.repoId)?.trim() : ''
return fallback || 'a repository'
}
function formatScanErrorReason(message: string | undefined): string {
if (!message) {
return 'Git could not list worktrees'
}
if (message === 'Could not scan workspace cleanup for this repository.') {
return 'Git could not list worktrees'
}
return message.replace(/\.$/, '')
}
function isOldWorkspaceCandidate(candidate: WorkspaceCleanupCandidate): boolean {
if (candidate.blockers.includes('main-worktree') || candidate.blockers.includes('folder-repo')) {
return false
}
return candidate.reasons.includes('archived') || candidate.reasons.includes('idle-clean')
}
function compareCleanupCandidates(
a: WorkspaceCleanupCandidate,
b: WorkspaceCleanupCandidate
): number {
const priorityA = getCleanupCandidatePriority(a)
const priorityB = getCleanupCandidatePriority(b)
if (priorityA !== priorityB) {
return priorityA - priorityB
}
return a.lastActivityAt - b.lastActivityAt
}
function getCleanupCandidatePriority(candidate: WorkspaceCleanupCandidate): number {
if (candidate.tier === 'ready') {
return 0
}
if (candidate.reasons.length > 0) {
return 1
}
if (isOldWorkspaceCandidate(candidate)) {
return 2
}
return 3
}
export default function WorkspaceCleanupDialog(): React.JSX.Element {
const activeModal = useAppStore((s) => s.activeModal)
const closeModal = useAppStore((s) => s.closeModal)
const scan = useAppStore((s) => s.workspaceCleanupScan)
const loading = useAppStore((s) => s.workspaceCleanupLoading)
const error = useAppStore((s) => s.workspaceCleanupError)
const repos = useAppStore((s) => s.repos)
const scanWorkspaceCleanup = useAppStore((s) => s.scanWorkspaceCleanup)
const markCandidateViewed = useAppStore((s) => s.markWorkspaceCleanupCandidateViewed)
const dismissCandidates = useAppStore((s) => s.dismissWorkspaceCleanupCandidates)
const resetDismissals = useAppStore((s) => s.resetWorkspaceCleanupDismissals)
const removeCandidates = useAppStore((s) => s.removeWorkspaceCleanupCandidates)
const open = activeModal === 'workspace-cleanup'
const [selectedIds, setSelectedIds] = useState<Set<string>>(() => new Set())
const [activeView, setActiveView] = useState<CleanupView>('ready')
const [confirming, setConfirming] = useState(false)
const [removing, setRemoving] = useState(false)
const [rowFailures, setRowFailures] = useState<Record<string, string>>({})
useEffect(() => {
if (open) {
setRowFailures({})
setActiveView('ready')
void scanWorkspaceCleanup().catch((err: unknown) => {
toast.error('Workspace cleanup scan failed', {
description: err instanceof Error ? err.message : String(err)
})
})
}
}, [open, scanWorkspaceCleanup])
const candidates = useMemo(() => scan?.candidates ?? [], [scan?.candidates])
useEffect(() => {
if (!open || !scan) {
return
}
setSelectedIds(
new Set(
candidates
.filter((candidate) => candidate.selectedByDefault)
.map((candidate) => candidate.worktreeId)
)
)
setConfirming(false)
}, [open, scan, scan?.scannedAt, candidates])
const visibleCandidates = useMemo(() => {
const rows = candidates.filter((candidate) => !candidate.blockers.includes('dismissed'))
return [...rows].sort(compareCleanupCandidates)
}, [candidates])
const hiddenCandidates = useMemo(
() =>
candidates
.filter((candidate) => candidate.blockers.includes('dismissed'))
.sort(compareCleanupCandidates),
[candidates]
)
const groups = useMemo(
() => ({
ready: visibleCandidates.filter((candidate) => candidate.tier === 'ready'),
review: visibleCandidates.filter((candidate) => candidate.tier === 'review'),
protected: visibleCandidates.filter((candidate) => candidate.tier === 'protected')
}),
[visibleCandidates]
)
const selectedCandidates = useMemo(() => {
const byId = new Map(candidates.map((candidate) => [candidate.worktreeId, candidate]))
return [...selectedIds]
.map((id) => byId.get(id))
.filter(
(candidate): candidate is WorkspaceCleanupCandidate =>
candidate != null && canQueueWorkspaceCleanupCandidate(candidate)
)
}, [candidates, selectedIds])
const hiddenByKeepCount = candidates.filter((candidate) =>
candidate.blockers.includes('dismissed')
).length
const repoNameById = useMemo(
() => new Map(repos.map((repo) => [repo.id, repo.displayName || repo.path])),
[repos]
)
const scanNoticeMessage = useMemo(
() => formatScanNoticeMessage(scan?.errors ?? [], repoNameById),
[repoNameById, scan?.errors]
)
const readyCount = groups.ready.length
const oldCandidateCount = useMemo(
() => candidates.filter(isOldWorkspaceCandidate).length,
[candidates]
)
const initialLoading = loading && !scan
const activeRows = activeView === 'hidden' ? hiddenCandidates : groups[activeView]
const activeQueueableRows = useMemo(
() => activeRows.filter(canQueueWorkspaceCleanupCandidate),
[activeRows]
)
const activeQueueableSelected = useMemo(
() => activeQueueableRows.filter((candidate) => selectedIds.has(candidate.worktreeId)).length,
[activeQueueableRows, selectedIds]
)
const allActiveQueueableSelected =
activeQueueableRows.length > 0 && activeQueueableSelected === activeQueueableRows.length
const someActiveQueueableSelected = activeQueueableSelected > 0
const activeSelectionState = allActiveQueueableSelected
? 'checked'
: someActiveQueueableSelected
? 'mixed'
: 'unchecked'
useEffect(() => {
if (!open || loading || !scan) {
return
}
if (activeRows.length > 0) {
return
}
if (readyCount > 0) {
setActiveView('ready')
} else if (groups.review.length > 0) {
setActiveView('review')
} else if (groups.protected.length > 0) {
setActiveView('protected')
} else if (hiddenCandidates.length > 0) {
setActiveView('hidden')
}
}, [
activeRows.length,
groups.protected.length,
groups.review.length,
hiddenCandidates.length,
loading,
open,
readyCount,
scan
])
const handleOpenChange = useCallback(
(nextOpen: boolean) => {
if (!nextOpen && !removing) {
closeModal()
}
},
[closeModal, removing]
)
const refresh = useCallback(() => {
setRowFailures({})
void scanWorkspaceCleanup().catch((err: unknown) => {
toast.error('Workspace cleanup scan failed', {
description: err instanceof Error ? err.message : String(err)
})
})
}, [scanWorkspaceCleanup])
const toggleActiveSelection = useCallback(() => {
if (activeQueueableRows.length === 0) {
return
}
setSelectedIds((current) => {
const next = new Set(current)
if (allActiveQueueableSelected) {
for (const candidate of activeQueueableRows) {
next.delete(candidate.worktreeId)
}
} else {
for (const candidate of activeQueueableRows) {
next.add(candidate.worktreeId)
}
}
return next
})
}, [activeQueueableRows, allActiveQueueableSelected])
const ignoreCandidate = useCallback(
(candidate: WorkspaceCleanupCandidate) => {
void dismissCandidates([candidate])
.then(() => {
setSelectedIds((current) => {
const next = new Set(current)
next.delete(candidate.worktreeId)
return next
})
})
.catch((err: unknown) => {
toast.error('Could not ignore cleanup suggestion', {
description: err instanceof Error ? err.message : String(err)
})
})
},
[dismissCandidates]
)
const confirmRemove = useCallback(async () => {
if (selectedCandidates.length === 0) {
return
}
setRemoving(true)
setRowFailures({})
try {
const result = await removeCandidates(
selectedCandidates.map((candidate) => candidate.worktreeId)
)
const nextFailures: Record<string, string> = {}
for (const failure of result.failures) {
nextFailures[failure.worktreeId] = failure.message
}
setRowFailures(nextFailures)
setSelectedIds((current) => {
const next = new Set(current)
for (const id of result.removedIds) {
next.delete(id)
}
return next
})
if (result.removedIds.length > 0) {
toast.success(
`Removed ${result.removedIds.length} workspace${result.removedIds.length === 1 ? '' : 's'}`
)
}
if (result.failures.length > 0) {
toast.error(
`${result.failures.length} workspace${result.failures.length === 1 ? '' : 's'} could not be removed`
)
} else {
setConfirming(false)
}
} finally {
setRemoving(false)
}
}, [removeCandidates, selectedCandidates])
const selectedCount = selectedCandidates.length
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent
showCloseButton={false}
className="flex h-[min(820px,90vh)] w-[calc(100vw-3rem)] max-w-[calc(100vw-3rem)] flex-col gap-0 overflow-hidden p-0 sm:max-w-[calc(100vw-3rem)] xl:w-[920px] xl:max-w-[920px]"
>
{!confirming ? (
<>
<DialogHeader className="border-b border-border px-5 py-4">
<div className="flex items-start justify-between gap-4">
<div className="min-w-0">
<DialogTitle className="text-base">Clean Up Old Workspaces</DialogTitle>
<DialogDescription className="mt-1 text-xs">
Review old workspaces before deleting their local files and Orca state.
</DialogDescription>
</div>
<div className="flex shrink-0 items-center gap-2">
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon-sm"
aria-label="Refresh"
onClick={refresh}
disabled={loading}
>
<RefreshCcw className={cn('size-3.5', loading && 'animate-spin')} />
</Button>
</TooltipTrigger>
<TooltipContent side="bottom" sideOffset={4}>
Refresh
</TooltipContent>
</Tooltip>
<Button
variant="ghost"
size="icon-sm"
aria-label="Close"
onClick={() => closeModal()}
disabled={removing}
>
<X className="size-4" />
</Button>
</div>
</div>
</DialogHeader>
{initialLoading ? (
<div className="flex items-center gap-2 border-b border-border bg-muted/25 px-5 py-3 text-xs text-muted-foreground">
<Loader2 className="size-3.5 animate-spin" />
Checking old workspaces
</div>
) : oldCandidateCount > 0 || hiddenByKeepCount > 0 ? (
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-border bg-muted/25 px-4 py-2.5">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<div className="min-w-0 text-sm font-medium text-foreground">
{selectedCount} selected
</div>
{readyCount > 0 ? (
<StatusPill tone="ready">{readyCount} safe to remove</StatusPill>
) : null}
{groups.review.length > 0 ? (
<StatusPill tone="review">{groups.review.length} need review</StatusPill>
) : null}
</div>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<Button
variant="destructive"
size="sm"
onClick={() => setConfirming(true)}
disabled={selectedCount === 0}
>
<Trash2 className="size-3.5" />
Remove selected
</Button>
</div>
</div>
) : null}
{error ? (
<div className="border-b border-destructive/30 bg-destructive/10 px-5 py-2 text-xs text-destructive">
{error}
</div>
) : scanNoticeMessage ? (
<div className="flex items-center gap-2 border-b border-border bg-muted/25 px-5 py-2 text-xs text-muted-foreground">
<AlertTriangle className="size-3.5 shrink-0" />
<span>{scanNoticeMessage}</span>
</div>
) : null}
<div className="grid min-h-0 flex-1 grid-cols-1 overflow-hidden md:grid-cols-[185px_minmax(0,1fr)]">
<CleanupViewNav
activeView={activeView}
counts={{
ready: groups.ready.length,
review: groups.review.length,
protected: groups.protected.length,
hidden: hiddenByKeepCount
}}
onViewChange={setActiveView}
/>
<div className="flex min-w-0 flex-col border-t border-border md:border-l md:border-t-0">
<div className="flex min-h-10 items-center justify-between gap-3 border-b border-border px-3 py-2">
<div className="flex min-w-0 items-center gap-2">
{activeView !== 'hidden' && activeQueueableRows.length > 0 ? (
<button
type="button"
role="checkbox"
aria-checked={
activeSelectionState === 'mixed' ? 'mixed' : allActiveQueueableSelected
}
aria-label={
allActiveQueueableSelected
? `Unselect all in ${TIER_LABELS[activeView]}`
: `Select all in ${TIER_LABELS[activeView]}`
}
onClick={toggleActiveSelection}
className="flex size-4 shrink-0 items-center justify-center rounded border border-border bg-background text-primary hover:bg-accent"
>
{activeSelectionState === 'checked' ? (
<Check className="size-3" strokeWidth={3} />
) : activeSelectionState === 'mixed' ? (
<Minus className="size-3" strokeWidth={3} />
) : null}
</button>
) : null}
<div className="min-w-0 truncate text-[11px] font-semibold uppercase tracking-[0.05em] text-muted-foreground">
{activeView === 'hidden'
? 'Ignored cleanup suggestions'
: TIER_LABELS[activeView]}
</div>
</div>
{activeView === 'hidden' && hiddenByKeepCount > 0 ? (
<Button
variant="link"
size="xs"
className="h-auto shrink-0 px-0 text-xs"
onClick={() => void resetDismissals()}
>
Restore ignored suggestions
</Button>
) : (
<div className="shrink-0 text-xs text-muted-foreground">
Sorted by oldest activity
</div>
)}
</div>
<ScrollArea className="min-h-0 flex-1">
<div>
{initialLoading ? <SkeletonRows /> : null}
{!loading && scan && candidates.length === 0 && !scanNoticeMessage ? (
<EmptyState title="No old workspaces to clean up." />
) : null}
{!loading && scan && candidates.length === 0 && scanNoticeMessage ? (
<EmptyState title="No old workspaces found in checked repositories." />
) : null}
{!loading && scan && candidates.length > 0 && visibleCandidates.length === 0 ? (
<EmptyState
title="All cleanup suggestions are ignored."
actionLabel="Review ignored workspaces"
onAction={() => setActiveView('hidden')}
/>
) : null}
{!loading && scan && activeRows.length === 0 && visibleCandidates.length > 0 ? (
<EmptyState title="No workspaces in this cleanup set." />
) : null}
{activeRows.map((candidate, index) => (
<CandidateRow
key={candidate.worktreeId}
candidate={candidate}
last={index === activeRows.length - 1}
selected={selectedIds.has(candidate.worktreeId)}
failure={rowFailures[candidate.worktreeId]}
onToggleSelected={(id) =>
setSelectedIds((current) => toggleSetMember(current, id))
}
onView={closeAndView}
onIgnore={ignoreCandidate}
onRemove={(candidate) => {
setSelectedIds(new Set([candidate.worktreeId]))
setConfirming(true)
}}
/>
))}
</div>
</ScrollArea>
</div>
</div>
</>
) : (
<ConfirmRemove
count={selectedCount}
removing={removing}
onCancel={() => setConfirming(false)}
onConfirm={() => void confirmRemove()}
/>
)}
</DialogContent>
</Dialog>
)
function closeAndView(candidate: WorkspaceCleanupCandidate): void {
markCandidateViewed(candidate)
closeModal()
activateAndRevealWorktree(candidate.worktreeId)
}
}
function StatusPill({
children,
tone = 'neutral'
}: {
children: React.ReactNode
tone?: 'neutral' | 'ready' | 'review' | 'destructive'
}): React.JSX.Element {
return (
<span
className={cn(
'inline-flex h-5 items-center rounded-full border px-2 text-[11px] font-medium',
tone === 'neutral' && 'border-border bg-background text-muted-foreground',
tone === 'ready' && 'border-border text-[var(--git-decoration-added)]',
tone === 'review' && 'border-border text-[var(--git-decoration-modified)]',
tone === 'destructive' && 'border-destructive/30 text-destructive'
)}
>
{children}
</span>
)
}
function CleanupViewNav({
activeView,
counts,
onViewChange
}: {
activeView: CleanupView
counts: Record<CleanupView, number>
onViewChange: (view: CleanupView) => void
}): React.JSX.Element {
const items: { view: CleanupView; label: string }[] = [
{ view: 'ready', label: 'Suggested' },
{ view: 'review', label: 'Needs review' },
{ view: 'protected', label: 'Not suggested' },
{ view: 'hidden', label: 'Ignored' }
]
return (
<aside className="border-t border-border bg-background md:border-t-0">
<div className="space-y-1 p-2">
{items.map((item) => (
<button
key={item.view}
type="button"
className={cn(
'flex h-8 w-full items-center justify-between gap-2 rounded-md px-2 text-left text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground',
activeView === item.view && 'bg-accent text-accent-foreground'
)}
onClick={() => onViewChange(item.view)}
>
<span className="truncate">{item.label}</span>
<span className="tabular-nums text-muted-foreground">{counts[item.view]}</span>
</button>
))}
</div>
</aside>
)
}
function CandidateRow({
candidate,
last,
selected,
failure,
onToggleSelected,
onView,
onIgnore,
onRemove
}: {
candidate: WorkspaceCleanupCandidate
last: boolean
selected: boolean
failure?: string
onToggleSelected: (worktreeId: string) => void
onView: (candidate: WorkspaceCleanupCandidate) => void
onIgnore: (candidate: WorkspaceCleanupCandidate) => void
onRemove: (candidate: WorkspaceCleanupCandidate) => void
}): React.JSX.Element {
const selectable = canQueueWorkspaceCleanupCandidate(candidate)
const ignored = candidate.blockers.includes('dismissed')
const blockers = candidate.blockers.map((blocker) => BLOCKER_LABELS[blocker])
const contextDetails = formatContextDetails(candidate)
const branchSafetyDetails = formatBranchSafetyDetails(candidate)
const status = getCandidateStatus(candidate)
return (
<div
className={cn(
'group w-full border-b border-border/60 px-3 py-3 text-left text-foreground transition-colors hover:bg-accent/40',
last && 'border-b-0'
)}
>
<div className="grid grid-cols-[auto_minmax(0,1fr)] items-start gap-x-2.5 gap-y-1 md:grid-cols-[auto_minmax(0,1fr)_auto]">
{selectable ? (
<button
type="button"
role="checkbox"
aria-checked={selected}
aria-label={`Select ${candidate.displayName}`}
onClick={() => onToggleSelected(candidate.worktreeId)}
className="mt-0.5 flex size-4 shrink-0 items-center justify-center rounded border border-border bg-background text-primary hover:bg-accent"
>
{selected ? <Check className="size-3" strokeWidth={3} /> : null}
</button>
) : (
<div className="mt-0.5 size-4 shrink-0" aria-hidden="true" />
)}
<div className="min-w-0">
<div className="flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-0.5">
<span className="min-w-0 truncate text-sm font-medium">{candidate.displayName}</span>
<StatusPill tone={status.tone}>{status.label}</StatusPill>
<span className="text-xs text-muted-foreground">
Last active {formatRelativeTime(candidate.lastActivityAt)}
</span>
{blockers.length > 0 ? (
<span className="min-w-0 truncate text-xs text-muted-foreground">
{blockers.slice(0, 2).join(', ')}
</span>
) : null}
</div>
<div className="mt-1 min-w-0 truncate font-mono text-[11px] text-muted-foreground">
{candidate.path}
</div>
<div className="mt-1 flex min-w-0 flex-wrap gap-x-3 gap-y-1 text-xs text-muted-foreground">
<span className="min-w-0 truncate">Repo {candidate.repoName}</span>
<span className="min-w-0 truncate font-mono">Branch {candidate.branch}</span>
<span>{formatGitStatus(candidate)}</span>
{branchSafetyDetails.slice(0, 1).map((detail) => (
<span key={detail}>{detail}</span>
))}
{contextDetails ? <span className="min-w-0 truncate">{contextDetails}</span> : null}
</div>
{failure ? (
<div className="mt-2 flex items-center gap-1.5 text-xs text-destructive">
<AlertTriangle className="size-3.5" />
{failure}
</div>
) : null}
</div>
<div className="col-start-2 flex flex-wrap items-center gap-0.5 md:col-start-auto md:justify-end">
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
aria-label={`View ${candidate.displayName}`}
onClick={() => onView(candidate)}
>
<Search className="size-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
View
</TooltipContent>
</Tooltip>
{!ignored ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
aria-label={`Ignore ${candidate.displayName}`}
onClick={() => onIgnore(candidate)}
>
<EyeOff className="size-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
Ignore
</TooltipContent>
</Tooltip>
) : null}
{selectable ? (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon-xs"
aria-label={`Remove ${candidate.displayName}`}
className="text-destructive hover:text-destructive"
onClick={() => onRemove(candidate)}
>
<Trash2 className="size-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent side="top" sideOffset={4}>
Remove
</TooltipContent>
</Tooltip>
) : null}
</div>
</div>
</div>
)
}
function getCandidateStatus(candidate: WorkspaceCleanupCandidate): {
label: string
tone: 'neutral' | 'ready' | 'review' | 'destructive'
} {
if (candidate.blockers.includes('dismissed')) {
return { label: 'Ignored', tone: 'neutral' }
}
if (candidate.tier === 'ready') {
return { label: candidate.reasons.includes('archived') ? 'Archived' : 'Clean', tone: 'ready' }
}
if (candidate.blockers.length > 0) {
return { label: BLOCKER_LABELS[candidate.blockers[0]], tone: 'neutral' }
}
if (candidate.git.upstreamAhead && candidate.git.upstreamAhead > 0) {
return { label: 'Unpushed commits', tone: 'review' }
}
if (candidate.git.clean === false) {
return { label: 'Dirty', tone: 'review' }
}
if (candidate.tier === 'review') {
return { label: 'Review', tone: 'review' }
}
return { label: 'Not suggested', tone: 'neutral' }
}
function formatGitStatus(candidate: WorkspaceCleanupCandidate): string {
if (candidate.git.clean === true) {
return 'Clean git'
}
if (candidate.git.clean === false) {
return 'Dirty git'
}
return 'Git unknown'
}
function formatBranchSafetyDetails(candidate: WorkspaceCleanupCandidate): string[] {
const details: string[] = []
if (candidate.git.upstreamAhead !== null) {
details.push(
candidate.git.upstreamAhead === 0
? 'No unpushed commits'
: `${candidate.git.upstreamAhead} unpushed commit${
candidate.git.upstreamAhead === 1 ? '' : 's'
}`
)
}
return details
}
function formatContextDetails(candidate: WorkspaceCleanupCandidate): string | null {
const parts: string[] = []
if (candidate.localContext.terminalTabCount > 0) {
parts.push(
`${candidate.localContext.terminalTabCount} terminal tab${
candidate.localContext.terminalTabCount === 1 ? '' : 's'
}`
)
}
if (candidate.localContext.cleanEditorTabCount > 0) {
parts.push(
`${candidate.localContext.cleanEditorTabCount} editor tab${
candidate.localContext.cleanEditorTabCount === 1 ? '' : 's'
}`
)
}
if (candidate.localContext.browserTabCount > 0) {
parts.push(
`${candidate.localContext.browserTabCount} browser tab${
candidate.localContext.browserTabCount === 1 ? '' : 's'
}`
)
}
if (candidate.localContext.diffCommentCount > 0) {
parts.push(
`${candidate.localContext.diffCommentCount} diff note${
candidate.localContext.diffCommentCount === 1 ? '' : 's'
}`
)
}
if (candidate.localContext.retainedDoneAgentCount > 0) {
parts.push(
`${candidate.localContext.retainedDoneAgentCount} completed agent${
candidate.localContext.retainedDoneAgentCount === 1 ? '' : 's'
}`
)
}
return parts.length > 0 ? parts.join(', ') : null
}
function ConfirmRemove({
count,
removing,
onCancel,
onConfirm
}: {
count: number
removing: boolean
onCancel: () => void
onConfirm: () => void
}): React.JSX.Element {
return (
<>
<DialogHeader className="border-b border-border px-5 py-4">
<DialogTitle className="text-base">
Remove {count} workspace{count === 1 ? '' : 's'}?
</DialogTitle>
<DialogDescription className="mt-2 text-xs leading-5">
Removing a workspace deletes its working tree folder, local Orca metadata, terminal
history, browser workspace state, and the local branch when the existing git deletion path
decides that branch is no longer used.
</DialogDescription>
</DialogHeader>
<div className="flex-1 px-5 py-4 text-sm">
Cleanup rechecks each selected workspace before deletion. Suggested rows use the normal
git-safe removal path; not suggested rows may need forced worktree removal and are reported
if they cannot be removed.
</div>
<DialogFooter className="border-t border-border px-5 py-3">
<Button variant="outline" onClick={onCancel} disabled={removing}>
Cancel
</Button>
<Button variant="destructive" onClick={onConfirm} disabled={removing || count === 0}>
{removing ? <Loader2 className="size-4 animate-spin" /> : <Trash2 className="size-4" />}
Remove {count}
</Button>
</DialogFooter>
</>
)
}
function SkeletonRows(): React.JSX.Element {
return (
<div className="space-y-2">
{[0, 1, 2].map((index) => (
<div
key={index}
className="h-24 animate-pulse rounded-lg border border-border bg-muted/35"
/>
))}
</div>
)
}
function EmptyState({
title,
actionLabel,
onAction
}: {
title: string
actionLabel?: string
onAction?: () => void
}): React.JSX.Element {
return (
<div className="flex min-h-48 flex-col items-center justify-center gap-3 rounded-lg border border-border bg-muted/20 text-sm text-muted-foreground">
<span>{title}</span>
{actionLabel && onAction ? (
<Button variant="outline" size="sm" onClick={onAction}>
{actionLabel}
</Button>
) : null}
</div>
)
}
function toggleSetMember(current: Set<string>, value: string): Set<string> {
const next = new Set(current)
if (next.has(value)) {
next.delete(value)
} else {
next.add(value)
}
return next
}
+3 -1
View File
@@ -24,6 +24,7 @@ import { createDiffCommentsSlice } from './slices/diffComments'
import { createDetectedAgentsSlice } from './slices/detected-agents'
import { createWorktreeNavHistorySlice } from './slices/worktree-nav-history'
import { createDictationSlice } from './slices/dictation'
import { createWorkspaceCleanupSlice } from './slices/workspace-cleanup'
import { e2eConfig } from '@/lib/e2e-config'
import { registerHttpLinkStoreAccessor } from '@/lib/http-link-routing'
@@ -51,7 +52,8 @@ export const useAppStore = create<AppState>()((...a) => ({
...createDiffCommentsSlice(...a),
...createDetectedAgentsSlice(...a),
...createWorktreeNavHistorySlice(...a),
...createDictationSlice(...a)
...createDictationSlice(...a),
...createWorkspaceCleanupSlice(...a)
}))
registerHttpLinkStoreAccessor(() => useAppStore.getState())
@@ -111,6 +111,7 @@ import { createDiffCommentsSlice } from './diffComments'
import { createDetectedAgentsSlice } from './detected-agents'
import { createWorktreeNavHistorySlice } from './worktree-nav-history'
import { createDictationSlice } from './dictation'
import { createWorkspaceCleanupSlice } from './workspace-cleanup'
function createTestStore() {
return create<AppState>()((...a) => ({
@@ -137,7 +138,8 @@ function createTestStore() {
...createDiffCommentsSlice(...a),
...createDetectedAgentsSlice(...a),
...createWorktreeNavHistorySlice(...a),
...createDictationSlice(...a)
...createDictationSlice(...a),
...createWorkspaceCleanupSlice(...a)
}))
}
@@ -114,6 +114,7 @@ import { createDiffCommentsSlice } from './diffComments'
import { createDetectedAgentsSlice } from './detected-agents'
import { createWorktreeNavHistorySlice } from './worktree-nav-history'
import { createDictationSlice } from './dictation'
import { createWorkspaceCleanupSlice } from './workspace-cleanup'
function createTestStore() {
return create<AppState>()((...a) => ({
@@ -140,7 +141,8 @@ function createTestStore() {
...createDiffCommentsSlice(...a),
...createDetectedAgentsSlice(...a),
...createWorktreeNavHistorySlice(...a),
...createDictationSlice(...a)
...createDictationSlice(...a),
...createWorkspaceCleanupSlice(...a)
}))
}
@@ -32,6 +32,7 @@ import { createDiffCommentsSlice } from './diffComments'
import { createDetectedAgentsSlice } from './detected-agents'
import { createWorktreeNavHistorySlice } from './worktree-nav-history'
import { createDictationSlice } from './dictation'
import { createWorkspaceCleanupSlice } from './workspace-cleanup'
export const TEST_REPO = {
id: 'repo1',
@@ -66,7 +67,8 @@ export function createTestStore() {
...createDiffCommentsSlice(...a),
...createDetectedAgentsSlice(...a),
...createWorktreeNavHistorySlice(...a),
...createDictationSlice(...a)
...createDictationSlice(...a),
...createWorkspaceCleanupSlice(...a)
}))
}
+3 -1
View File
@@ -108,6 +108,7 @@ import { createDiffCommentsSlice } from './diffComments'
import { createDetectedAgentsSlice } from './detected-agents'
import { createWorktreeNavHistorySlice } from './worktree-nav-history'
import { createDictationSlice } from './dictation'
import { createWorkspaceCleanupSlice } from './workspace-cleanup'
const WT = 'repo1::/tmp/feature'
@@ -136,7 +137,8 @@ function createTestStore() {
...createDiffCommentsSlice(...a),
...createDetectedAgentsSlice(...a),
...createWorktreeNavHistorySlice(...a),
...createDictationSlice(...a)
...createDictationSlice(...a),
...createWorkspaceCleanupSlice(...a)
}))
}
+42
View File
@@ -16,6 +16,10 @@ import type {
WorktreeCardProperty
} from '../../../../shared/types'
import { PET_SIZE_DEFAULT, PET_SIZE_MAX, PET_SIZE_MIN } from '../../../../shared/types'
import {
WORKSPACE_CLEANUP_CLASSIFIER_VERSION,
type WorkspaceCleanupDismissal
} from '../../../../shared/workspace-cleanup'
import { PER_REPO_FETCH_LIMIT } from '../../../../shared/work-items'
import {
DEFAULT_STATUS_BAR_ITEMS,
@@ -152,6 +156,40 @@ function sanitizeAcknowledgedAgentsByPaneKey(value: unknown): Record<string, num
return out
}
function sanitizeWorkspaceCleanupDismissals(
value: unknown
): Record<string, WorkspaceCleanupDismissal> {
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
return {}
}
const out: Record<string, WorkspaceCleanupDismissal> = {}
for (const [key, raw] of Object.entries(value as Record<string, unknown>)) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
continue
}
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
continue
}
const input = raw as Record<string, unknown>
if (
typeof input.worktreeId !== 'string' ||
typeof input.dismissedAt !== 'number' ||
!Number.isFinite(input.dismissedAt) ||
typeof input.fingerprint !== 'string' ||
input.classifierVersion !== WORKSPACE_CLEANUP_CLASSIFIER_VERSION
) {
continue
}
out[key] = {
worktreeId: input.worktreeId,
dismissedAt: input.dismissedAt,
fingerprint: input.fingerprint,
classifierVersion: input.classifierVersion
}
}
return out
}
function sanitizeTaskResumeState(value: unknown): TaskResumeState | undefined {
if (!value || typeof value !== 'object') {
return undefined
@@ -284,6 +322,7 @@ export type UISlice = {
| 'add-repo'
| 'quick-open'
| 'worktree-palette'
| 'workspace-cleanup'
| 'feature-wall'
| 'new-workspace-composer'
| 'confirm-orca-yaml-hooks'
@@ -896,6 +935,9 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
acknowledgedAgentsByPaneKey: sanitizeAcknowledgedAgentsByPaneKey(
ui.acknowledgedAgentsByPaneKey
),
workspaceCleanupDismissals: sanitizeWorkspaceCleanupDismissals(
ui.workspaceCleanup?.dismissals
),
persistedUIReady: true
}
}),
@@ -0,0 +1,363 @@
/* eslint-disable max-lines -- Why: cleanup store tests share a Zustand store
harness and mocked window API; splitting would obscure the state transitions. */
import { create } from 'zustand'
import { describe, expect, it, vi } from 'vitest'
import type { AppState } from '../types'
import type {
WorkspaceCleanupCandidate,
WorkspaceCleanupScanResult
} from '../../../../shared/workspace-cleanup'
import { createWorkspaceCleanupSlice, enrichWorkspaceCleanupCandidates } from './workspace-cleanup'
const WORKTREE_ID = 'repo1::/tmp/old-workspace'
const NOW = 1_700_000_000_000
function makeCandidate(
overrides: Partial<WorkspaceCleanupCandidate> = {}
): WorkspaceCleanupCandidate {
return {
worktreeId: WORKTREE_ID,
repoId: 'repo1',
repoName: 'Repo 1',
connectionId: null,
displayName: 'old-workspace',
branch: 'old-workspace',
path: '/tmp/old-workspace',
tier: 'ready',
selectedByDefault: true,
reasons: ['idle-clean'],
blockers: [],
lastActivityAt: NOW - 30 * 24 * 60 * 60 * 1000,
localContext: {
terminalTabCount: 0,
cleanEditorTabCount: 0,
browserTabCount: 0,
diffCommentCount: 0,
newestDiffCommentAt: null,
retainedDoneAgentCount: 0
},
git: {
clean: true,
upstreamAhead: 0,
upstreamBehind: 0,
checkedAt: NOW
},
fingerprint: 'fingerprint-1',
...overrides
}
}
function makeState(overrides: Partial<AppState> = {}): AppState {
return {
tabsByWorktree: {},
ptyIdsByTabId: {},
openFiles: [],
editorDrafts: {},
browserTabsByWorktree: {},
retainedAgentsByPaneKey: {},
activeWorktreeId: null,
agentStatusByPaneKey: {},
runtimePaneTitlesByTabId: {},
lastVisitedAtByWorktreeId: {},
workspaceCleanupDismissals: {},
workspaceCleanupViewedCandidates: {},
...overrides
} as AppState
}
function createCleanupTestStore(removeWorktree = vi.fn()) {
return create<AppState>()(
(...a) =>
({
tabsByWorktree: {},
ptyIdsByTabId: {},
openFiles: [],
editorDrafts: {},
browserTabsByWorktree: {},
retainedAgentsByPaneKey: {},
activeWorktreeId: null,
agentStatusByPaneKey: {},
runtimePaneTitlesByTabId: {},
lastVisitedAtByWorktreeId: {},
removeWorktree,
...createWorkspaceCleanupSlice(...a)
}) as unknown as AppState
)
}
describe('workspace cleanup viewed rows', () => {
it('demotes an active suggested workspace when it was not viewed from cleanup', async () => {
const [candidate] = await enrichWorkspaceCleanupCandidates(
[makeCandidate()],
makeState({ activeWorktreeId: WORKTREE_ID }),
{ applyDismissals: false }
)
expect(candidate.tier).toBe('protected')
expect(candidate.blockers).toContain('active-workspace')
})
it('keeps a viewed active workspace visible but not removable', async () => {
const [candidate] = await enrichWorkspaceCleanupCandidates(
[makeCandidate()],
makeState({
activeWorktreeId: WORKTREE_ID,
workspaceCleanupViewedCandidates: {
[WORKTREE_ID]: {
viewedAt: Date.now(),
fingerprint: 'fingerprint-1',
wasSuggested: true
}
}
}),
{ applyDismissals: false }
)
expect(candidate.tier).toBe('protected')
expect(candidate.selectedByDefault).toBe(false)
expect(candidate.blockers).toContain('active-workspace')
})
it('does not preserve the cleanup view exception after the row changes', async () => {
const [candidate] = await enrichWorkspaceCleanupCandidates(
[makeCandidate({ fingerprint: 'fingerprint-2' })],
makeState({
activeWorktreeId: WORKTREE_ID,
workspaceCleanupViewedCandidates: {
[WORKTREE_ID]: {
viewedAt: Date.now(),
fingerprint: 'fingerprint-1',
wasSuggested: true
}
}
}),
{ applyDismissals: false }
)
expect(candidate.tier).toBe('protected')
expect(candidate.blockers).toContain('active-workspace')
})
it('protects recently visible old workspaces with open context', async () => {
const [candidate] = await enrichWorkspaceCleanupCandidates(
[makeCandidate()],
makeState({
openFiles: [
{
id: 'file-1',
worktreeId: WORKTREE_ID,
filePath: '/tmp/old-workspace/src/app.ts',
relativePath: 'src/app.ts',
language: 'typescript',
isDirty: false
}
] as AppState['openFiles'],
lastVisitedAtByWorktreeId: {
[WORKTREE_ID]: Date.now()
}
}),
{ applyDismissals: false }
)
expect(candidate.tier).toBe('protected')
expect(candidate.selectedByDefault).toBe(false)
expect(candidate.blockers).toContain('recent-visible-context')
})
it('uses current renderer state after async delete preflight scan resolves', async () => {
let resolveScan: (value: WorkspaceCleanupScanResult) => void
const removeWorktree = vi.fn().mockResolvedValue({ ok: true })
const store = createCleanupTestStore(removeWorktree)
;(globalThis as { window: unknown }).window = {
api: {
workspaceCleanup: {
scan: vi.fn(
(): Promise<WorkspaceCleanupScanResult> =>
new Promise<WorkspaceCleanupScanResult>((resolve) => {
resolveScan = resolve
})
),
dismiss: vi.fn().mockResolvedValue(undefined),
clearDismissals: vi.fn().mockResolvedValue(undefined),
hasKillableLocalProcesses: vi.fn().mockResolvedValue({
hasKillableProcesses: false
})
}
}
}
const removal = store.getState().removeWorkspaceCleanupCandidates([WORKTREE_ID])
store.setState({ activeWorktreeId: WORKTREE_ID })
resolveScan!({ scannedAt: NOW, candidates: [makeCandidate()], errors: [] })
await expect(removal).resolves.toEqual({
removedIds: [WORKTREE_ID],
failures: []
})
expect(removeWorktree).toHaveBeenCalledWith(WORKTREE_ID, false)
})
it('defers git checks for locally active workspaces on initial scans', async () => {
const scan = vi.fn().mockResolvedValue({
scannedAt: NOW,
candidates: [],
errors: []
} satisfies WorkspaceCleanupScanResult)
;(globalThis as { window: unknown }).window = {
api: {
workspaceCleanup: {
scan,
dismiss: vi.fn().mockResolvedValue(undefined),
clearDismissals: vi.fn().mockResolvedValue(undefined),
hasKillableLocalProcesses: vi.fn().mockResolvedValue({
hasKillableProcesses: false
})
}
}
}
const store = createCleanupTestStore()
store.setState({
activeWorktreeId: WORKTREE_ID,
tabsByWorktree: {
'repo1::/tmp/terminal-workspace': [
{ id: 'tab-1', title: 'zsh' }
] as AppState['tabsByWorktree'][string]
},
ptyIdsByTabId: { 'tab-1': ['pty-1'] }
} as Partial<AppState>)
await store.getState().scanWorkspaceCleanup()
expect(scan).toHaveBeenCalledWith({
skipGitWorktreeIds: expect.arrayContaining([WORKTREE_ID, 'repo1::/tmp/terminal-workspace'])
})
})
it('does not defer git checks for focused remove preflights', async () => {
const scan = vi.fn().mockResolvedValue({
scannedAt: NOW,
candidates: [makeCandidate()],
errors: []
} satisfies WorkspaceCleanupScanResult)
;(globalThis as { window: unknown }).window = {
api: {
workspaceCleanup: {
scan,
dismiss: vi.fn().mockResolvedValue(undefined),
clearDismissals: vi.fn().mockResolvedValue(undefined),
hasKillableLocalProcesses: vi.fn().mockResolvedValue({
hasKillableProcesses: false
})
}
}
}
const removeWorktree = vi.fn().mockResolvedValue({ ok: true })
const store = createCleanupTestStore(removeWorktree)
store.setState({ activeWorktreeId: 'repo1::/tmp/other-workspace' } as Partial<AppState>)
await store.getState().removeWorkspaceCleanupCandidates([WORKTREE_ID])
expect(scan).toHaveBeenCalledWith({ worktreeId: WORKTREE_ID })
})
it('lets explicitly selected not-suggested workspaces reach the removal path', async () => {
const scan = vi.fn().mockResolvedValue({
scannedAt: NOW,
candidates: [makeCandidate()],
errors: []
} satisfies WorkspaceCleanupScanResult)
const removeWorktree = vi.fn().mockResolvedValue({ ok: true })
;(globalThis as { window: unknown }).window = {
api: {
workspaceCleanup: {
scan,
dismiss: vi.fn().mockResolvedValue(undefined),
clearDismissals: vi.fn().mockResolvedValue(undefined),
hasKillableLocalProcesses: vi.fn().mockResolvedValue({
hasKillableProcesses: true
})
}
}
}
const store = createCleanupTestStore(removeWorktree)
store.setState({
tabsByWorktree: {
[WORKTREE_ID]: [{ id: 'tab-1', title: 'zsh' }] as AppState['tabsByWorktree'][string]
},
ptyIdsByTabId: { 'tab-1': ['pty-1'] }
} as Partial<AppState>)
await expect(store.getState().removeWorkspaceCleanupCandidates([WORKTREE_ID])).resolves.toEqual(
{
removedIds: [WORKTREE_ID],
failures: []
}
)
expect(removeWorktree).toHaveBeenCalledWith(WORKTREE_ID, false)
})
it('protects old workspaces when an agent process is still foregrounded', async () => {
;(globalThis as { window: unknown }).window = {
api: {
pty: {
hasChildProcesses: vi.fn().mockResolvedValue(true),
getForegroundProcess: vi.fn().mockResolvedValue('codex')
}
}
}
const [candidate] = await enrichWorkspaceCleanupCandidates(
[makeCandidate()],
makeState({
tabsByWorktree: {
[WORKTREE_ID]: [{ id: 'tab-1', title: 'zsh' }] as AppState['tabsByWorktree'][string]
},
ptyIdsByTabId: { 'tab-1': ['pty-1'] }
}),
{ applyDismissals: false }
)
expect(candidate.tier).toBe('protected')
expect(candidate.selectedByDefault).toBe(false)
expect(candidate.blockers).toContain('running-terminal')
})
it('does not let an idle title in another tab mask a running agent process', async () => {
;(globalThis as { window: unknown }).window = {
api: {
pty: {
hasChildProcesses: vi.fn(async (ptyId: string) => ptyId === 'pty-running'),
getForegroundProcess: vi.fn(async (ptyId: string) =>
ptyId === 'pty-running' ? 'codex' : 'zsh'
)
}
}
}
const [candidate] = await enrichWorkspaceCleanupCandidates(
[makeCandidate()],
makeState({
tabsByWorktree: {
[WORKTREE_ID]: [
{ id: 'tab-running', title: 'zsh' },
{ id: 'tab-idle', title: 'Codex done' }
] as AppState['tabsByWorktree'][string]
},
ptyIdsByTabId: {
'tab-running': ['pty-running'],
'tab-idle': ['pty-idle']
}
}),
{ applyDismissals: false }
)
expect(candidate.tier).toBe('protected')
expect(candidate.selectedByDefault).toBe(false)
expect(candidate.blockers).toContain('running-terminal')
})
})
@@ -0,0 +1,527 @@
/* eslint-disable max-lines */
import type { StateCreator } from 'zustand'
import type { AppState } from '../types'
import {
AGENT_STATUS_STALE_AFTER_MS,
type AgentStatusEntry
} from '../../../../shared/agent-status-types'
import {
WORKSPACE_CLEANUP_CLASSIFIER_VERSION,
applyWorkspaceCleanupPolicy,
canQueueWorkspaceCleanupCandidate,
canSelectWorkspaceCleanupCandidate,
shouldForceWorkspaceCleanupRemoval,
shouldHideWorkspaceCleanupCandidate,
type WorkspaceCleanupBlocker,
type WorkspaceCleanupCandidate,
type WorkspaceCleanupDismissal,
type WorkspaceCleanupScanArgs,
type WorkspaceCleanupScanResult
} from '../../../../shared/workspace-cleanup'
import { detectAgentStatusFromTitle, isExplicitAgentStatusFresh } from '@/lib/agent-status'
export type WorkspaceCleanupFailure = {
worktreeId: string
displayName: string
message: string
}
export type WorkspaceCleanupRemoveResult = {
removedIds: string[]
failures: WorkspaceCleanupFailure[]
}
type WorkspaceCleanupViewedCandidate = {
viewedAt: number
fingerprint: string
wasSuggested: boolean
}
export type WorkspaceCleanupSlice = {
workspaceCleanupScan: WorkspaceCleanupScanResult | null
workspaceCleanupLoading: boolean
workspaceCleanupError: string | null
workspaceCleanupDismissals: Record<string, WorkspaceCleanupDismissal>
workspaceCleanupViewedCandidates: Record<string, WorkspaceCleanupViewedCandidate>
scanWorkspaceCleanup: (args?: WorkspaceCleanupScanArgs) => Promise<WorkspaceCleanupScanResult>
markWorkspaceCleanupCandidateViewed: (candidate: WorkspaceCleanupCandidate) => void
dismissWorkspaceCleanupCandidates: (
candidates: readonly WorkspaceCleanupCandidate[]
) => Promise<void>
resetWorkspaceCleanupDismissals: () => Promise<void>
removeWorkspaceCleanupCandidates: (
worktreeIds: readonly string[]
) => Promise<WorkspaceCleanupRemoveResult>
}
type EnrichOptions = {
applyDismissals?: boolean
}
const RECENT_VISIBLE_CONTEXT_MS = 24 * 60 * 60 * 1000
const VIEWED_FROM_CLEANUP_MS = 2 * 60 * 60 * 1000
const SHELL_PROCESS_NAMES = new Set([
'bash',
'cmd',
'cmd.exe',
'fish',
'nu',
'powershell',
'powershell.exe',
'pwsh',
'pwsh.exe',
'sh',
'zsh'
])
const AGENT_PROCESS_NAMES = new Set([
'aider',
'amp',
'claude',
'claude-code',
'codex',
'crush',
'droid',
'gemini',
'gemini-cli',
'goose',
'opencode'
])
export const createWorkspaceCleanupSlice: StateCreator<AppState, [], [], WorkspaceCleanupSlice> = (
set,
get
) => ({
workspaceCleanupScan: null,
workspaceCleanupLoading: false,
workspaceCleanupError: null,
workspaceCleanupDismissals: {},
workspaceCleanupViewedCandidates: {},
scanWorkspaceCleanup: async (args) => {
set({ workspaceCleanupLoading: true, workspaceCleanupError: null })
try {
const scanArgs =
args?.worktreeId !== undefined
? args
: {
...args,
skipGitWorktreeIds: [
...new Set([
...(args?.skipGitWorktreeIds ?? []),
...getInitialWorkspaceCleanupGitDeferrals(get())
])
]
}
const scan = await window.api.workspaceCleanup.scan(scanArgs)
const enriched = await enrichWorkspaceCleanupCandidates(scan.candidates, get())
const result = { ...scan, candidates: enriched }
set({ workspaceCleanupScan: result, workspaceCleanupLoading: false })
return result
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
set({ workspaceCleanupError: message, workspaceCleanupLoading: false })
throw error
}
},
markWorkspaceCleanupCandidateViewed: (candidate) => {
set((state) => ({
workspaceCleanupViewedCandidates: {
...state.workspaceCleanupViewedCandidates,
[candidate.worktreeId]: {
viewedAt: Date.now(),
fingerprint: candidate.fingerprint,
wasSuggested: candidate.tier === 'ready' && canSelectWorkspaceCleanupCandidate(candidate)
}
}
}))
},
dismissWorkspaceCleanupCandidates: async (candidates) => {
const now = Date.now()
const dismissals = candidates.map((candidate) => ({
worktreeId: candidate.worktreeId,
dismissedAt: now,
fingerprint: candidate.fingerprint,
classifierVersion: WORKSPACE_CLEANUP_CLASSIFIER_VERSION
}))
set((state) => {
const nextDismissals = { ...state.workspaceCleanupDismissals }
for (const dismissal of dismissals) {
nextDismissals[dismissal.worktreeId] = dismissal
}
const nextScan = state.workspaceCleanupScan
? {
...state.workspaceCleanupScan,
candidates: state.workspaceCleanupScan.candidates.map((candidate) =>
applyDismissal(candidate, nextDismissals)
)
}
: state.workspaceCleanupScan
return {
workspaceCleanupDismissals: nextDismissals,
workspaceCleanupScan: nextScan
}
})
await window.api.workspaceCleanup.dismiss({ dismissals })
},
resetWorkspaceCleanupDismissals: async () => {
set((state) => ({
workspaceCleanupDismissals: {},
workspaceCleanupScan: state.workspaceCleanupScan
? {
...state.workspaceCleanupScan,
candidates: state.workspaceCleanupScan.candidates.map((candidate) =>
applyWorkspaceCleanupPolicy({
...candidate,
blockers: candidate.blockers.filter((blocker) => blocker !== 'dismissed')
})
)
}
: state.workspaceCleanupScan
}))
await window.api.workspaceCleanup.clearDismissals()
},
removeWorkspaceCleanupCandidates: async (worktreeIds) => {
const removedIds: string[] = []
const failures: WorkspaceCleanupFailure[] = []
for (const worktreeId of worktreeIds) {
const preflight = await preflightWorkspaceCleanupCandidate(worktreeId, get)
if (!preflight.ok) {
failures.push(preflight.failure)
continue
}
const result = await get().removeWorktree(
worktreeId,
shouldForceWorkspaceCleanupRemoval(preflight.candidate)
)
if (result.ok) {
removedIds.push(worktreeId)
} else {
failures.push({
worktreeId,
displayName: preflight.candidate.displayName,
message: result.error
})
}
}
if (removedIds.length > 0) {
set((state) => ({
workspaceCleanupScan: state.workspaceCleanupScan
? {
...state.workspaceCleanupScan,
candidates: state.workspaceCleanupScan.candidates.filter(
(candidate) => !removedIds.includes(candidate.worktreeId)
)
}
: state.workspaceCleanupScan
}))
}
return { removedIds, failures }
}
})
function getInitialWorkspaceCleanupGitDeferrals(state: AppState): string[] {
const ids = new Set<string>()
if (state.activeWorktreeId) {
ids.add(state.activeWorktreeId)
}
for (const file of state.openFiles) {
if (file.isDirty || state.editorDrafts[file.id] !== undefined) {
ids.add(file.worktreeId)
}
}
const openEditorWorktreeIds = new Set(state.openFiles.map((file) => file.worktreeId))
for (const [worktreeId, tabs] of Object.entries(state.tabsByWorktree)) {
const tabIds = new Set(tabs.map((tab) => tab.id))
if (tabs.some((tab) => (state.ptyIdsByTabId[tab.id]?.length ?? 0) > 0)) {
ids.add(worktreeId)
}
if (hasFreshLiveAgent(state, tabIds) || hasWorkingTitleAgent(state, tabs)) {
ids.add(worktreeId)
}
}
for (const worktreeId of new Set([
...openEditorWorktreeIds,
...Object.keys(state.browserTabsByWorktree)
])) {
const hasVisibleContext =
openEditorWorktreeIds.has(worktreeId) ||
(state.browserTabsByWorktree[worktreeId]?.length ?? 0) > 0
const lastVisitedAt = state.lastVisitedAtByWorktreeId[worktreeId] ?? 0
if (
hasVisibleContext &&
lastVisitedAt > 0 &&
Date.now() - lastVisitedAt <= RECENT_VISIBLE_CONTEXT_MS
) {
ids.add(worktreeId)
}
}
// Why: these rows must stay visible, but they already need user attention.
// Defer expensive git reads until a focused refresh/remove preflight.
return [...ids]
}
export async function enrichWorkspaceCleanupCandidates(
candidates: readonly WorkspaceCleanupCandidate[],
state: AppState,
options: EnrichOptions = {}
): Promise<WorkspaceCleanupCandidate[]> {
return Promise.all(
candidates.map((candidate) => enrichWorkspaceCleanupCandidate(candidate, state, options))
)
}
async function enrichWorkspaceCleanupCandidate(
candidate: WorkspaceCleanupCandidate,
state: AppState,
options: EnrichOptions
): Promise<WorkspaceCleanupCandidate> {
const tabs = state.tabsByWorktree[candidate.worktreeId] ?? []
const tabIds = new Set(tabs.map((tab) => tab.id))
const openFiles = state.openFiles.filter((file) => file.worktreeId === candidate.worktreeId)
const dirtyEditorBuffers = openFiles.filter(
(file) => file.isDirty || state.editorDrafts[file.id] !== undefined
)
const cleanEditorTabCount = openFiles.length - dirtyEditorBuffers.length
const browserTabCount = (state.browserTabsByWorktree[candidate.worktreeId] ?? []).length
const retainedDoneAgentCount = Object.values(state.retainedAgentsByPaneKey).filter(
(entry) => entry.worktreeId === candidate.worktreeId && entry.entry.state === 'done'
).length
const blockers = candidate.blockers.filter((blocker) => blocker !== 'dismissed')
const preserveCleanupInspection = shouldPreserveCleanupInspection(candidate, state)
if (state.activeWorktreeId === candidate.worktreeId) {
blockers.push('active-workspace')
}
if (dirtyEditorBuffers.length > 0) {
blockers.push('dirty-editor-buffer')
}
if (hasFreshLiveAgent(state, tabIds)) {
blockers.push('live-agent')
}
if (hasWorkingTitleAgent(state, tabs)) {
blockers.push('live-agent')
}
const terminalProbe = await probeTerminalLiveness(state, tabs)
if (terminalProbe === 'running') {
blockers.push('running-terminal')
} else if (terminalProbe === 'unknown') {
blockers.push('terminal-liveness-unknown')
}
const lastVisitedAt = state.lastVisitedAtByWorktreeId[candidate.worktreeId] ?? 0
const hasVisibleContext = cleanEditorTabCount > 0 || browserTabCount > 0
if (
hasVisibleContext &&
!preserveCleanupInspection &&
lastVisitedAt > 0 &&
Date.now() - lastVisitedAt <= RECENT_VISIBLE_CONTEXT_MS
) {
blockers.push('recent-visible-context')
}
const enriched = applyWorkspaceCleanupPolicy({
...candidate,
blockers: [...new Set(blockers)],
localContext: {
...candidate.localContext,
terminalTabCount: tabs.length,
cleanEditorTabCount,
browserTabCount,
retainedDoneAgentCount
}
})
return options.applyDismissals === false
? enriched
: applyDismissal(enriched, state.workspaceCleanupDismissals)
}
function shouldPreserveCleanupInspection(
candidate: WorkspaceCleanupCandidate,
state: AppState
): boolean {
const viewed = state.workspaceCleanupViewedCandidates[candidate.worktreeId]
if (!viewed?.wasSuggested || viewed.fingerprint !== candidate.fingerprint) {
return false
}
// Why: View is part of cleanup review. It should not make the same
// suggested row vanish on the next scan, but this exception must expire.
return Date.now() - viewed.viewedAt <= VIEWED_FROM_CLEANUP_MS
}
function applyDismissal(
candidate: WorkspaceCleanupCandidate,
dismissals: Record<string, WorkspaceCleanupDismissal>
): WorkspaceCleanupCandidate {
if (!shouldHideWorkspaceCleanupCandidate(candidate, dismissals[candidate.worktreeId])) {
return candidate
}
return applyWorkspaceCleanupPolicy({
...candidate,
blockers: [...new Set<WorkspaceCleanupBlocker>([...candidate.blockers, 'dismissed'])]
})
}
async function preflightWorkspaceCleanupCandidate(
worktreeId: string,
getState: () => AppState
): Promise<
| { ok: true; candidate: WorkspaceCleanupCandidate }
| { ok: false; failure: WorkspaceCleanupFailure }
> {
const scan = await window.api.workspaceCleanup.scan({ worktreeId })
const [candidate] = await enrichWorkspaceCleanupCandidates(scan.candidates, getState(), {
applyDismissals: false
})
if (!candidate) {
return {
ok: false,
failure: {
worktreeId,
displayName: worktreeId,
message: 'Workspace no longer exists.'
}
}
}
if (!canQueueWorkspaceCleanupCandidate(candidate)) {
return {
ok: false,
failure: {
worktreeId,
displayName: candidate.displayName,
message: candidate.blockers.length
? candidate.blockers.join(', ')
: 'Workspace is no longer safe to remove.'
}
}
}
return { ok: true, candidate }
}
function hasFreshLiveAgent(state: AppState, tabIds: Set<string>): boolean {
const now = Date.now()
return Object.values(state.agentStatusByPaneKey).some(
(entry) =>
tabIds.has(getPaneKeyTabId(entry.paneKey)) &&
isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS) &&
(entry.state === 'working' || entry.state === 'blocked' || entry.state === 'waiting')
)
}
function hasWorkingTitleAgent(state: AppState, tabs: { id: string; title: string }[]): boolean {
for (const tab of tabs) {
if ((state.ptyIdsByTabId[tab.id]?.length ?? 0) === 0) {
continue
}
const paneTitles = state.runtimePaneTitlesByTabId[tab.id]
const titles =
paneTitles && Object.keys(paneTitles).length > 0 ? Object.values(paneTitles) : [tab.title]
for (const title of titles) {
const status = detectAgentStatusFromTitle(title)
if (status === 'working' || status === 'permission') {
return true
}
}
}
return false
}
async function probeTerminalLiveness(
state: AppState,
tabs: { id: string; title: string }[]
): Promise<'idle' | 'running' | 'unknown'> {
const ptyChecks = tabs.flatMap((tab) =>
(state.ptyIdsByTabId[tab.id] ?? []).map((ptyId) => ({ tab, ptyId }))
)
if (ptyChecks.length === 0) {
return 'idle'
}
let unknown = false
for (const { tab, ptyId } of ptyChecks) {
try {
const [hasChildProcesses, foregroundProcess] = await Promise.all([
window.api.pty.hasChildProcesses(ptyId),
window.api.pty.getForegroundProcess(ptyId)
])
const processName = normalizeProcessName(foregroundProcess)
if (!hasChildProcesses && (!processName || SHELL_PROCESS_NAMES.has(processName))) {
continue
}
if (
processName &&
AGENT_PROCESS_NAMES.has(processName) &&
hasIdleAgentTitleForPty(state, tab, ptyId)
) {
continue
}
return 'running'
} catch {
unknown = true
}
}
return unknown ? 'unknown' : 'idle'
}
function hasIdleAgentTitleForPty(
state: AppState,
tab: { id: string; title: string },
ptyId: string
): boolean {
const paneTitles = state.runtimePaneTitlesByTabId[tab.id] ?? {}
const layoutPtyIds = state.terminalLayoutsByTabId?.[tab.id]?.ptyIdsByLeafId ?? {}
const matchingTitles = Object.entries(layoutPtyIds)
.filter(([, leafPtyId]) => leafPtyId === ptyId)
.map(([leafId]) => paneTitles[leafId.replace(/^pane:/, '')])
.filter((title): title is string => typeof title === 'string')
if (matchingTitles.length > 0) {
return matchingTitles.some(isIdleAgentTitle)
}
// Why: without a pane->PTY binding, a tab-level idle title is safe evidence
// only when this tab has a single live PTY. Multi-pane tabs stay protected.
const tabPtyIds = state.ptyIdsByTabId[tab.id] ?? []
if (tabPtyIds.length !== 1) {
return false
}
const titles = Object.keys(paneTitles).length > 0 ? Object.values(paneTitles) : [tab.title]
return titles.some(isIdleAgentTitle)
}
function isIdleAgentTitle(title: string): boolean {
return detectAgentStatusFromTitle(title) === 'idle'
}
function getPaneKeyTabId(paneKey: AgentStatusEntry['paneKey']): string {
const separatorIndex = paneKey.lastIndexOf(':')
return separatorIndex === -1 ? paneKey : paneKey.slice(0, separatorIndex)
}
function normalizeProcessName(value: string | null): string | null {
if (!value) {
return null
}
const normalizedPath = value.replace(/\\/g, '/')
const name = normalizedPath.slice(normalizedPath.lastIndexOf('/') + 1).toLowerCase()
return name.replace(/\.exe$/i, '.exe')
}
+3 -1
View File
@@ -22,6 +22,7 @@ import type { DiffCommentsSlice } from './slices/diffComments'
import type { DetectedAgentsSlice } from './slices/detected-agents'
import type { WorktreeNavHistorySlice } from './slices/worktree-nav-history'
import type { DictationSlice } from './slices/dictation'
import type { WorkspaceCleanupSlice } from './slices/workspace-cleanup'
export type AppState = RepoSlice &
SparsePresetsSlice &
@@ -46,4 +47,5 @@ export type AppState = RepoSlice &
DiffCommentsSlice &
DetectedAgentsSlice &
WorktreeNavHistorySlice &
DictationSlice
DictationSlice &
WorkspaceCleanupSlice
+2 -1
View File
@@ -349,7 +349,8 @@ export function getDefaultUIState(): PersistedUIState {
dismissedUpdateVersion: null,
lastUpdateCheckAt: null,
trustedOrcaHooks: {},
acknowledgedAgentsByPaneKey: {}
acknowledgedAgentsByPaneKey: {},
workspaceCleanup: { dismissals: {} }
}
}
+2
View File
@@ -5,6 +5,7 @@ import type { WorkspaceSource } from './telemetry-events'
import type { GitHubProjectSettings } from './github-project-types'
import type { MigrationUnsupportedPtyEntry } from './agent-status-types'
import type { VoiceSettings } from './speech-types'
import type { WorkspaceCleanupUIState } from './workspace-cleanup'
import type { GitLabProjectSettings } from './gitlab-types'
// Re-exported for backward compat with renderer call sites that import
@@ -1730,6 +1731,7 @@ export type PersistedUIState = {
* using their existing settings paths; this only restores transient tabs
* and applied searches. */
taskResumeState?: TaskResumeState
workspaceCleanup?: WorkspaceCleanupUIState
}
export const PET_SIZE_MIN = 60
+129
View File
@@ -0,0 +1,129 @@
import { describe, expect, it } from 'vitest'
import {
WORKSPACE_CLEANUP_CLASSIFIER_VERSION,
applyWorkspaceCleanupPolicy,
canQueueWorkspaceCleanupCandidate,
canSelectWorkspaceCleanupCandidate,
createWorkspaceCleanupFingerprint,
shouldForceWorkspaceCleanupRemoval,
shouldHideWorkspaceCleanupCandidate,
type WorkspaceCleanupCandidate
} from './workspace-cleanup'
type CandidateOverrides = Partial<Omit<WorkspaceCleanupCandidate, 'git' | 'localContext'>> & {
git?: Partial<WorkspaceCleanupCandidate['git']>
localContext?: Partial<WorkspaceCleanupCandidate['localContext']>
}
function makeCandidate(overrides: CandidateOverrides = {}): WorkspaceCleanupCandidate {
const { git, localContext, ...candidateOverrides } = overrides
const candidate: WorkspaceCleanupCandidate = {
worktreeId: 'repo-1::/tmp/feature',
repoId: 'repo-1',
repoName: 'Repo',
connectionId: null,
displayName: 'feature',
branch: 'feature',
path: '/tmp/feature',
tier: 'review',
selectedByDefault: false,
reasons: ['idle-clean'],
blockers: [],
lastActivityAt: 1_700_000_000_000,
localContext: {
terminalTabCount: 0,
cleanEditorTabCount: 0,
browserTabCount: 0,
diffCommentCount: 0,
newestDiffCommentAt: null,
retainedDoneAgentCount: 0
},
git: {
clean: true,
upstreamAhead: 0,
upstreamBehind: 0,
checkedAt: 1_700_000_000_000
},
fingerprint: 'fingerprint',
...candidateOverrides
}
return {
...candidate,
git: { ...candidate.git, ...git },
localContext: { ...candidate.localContext, ...localContext }
}
}
describe('workspace cleanup policy', () => {
it('marks clean inactive workspaces as ready and selected', () => {
const candidate = applyWorkspaceCleanupPolicy(makeCandidate())
expect(candidate.tier).toBe('ready')
expect(candidate.selectedByDefault).toBe(true)
expect(canSelectWorkspaceCleanupCandidate(candidate)).toBe(true)
})
it('requires an inactivity reason before selecting a workspace', () => {
const candidate = applyWorkspaceCleanupPolicy(makeCandidate({ reasons: [] }))
expect(canSelectWorkspaceCleanupCandidate(candidate)).toBe(false)
expect(candidate.tier).toBe('review')
expect(candidate.selectedByDefault).toBe(false)
})
it('keeps not-suggested candidates queueable when git evidence is clean', () => {
const candidate = applyWorkspaceCleanupPolicy(makeCandidate({ blockers: ['unpushed-commits'] }))
expect(candidate.tier).toBe('protected')
expect(candidate.selectedByDefault).toBe(false)
expect(canSelectWorkspaceCleanupCandidate(candidate)).toBe(false)
expect(canQueueWorkspaceCleanupCandidate(candidate)).toBe(true)
expect(shouldForceWorkspaceCleanupRemoval(candidate)).toBe(true)
})
it('does not queue main worktrees or folder projects for cleanup removal', () => {
const mainWorktree = applyWorkspaceCleanupPolicy(makeCandidate({ blockers: ['main-worktree'] }))
const folderProject = applyWorkspaceCleanupPolicy(makeCandidate({ blockers: ['folder-repo'] }))
expect(canQueueWorkspaceCleanupCandidate(mainWorktree)).toBe(false)
expect(canQueueWorkspaceCleanupCandidate(folderProject)).toBe(false)
})
it('requires current git status before selecting a workspace', () => {
const candidate = applyWorkspaceCleanupPolicy(
makeCandidate({
git: { clean: null, checkedAt: null }
})
)
expect(candidate.tier).toBe('review')
expect(canSelectWorkspaceCleanupCandidate(candidate)).toBe(false)
})
it('matches dismissals only for the current classifier fingerprint', () => {
const fingerprint = createWorkspaceCleanupFingerprint({
branch: 'feature',
head: 'abc123',
gitClean: true,
lastActivityAt: 1_700_000_000_000
})
const candidate = makeCandidate({ fingerprint })
expect(
shouldHideWorkspaceCleanupCandidate(candidate, {
worktreeId: candidate.worktreeId,
dismissedAt: 1_700_000_000_000,
fingerprint,
classifierVersion: WORKSPACE_CLEANUP_CLASSIFIER_VERSION
})
).toBe(true)
expect(
shouldHideWorkspaceCleanupCandidate(candidate, {
worktreeId: candidate.worktreeId,
dismissedAt: 1_700_000_000_000,
fingerprint: `${fingerprint}|changed`,
classifierVersion: WORKSPACE_CLEANUP_CLASSIFIER_VERSION
})
).toBe(false)
})
})
+232
View File
@@ -0,0 +1,232 @@
export const WORKSPACE_CLEANUP_CLASSIFIER_VERSION = 2
export const WORKSPACE_CLEANUP_ARCHIVED_IDLE_MS = 7 * 24 * 60 * 60 * 1000
export const WORKSPACE_CLEANUP_IDLE_MS = 30 * 24 * 60 * 60 * 1000
export type WorkspaceCleanupTier = 'ready' | 'review' | 'protected'
export type WorkspaceCleanupReason = 'archived' | 'idle-clean'
export type WorkspaceCleanupInactivityInput = {
isArchived: boolean
lastActivityAt: number
}
export type WorkspaceCleanupBlocker =
| 'main-worktree'
| 'folder-repo'
| 'pinned'
| 'active-workspace'
| 'running-terminal'
| 'terminal-liveness-unknown'
| 'dirty-editor-buffer'
| 'volatile-local-context'
| 'recent-visible-context'
| 'live-agent'
| 'ssh-disconnected'
| 'git-status-error'
| 'dirty-files'
| 'unpushed-commits'
| 'unknown-base'
| 'dismissed'
export type WorkspaceCleanupDismissal = {
worktreeId: string
dismissedAt: number
fingerprint: string
classifierVersion: number
}
export type WorkspaceCleanupUIState = {
dismissals: Record<string, WorkspaceCleanupDismissal>
}
export type WorkspaceCleanupCandidate = {
worktreeId: string
repoId: string
repoName: string
connectionId: string | null
displayName: string
branch: string
path: string
tier: WorkspaceCleanupTier
selectedByDefault: boolean
reasons: WorkspaceCleanupReason[]
blockers: WorkspaceCleanupBlocker[]
lastActivityAt: number
createdAt?: number
localContext: {
terminalTabCount: number
cleanEditorTabCount: number
browserTabCount: number
diffCommentCount: number
newestDiffCommentAt: number | null
retainedDoneAgentCount: number
}
git: {
clean: boolean | null
upstreamAhead: number | null
upstreamBehind: number | null
checkedAt: number | null
}
fingerprint: string
}
export type WorkspaceCleanupScanArgs = {
worktreeId?: string
skipGitWorktreeIds?: string[]
}
export type WorkspaceCleanupLocalProcessArgs = {
worktreeId: string
connectionId?: string | null
worktreePath?: string
}
export type WorkspaceCleanupScanError = {
repoId: string
repoName: string
message: string
}
export type WorkspaceCleanupScanResult = {
scannedAt: number
candidates: WorkspaceCleanupCandidate[]
errors: WorkspaceCleanupScanError[]
}
export type WorkspaceCleanupLocalProcessResult = {
hasKillableProcesses: boolean | null
}
export type WorkspaceCleanupDismissArgs = {
dismissals: WorkspaceCleanupDismissal[]
}
export const WORKSPACE_CLEANUP_HARD_BLOCKERS: ReadonlySet<WorkspaceCleanupBlocker> = new Set([
'main-worktree',
'folder-repo',
'pinned',
'active-workspace',
'running-terminal',
'terminal-liveness-unknown',
'dirty-editor-buffer',
'volatile-local-context',
'live-agent',
'recent-visible-context',
'ssh-disconnected',
'git-status-error',
'dirty-files',
'unpushed-commits',
'unknown-base',
'dismissed'
])
const WORKSPACE_CLEANUP_QUEUE_BLOCKERS: ReadonlySet<WorkspaceCleanupBlocker> = new Set([
'main-worktree',
'folder-repo',
'dismissed'
])
export const WORKSPACE_CLEANUP_FORCE_REMOVE_BLOCKERS: ReadonlySet<WorkspaceCleanupBlocker> =
new Set(['dirty-files', 'unpushed-commits', 'unknown-base', 'git-status-error'])
export function isWorkspaceCleanupHardBlocker(blocker: WorkspaceCleanupBlocker): boolean {
return WORKSPACE_CLEANUP_HARD_BLOCKERS.has(blocker)
}
export function canQueueWorkspaceCleanupCandidate(
candidate: Pick<WorkspaceCleanupCandidate, 'blockers' | 'reasons'>
): boolean {
return (
candidate.reasons.length > 0 &&
!candidate.blockers.some((blocker) => WORKSPACE_CLEANUP_QUEUE_BLOCKERS.has(blocker))
)
}
export function shouldForceWorkspaceCleanupRemoval(
candidate: Pick<WorkspaceCleanupCandidate, 'blockers' | 'git'>
): boolean {
return (
candidate.git.clean !== true ||
candidate.git.checkedAt === null ||
candidate.blockers.some((blocker) => WORKSPACE_CLEANUP_FORCE_REMOVE_BLOCKERS.has(blocker))
)
}
export function canSelectWorkspaceCleanupCandidate(
candidate: Pick<WorkspaceCleanupCandidate, 'blockers' | 'git' | 'reasons'>
): boolean {
return (
candidate.reasons.length > 0 &&
candidate.git.clean === true &&
candidate.git.checkedAt !== null &&
!candidate.blockers.some(isWorkspaceCleanupHardBlocker)
)
}
export function applyWorkspaceCleanupPolicy(
candidate: WorkspaceCleanupCandidate
): WorkspaceCleanupCandidate {
const canSelect = canSelectWorkspaceCleanupCandidate(candidate)
const hasHardBlocker = candidate.blockers.some(isWorkspaceCleanupHardBlocker)
const tier: WorkspaceCleanupTier = hasHardBlocker ? 'protected' : canSelect ? 'ready' : 'review'
return {
...candidate,
tier,
selectedByDefault: tier === 'ready' && canSelect
}
}
export function createWorkspaceCleanupFingerprint(args: {
branch: string
head: string
gitClean: boolean | null
lastActivityAt: number
classifierVersion?: number
}): string {
const version = args.classifierVersion ?? WORKSPACE_CLEANUP_CLASSIFIER_VERSION
const lastActivityBucket = Math.floor((args.lastActivityAt || 0) / (24 * 60 * 60 * 1000))
return [
version,
args.branch,
args.head,
args.gitClean === null ? 'unknown' : args.gitClean ? 'clean' : 'dirty',
lastActivityBucket
].join('|')
}
export function getWorkspaceCleanupInactivityReasons(
workspace: WorkspaceCleanupInactivityInput,
scannedAt: number
): WorkspaceCleanupReason[] {
const reasons: WorkspaceCleanupReason[] = []
if (
workspace.isArchived &&
scannedAt - workspace.lastActivityAt >= WORKSPACE_CLEANUP_ARCHIVED_IDLE_MS
) {
reasons.push('archived')
}
if (scannedAt - workspace.lastActivityAt >= WORKSPACE_CLEANUP_IDLE_MS) {
reasons.push('idle-clean')
}
return reasons
}
export function isWorkspaceOldForCleanup(
workspace: WorkspaceCleanupInactivityInput,
scannedAt: number
): boolean {
return getWorkspaceCleanupInactivityReasons(workspace, scannedAt).length > 0
}
export function shouldHideWorkspaceCleanupCandidate(
candidate: Pick<WorkspaceCleanupCandidate, 'worktreeId' | 'fingerprint'>,
dismissal: WorkspaceCleanupDismissal | undefined
): boolean {
return (
dismissal?.worktreeId === candidate.worktreeId &&
dismissal.fingerprint === candidate.fingerprint &&
dismissal.classifierVersion === WORKSPACE_CLEANUP_CLASSIFIER_VERSION
)
}