diff --git a/src/main/git/checkpoints/worktree-checkpoint-git.ts b/src/main/git/checkpoints/worktree-checkpoint-git.ts index 33e6c2ea8e5..973abd6550c 100644 --- a/src/main/git/checkpoints/worktree-checkpoint-git.ts +++ b/src/main/git/checkpoints/worktree-checkpoint-git.ts @@ -67,7 +67,12 @@ export function defaultCheckpointGit(cwd: string): CheckpointGit { const { stdout } = await gitExecFileAsync(args, { cwd, // Plumbing only: no optional locks, so a snapshot never contends with the user's own git. - env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', ...CHECKPOINT_IDENTITY, ...options.env }, + env: { + ...process.env, + GIT_OPTIONAL_LOCKS: '0', + ...CHECKPOINT_IDENTITY, + ...options.env + }, ...(options.stdin !== undefined ? { stdin: options.stdin } : {}), ...(options.signal ? { signal: options.signal } : {}), timeout: options.timeoutMs ?? 120_000, diff --git a/src/main/git/checkpoints/worktree-checkpoint-real-git.test.ts b/src/main/git/checkpoints/worktree-checkpoint-real-git.test.ts index de02c62dde5..62b181f59d5 100644 --- a/src/main/git/checkpoints/worktree-checkpoint-real-git.test.ts +++ b/src/main/git/checkpoints/worktree-checkpoint-real-git.test.ts @@ -15,6 +15,7 @@ import { readWorktreeCheckpoint } from './worktree-checkpoint-snapshot' import { previewWorktreeRestore, restoreWorktreeCheckpoint } from './worktree-checkpoint-restore' +import { assertUndoCovers } from './worktree-checkpoint-restore-guards' import { listCheckpointRefs, pruneCheckpointRefs } from './worktree-checkpoint-retention' let dir: string @@ -138,8 +139,9 @@ describe('worktree checkpoints', () => { expect(result.indexRestored).toBe(true) expect(await git('diff', '--cached', '--name-status')).toBe('') expect(await git('status', '--porcelain=v1')).toBe('?? bin.dat\n?? untracked.txt'.trim()) - expect((await previewWorktreeRestore(repo, (await readWorktreeCheckpoint(repo, T1))!)).changes) - .toEqual([]) + expect( + (await previewWorktreeRestore(repo, (await readWorktreeCheckpoint(repo, T1))!)).changes + ).toEqual([]) }) it('leaves gitignored files alone', async () => { @@ -225,7 +227,9 @@ describe('worktree checkpoints', () => { await git('-c', 'commit.gpgsign=false', 'commit', '-qam', 'main') await runProcess({ program: 'git', args: ['merge', 'other'], cwd: dir }) const conflicted = await read('a.txt') - await expect(restore()).rejects.toMatchObject({ reason: 'merge-conflicts' }) + await expect(restore()).rejects.toMatchObject({ + reason: 'merge-conflicts' + }) expect(await read('a.txt')).toBe(conflicted) expect(await git('for-each-ref', 'refs/orca/checkpoints/s1/undo/')).toBe('') }) @@ -287,6 +291,7 @@ describe('worktree checkpoints', () => { expect(result.changes.map((c) => c.path)).toEqual(['new.txt']) expect(await read('a.txt')).toBe('local only\n') expect(await read('keep/b.txt')).toBe('local too\n') + expect(await git('ls-files', '-v', 'a.txt')).toBe('S a.txt') }) it('names its undo point when a restore fails partway', async () => { @@ -307,13 +312,38 @@ describe('worktree checkpoints', () => { expect(existsSync(join(dir, 'extra.txt'))).toBe(false) await chmod(join(dir, 'locked'), 0o755) const undo = await readWorktreeCheckpoint(repo, undoRef ?? '') - await restoreWorktreeCheckpoint(repo, undo!, { ref: 'refs/orca/checkpoints/s1/undo/u9', now: NOW }) + await restoreWorktreeCheckpoint(repo, undo!, { + ref: 'refs/orca/checkpoints/s1/undo/u9', + now: NOW + }) expect(await read('extra.txt')).toBe('agent\n') } finally { await chmod(join(dir, 'locked'), 0o755) } }) + it('never writes into a nested repository the agent created', async () => { + await put('sub/a.txt', 'checkpointed\n') + await capture() + await git('-C', join(dir, 'sub'), 'init', '-q') + await put('sub/a.txt', 'uncommitted work in the nested repo\n') + await put('a.txt', 'agent\n') + await expect(restore()).rejects.toMatchObject({ reason: 'blocked-path' }) + expect(await read('sub/a.txt')).toBe('uncommitted work in the nested repo\n') + expect(await read('a.txt')).toBe('agent\n') + }) + + it('refuses when a path on disk is missing from the undo tree', async () => { + await put('present.txt', 'on disk\n') + const empty = (await git('hash-object', '-t', 'tree', '-w', '--stdin')).trim() + await expect( + assertUndoCovers(repo, empty, [{ status: 'M', path: 'present.txt' }]) + ).rejects.toMatchObject({ reason: 'blocked-path', paths: ['present.txt'] }) + await expect( + assertUndoCovers(repo, empty, [{ status: 'A', path: 'absent.txt' }]) + ).resolves.toBeUndefined() + }) + it('works on an unborn branch', async () => { await rm(join(dir, '.git'), { recursive: true }) await git('init', '-q') @@ -363,7 +393,9 @@ describe('worktree checkpoints', () => { it('rejects plain folders', async () => { const plain = await mkdtemp(join(tmpdir(), 'orca-checkpoint-plain-')) try { - await expect(openCheckpointRepo(plain)).rejects.toMatchObject({ reason: 'not-a-repo' }) + await expect(openCheckpointRepo(plain)).rejects.toMatchObject({ + reason: 'not-a-repo' + }) } finally { await rm(plain, { recursive: true, force: true }) } diff --git a/src/main/git/checkpoints/worktree-checkpoint-restore-guards.ts b/src/main/git/checkpoints/worktree-checkpoint-restore-guards.ts index 3568da6c5e4..cdee8184396 100644 --- a/src/main/git/checkpoints/worktree-checkpoint-restore-guards.ts +++ b/src/main/git/checkpoints/worktree-checkpoint-restore-guards.ts @@ -71,6 +71,19 @@ export function overwrittenUnsnapshottedPaths(repo: CheckpointRepo, target: Work } } +async function hasGitDir( + repo: CheckpointRepo, + folder: string, + cache: Map +): Promise { + let known = cache.get(folder) + if (known === undefined) { + known = (await lstat(join(repo.root, folder, '.git')).catch(() => null)) !== null + cache.set(folder, known) + } + return known +} + /** Refuses before any write when a path to write is a folder or an unreadable file now, when a * leading folder of it is now a file the restore doesn't delete itself (an ignored file would be * replaced with no copy), or when any path is unsafe. */ @@ -94,9 +107,18 @@ export async function assertWritable(repo: CheckpointRepo, changes: TreeChange[] } return known } + const gitDirs = new Map() const blocked: string[] = [] for (const change of changes) { + const parts = change.path.split('/') + // A nested repository owns its files; the restore never writes or deletes inside one. if (change.status === 'D') { + for (let depth = 1; depth < parts.length; depth += 1) { + if (await hasGitDir(repo, parts.slice(0, depth).join('/'), gitDirs)) { + blocked.push(change.path) + break + } + } continue } const absolute = join(repo.root, change.path) @@ -107,13 +129,17 @@ export async function assertWritable(repo: CheckpointRepo, changes: TreeChange[] () => false, () => true )) - const parts = change.path.split('/') let leadingFile = false for (let depth = 1; depth < parts.length && !leadingFile; depth += 1) { const prefix = parts.slice(0, depth).join('/') leadingFile = !deleted.has(prefix) && (await isNonFolder(prefix)) } - if (stat?.isDirectory() || unreadable || leadingFile) { + let nestedRepo = false + for (let depth = 1; depth < parts.length && !nestedRepo; depth += 1) { + const prefix = parts.slice(0, depth).join('/') + nestedRepo = await hasGitDir(repo, prefix, gitDirs) + } + if (stat?.isDirectory() || unreadable || leadingFile || nestedRepo) { blocked.push(change.path) } } @@ -125,3 +151,34 @@ export async function assertWritable(repo: CheckpointRepo, changes: TreeChange[] ) } } + +/** Every path the restore writes or deletes that exists on disk must be in the undo tree, or the + * restore could destroy work nothing saved. `git add` can skip a path without failing (a nested + * repo with no commits, a file it couldn't read), so this checks the tree itself. */ +export async function assertUndoCovers( + repo: CheckpointRepo, + undoTree: string, + changes: TreeChange[] +): Promise { + const present: string[] = [] + for (const change of changes) { + if (await lstat(join(repo.root, change.path)).catch(() => null)) { + present.push(change.path) + } + } + if (present.length === 0) { + return + } + const out = await repo.git(['cat-file', '--batch-check=%(objecttype)'], { + stdin: present.map((path) => `${undoTree}:${path}\n`).join('') + }) + const answers = out.split('\n') + const missing = present.filter((_, index) => !answers[index]?.endsWith('blob')) + if (missing.length > 0) { + throw new WorktreeCheckpointError( + 'blocked-path', + 'Some files the restore would change could not be saved first.', + missing + ) + } +} diff --git a/src/main/git/checkpoints/worktree-checkpoint-restore.ts b/src/main/git/checkpoints/worktree-checkpoint-restore.ts index 7b14bb5f282..78bb60ca115 100644 --- a/src/main/git/checkpoints/worktree-checkpoint-restore.ts +++ b/src/main/git/checkpoints/worktree-checkpoint-restore.ts @@ -14,6 +14,7 @@ import { } from './worktree-checkpoint-git' import { assertNoConflicts, + assertUndoCovers, assertWritable, hiddenIndexPaths, overwrittenUnsnapshottedPaths, @@ -78,7 +79,8 @@ async function removeWorktreeFile(rootReal: string, root: string, path: string): async function restoreIndexEntries( repo: CheckpointRepo, fromTree: string, - toTree: string + toTree: string, + hidden: Set ): Promise { if (fromTree === toTree) { return @@ -93,11 +95,17 @@ async function restoreIndexEntries( } const [, newMode, , newObject] = header.slice(1).split(' ') const path = fields[index + 1] + // Rewriting an entry drops its skip-worktree/assume-unchanged bit; those stay as they are. + if (path === undefined || hidden.has(path)) { + continue + } // A path the staged tree lacks arrives as mode 000000 with an all-zero id: --index-info removes it. records.push(`${newMode === '000000' ? '0' : newMode} ${newObject}\t${path}`) } if (records.length > 0) { - await repo.git(['update-index', '-z', '--index-info'], { stdin: `${records.join('\0')}\0` }) + await repo.git(['update-index', '-z', '--index-info'], { + stdin: `${records.join('\0')}\0` + }) } } @@ -139,6 +147,7 @@ export async function restoreWorktreeCheckpoint( }) const changes = await restoreChanges(repo, before.tree, target.tree, hidden) await assertWritable(repo, changes) + await assertUndoCovers(repo, before.tree, changes) const undoCheckpoint = await writeWorktreeCheckpoint(repo, undo.ref, before, { kind: 'undo', createdAt: undo.now, @@ -162,7 +171,7 @@ export async function restoreWorktreeCheckpoint( // differ are rewritten, so the rest keep their stat data and the next status stays fast. Files // are already restored, so a busy index (another git holding index.lock) only loses staging. try { - await restoreIndexEntries(repo, before.indexTree, target.indexTree) + await restoreIndexEntries(repo, before.indexTree, target.indexTree, hidden) indexRestored = true } catch { indexRestored = false diff --git a/src/main/git/checkpoints/worktree-checkpoint-retention.ts b/src/main/git/checkpoints/worktree-checkpoint-retention.ts index a681481a641..a1b66e8ceb5 100644 --- a/src/main/git/checkpoints/worktree-checkpoint-retention.ts +++ b/src/main/git/checkpoints/worktree-checkpoint-retention.ts @@ -18,7 +18,10 @@ async function listRefs(repo: CheckpointRepo, prefix: string): Promise .filter(Boolean) .map((line) => { const space = line.indexOf(' ') - return { committedAt: Number(line.slice(0, space)) * 1000, ref: line.slice(space + 1) } + return { + committedAt: Number(line.slice(0, space)) * 1000, + ref: line.slice(space + 1) + } }) } diff --git a/src/main/git/checkpoints/worktree-checkpoint-snapshot.ts b/src/main/git/checkpoints/worktree-checkpoint-snapshot.ts index aa1b0f1a2be..2baabad10bf 100644 --- a/src/main/git/checkpoints/worktree-checkpoint-snapshot.ts +++ b/src/main/git/checkpoints/worktree-checkpoint-snapshot.ts @@ -58,11 +58,15 @@ export const CHECKPOINT_MAX_UNTRACKED_BYTES = 10 * 1024 * 1024 async function largeUntrackedPaths( repo: CheckpointRepo, - options: CheckpointGitOptions + options: CheckpointGitOptions, + deadline: number | null ): Promise { const out = await repo.git(['ls-files', '-o', '--exclude-standard', '-z'], options) const large: string[] = [] for (const path of out.split('\0')) { + if (deadline !== null && Date.now() > deadline) { + throw new WorktreeCheckpointError('snapshot-failed', 'The snapshot ran out of time.') + } const stat = path ? await lstat(join(repo.root, path)).catch(() => null) : null if (stat?.isFile() && stat.size > CHECKPOINT_MAX_UNTRACKED_BYTES) { large.push(path) @@ -99,7 +103,7 @@ export async function captureWorktreeTree( ...(env ? { env } : {}) }) const head = await resolveCommit(repo, 'HEAD') - const large = await largeUntrackedPaths(repo, run()) + const large = await largeUntrackedPaths(repo, run(), deadline) return withTempIndex(repo, true, async (env) => { let indexTree: string | null = null try { @@ -156,26 +160,32 @@ export async function writeWorktreeCheckpoint( // The staged tree rides as the second parent so gc keeps it as long as the checkpoint. const indexCommit = snapshot.indexTree ? ( - await repo.git([ - 'commit-tree', - '--no-gpg-sign', - snapshot.indexTree, - ...headParent, - '-m', - 'Orca checkpoint index' - ], { env }) + await repo.git( + [ + 'commit-tree', + '--no-gpg-sign', + snapshot.indexTree, + ...headParent, + '-m', + 'Orca checkpoint index' + ], + { env } + ) ).trim() : null const commit = ( - await repo.git([ - 'commit-tree', - '--no-gpg-sign', - snapshot.tree, - ...headParent, - ...(indexCommit ? ['-p', indexCommit] : []), - '-m', - `Orca checkpoint (${meta.kind})\n\n${META_PREFIX}${JSON.stringify(full)}` - ], { env }) + await repo.git( + [ + 'commit-tree', + '--no-gpg-sign', + snapshot.tree, + ...headParent, + ...(indexCommit ? ['-p', indexCommit] : []), + '-m', + `Orca checkpoint (${meta.kind})\n\n${META_PREFIX}${JSON.stringify(full)}` + ], + { env } + ) ).trim() await repo.git(['update-ref', ref, commit]) return { ...full, ref, commit, tree: snapshot.tree } diff --git a/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoint-queue.ts b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoint-queue.ts new file mode 100644 index 00000000000..a84c8041731 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoint-queue.ts @@ -0,0 +1,32 @@ +// Per-worktree ordering shared by every chat's checkpoint work in this process. + +// One git writer per worktree at a time across every chat in this process: a capture never +// interleaves with a restore, so a send after a rewind snapshots the restored files. +const queues = new Map>() +export function serialize(root: string, task: () => Promise): Promise { + const run = (queues.get(root) ?? Promise.resolve()).then(task, task) + const tail = run.catch(() => undefined) + queues.set(root, tail) + void tail.then(() => queues.get(root) === tail && queues.delete(root)) + return run +} + +// Worktrees with a turn between its snapshot and its hand-off to the agent: the chat isn't +// "working" yet, but a restore now would rewrite files the agent is about to see. +export const startingTurns = new Map() +export function markTurnStarting(root: string): () => void { + startingTurns.set(root, (startingTurns.get(root) ?? 0) + 1) + let released = false + return () => { + if (released) { + return + } + released = true + const left = (startingTurns.get(root) ?? 1) - 1 + if (left > 0) { + startingTurns.set(root, left) + } else { + startingTurns.delete(root) + } + } +} diff --git a/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints-host.ts b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints-host.ts new file mode 100644 index 00000000000..064c3668c05 --- /dev/null +++ b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints-host.ts @@ -0,0 +1,60 @@ +// Binds checkpoints to the host: the capture a send takes, and the host's preview/restore/undo. + +import type { StructuredAgentSessionDeliveryLoopDeps } from '../delivery/structured-agent-session-delivery-loop-deps' +import type { StructuredAgentSessionHostDeps } from '../host/structured-agent-session-host-types' +import { + type AgentSessionCheckpoints, + createAgentSessionCheckpoints +} from './agent-session-checkpoints' + +/** The snapshot a send takes before its message opens a turn; never throws. */ +export function structuredAgentSessionTurnCheckpoint( + deps: Pick< + StructuredAgentSessionDeliveryLoopDeps, + 'record' | 'resolveWorkspacePath' | 'logger' | 'now' + >, + sessionId: string +): (itemId: string, signal?: AbortSignal) => Promise<() => void> { + const { captureTurn } = createAgentSessionCheckpoints({ + record: deps.record, + ...(deps.resolveWorkspacePath ? { resolveWorkspacePath: deps.resolveWorkspacePath } : {}), + isBusy: () => false, + logger: deps.logger, + now: deps.now + }) + return (itemId, signal) => captureTurn(sessionId, itemId, signal) +} + +type CheckpointHost = { + deps: Pick + readStatusSummary: (sessionId: string) => { status: string | null } | undefined +} +const hostCheckpoints = new WeakMap() + +/** Preview, restore and undo for a host's chats; a restore waits for a running turn to end. */ +export function hostAgentSessionCheckpoints(host: CheckpointHost): AgentSessionCheckpoints { + let checkpoints = hostCheckpoints.get(host) + if (!checkpoints) { + const { deps } = host + checkpoints = createAgentSessionCheckpoints({ + record: (sessionId) => deps.store.getRecord(sessionId), + ...(deps.resolveWorkspacePath ? { resolveWorkspacePath: deps.resolveWorkspacePath } : {}), + // Any chat working in the same worktree could be writing the files a restore rewrites. + isBusy: (sessionId) => { + const location = deps.store.getRecord(sessionId)?.location + return deps.store + .listConversations() + .some( + (record) => + record.location.workspaceId === location?.workspaceId && + record.location.executionHostId === location.executionHostId && + host.readStatusSummary(record.sessionId)?.status === 'working' + ) + }, + logger: deps.logger, + now: () => deps.now?.() ?? Date.now() + }) + hostCheckpoints.set(host, checkpoints) + } + return checkpoints +} diff --git a/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts index 504a6dea526..cad0e2fc7b6 100644 --- a/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts +++ b/src/main/native-chat/agent-session-wire/checkpoints/agent-session-checkpoints.ts @@ -28,8 +28,7 @@ import { } from '../../../git/checkpoints/worktree-checkpoint-restore' import { pruneCheckpointRefs } from '../../../git/checkpoints/worktree-checkpoint-retention' import type { StructuredAgentSessionLogger } from '../host/structured-agent-session-logger' -import type { StructuredAgentSessionDeliveryLoopDeps } from '../delivery/structured-agent-session-delivery-loop-deps' -import type { StructuredAgentSessionHostDeps } from '../host/structured-agent-session-host-types' +import { markTurnStarting, serialize, startingTurns } from './agent-session-checkpoint-queue' export const TURN_CHECKPOINTS_KEPT = 50 export const UNDO_CHECKPOINTS_KEPT = 10 @@ -68,16 +67,8 @@ function refuse(reason: Parameters[ throw new Error(agentSessionCheckpointRefusalMessage(reason)) } -// One git writer per worktree at a time across every chat in this process: a capture never -// interleaves with a restore, so a send after a rewind snapshots the restored files. -const queues = new Map>() -function serialize(root: string, task: () => Promise): Promise { - const run = (queues.get(root) ?? Promise.resolve()).then(task, task) - const tail = run.catch(() => undefined) - queues.set(root, tail) - void tail.then(() => queues.get(root) === tail && queues.delete(root)) - return run -} +/** Something else in the workspace that may write files: a terminal agent, say. */ +export type AgentSessionWorkspaceBusy = () => Promise export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) { const open = deps.openRepo ?? ((directory: string) => openCheckpointRepo(directory)) @@ -96,18 +87,24 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) sessionId: string, itemId: string, signal?: AbortSignal - ): Promise => { + ): Promise<() => void> => { const started = deps.now() + let release = () => {} try { const repo = await repoFor(sessionId) if (!repo) { - return + return release } + release = markTurnStarting(repo.root) await serialize(repo.root, async () => { await captureWorktreeCheckpoint( repo, turnRef(sessionId, itemId), - { kind: 'turn', createdAt: deps.now(), labels: { sessionId, itemId } }, + { + kind: 'turn', + createdAt: deps.now(), + labels: { sessionId, itemId } + }, { signal, timeoutMs: CHECKPOINT_CAPTURE_TIMEOUT_MS } ) await pruneCheckpointRefs(repo, { @@ -119,22 +116,25 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) }) }) } catch (error) { - if (error instanceof WorktreeCheckpointError && error.reason === 'not-a-repo') { - return + if (!(error instanceof WorktreeCheckpointError && error.reason === 'not-a-repo')) { + deps.logger.warn('[agent-session] turn checkpoint skipped', { + scope: 'checkpoint-capture', + sessionId, + elapsedMs: deps.now() - started, + error: error instanceof Error ? error.message : String(error) + }) } - deps.logger.warn('[agent-session] turn checkpoint skipped', { - scope: 'checkpoint-capture', - sessionId, - elapsedMs: deps.now() - started, - error: error instanceof Error ? error.message : String(error) - }) } + return release } const target = async ( sessionId: string, ref: string - ): Promise<{ repo: CheckpointRepo; checkpoint: WorktreeCheckpoint } | null> => { + ): Promise<{ + repo: CheckpointRepo + checkpoint: WorktreeCheckpoint + } | null> => { const repo = await repoFor(sessionId) const checkpoint = repo ? await readWorktreeCheckpoint(repo, ref) : null return repo && checkpoint ? { repo, checkpoint } : null @@ -142,7 +142,8 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) const preview = async ( sessionId: string, - itemId: string + itemId: string, + workspaceBusy?: AgentSessionWorkspaceBusy ): Promise => { try { const found = await target(sessionId, turnRef(sessionId, itemId)) @@ -156,7 +157,11 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) available: true, changedFiles: changes.length, headMoved, - createdAt: found.checkpoint.createdAt + createdAt: found.checkpoint.createdAt, + busy: + deps.isBusy(sessionId) || + (startingTurns.get(found.repo.root) ?? 0) > 0 || + ((await workspaceBusy?.().catch(() => false)) ?? false) } } catch (error) { if (error instanceof WorktreeCheckpointError && error.reason === 'not-a-repo') { @@ -173,7 +178,8 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) const restoreRef = async ( sessionId: string, - ref: string + ref: string, + workspaceBusy?: AgentSessionWorkspaceBusy ): Promise => { const repo = await repoFor(sessionId).catch((error: unknown) => { if (error instanceof WorktreeCheckpointError && error.reason === 'not-a-repo') { @@ -191,7 +197,11 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) // Look up and check busy inside the queue: a capture queued first runs first, and the turn // it starts must make this restore refuse rather than rewrite files under a working agent. const result = await serialize(repo.root, async () => { - if (deps.isBusy(sessionId)) { + if ( + deps.isBusy(sessionId) || + (startingTurns.get(repo.root) ?? 0) > 0 || + (await workspaceBusy?.()) + ) { refuse('busy') } const checkpoint = await readWorktreeCheckpoint(repo, ref) @@ -211,7 +221,11 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) now, protect: [undoRef] }).catch(() => undefined) - return { changedFiles: result.changes.length, headMoved: result.headMoved, undoId } + return { + changedFiles: result.changes.length, + headMoved: result.headMoved, + undoId + } } catch (error) { if (error instanceof WorktreeCheckpointError && error.reason === 'partial') { throw new Error(agentSessionCheckpointPartialMessage(undoId)) @@ -231,65 +245,13 @@ export function createAgentSessionCheckpoints(deps: AgentSessionCheckpointsDeps) return { captureTurn, preview, - restore: (sessionId: string, itemId: string) => - restoreRef(sessionId, turnRef(sessionId, itemId)), - undo: async (sessionId: string, undoId: string) => { + restore: (sessionId: string, itemId: string, workspaceBusy?: AgentSessionWorkspaceBusy) => + restoreRef(sessionId, turnRef(sessionId, itemId), workspaceBusy), + undo: async (sessionId: string, undoId: string, workspaceBusy?: AgentSessionWorkspaceBusy) => { if (!AGENT_SESSION_CHECKPOINT_UNDO_ID.test(undoId)) { refuse('none') } - return restoreRef(sessionId, `${sessionPrefix(sessionId)}undo/${undoId}`) + return restoreRef(sessionId, `${sessionPrefix(sessionId)}undo/${undoId}`, workspaceBusy) } } } - -/** The snapshot a send takes before its message opens a turn; never throws. */ -export function structuredAgentSessionTurnCheckpoint( - deps: Pick< - StructuredAgentSessionDeliveryLoopDeps, - 'record' | 'resolveWorkspacePath' | 'logger' | 'now' - >, - sessionId: string -): (itemId: string, signal?: AbortSignal) => Promise { - const { captureTurn } = createAgentSessionCheckpoints({ - record: deps.record, - ...(deps.resolveWorkspacePath ? { resolveWorkspacePath: deps.resolveWorkspacePath } : {}), - isBusy: () => false, - logger: deps.logger, - now: deps.now - }) - return (itemId, signal) => captureTurn(sessionId, itemId, signal) -} - -type CheckpointHost = { - deps: Pick - readStatusSummary: (sessionId: string) => { status: string | null } | undefined -} -const hostCheckpoints = new WeakMap() - -/** Preview, restore and undo for a host's chats; a restore waits for a running turn to end. */ -export function hostAgentSessionCheckpoints(host: CheckpointHost): AgentSessionCheckpoints { - let checkpoints = hostCheckpoints.get(host) - if (!checkpoints) { - const { deps } = host - checkpoints = createAgentSessionCheckpoints({ - record: (sessionId) => deps.store.getRecord(sessionId), - ...(deps.resolveWorkspacePath ? { resolveWorkspacePath: deps.resolveWorkspacePath } : {}), - // Any chat working in the same worktree could be writing the files a restore rewrites. - isBusy: (sessionId) => { - const location = deps.store.getRecord(sessionId)?.location - return deps.store - .listConversations() - .some( - (record) => - record.location.workspaceId === location?.workspaceId && - record.location.executionHostId === location.executionHostId && - host.readStatusSummary(record.sessionId)?.status === 'working' - ) - }, - logger: deps.logger, - now: () => deps.now?.() ?? Date.now() - }) - hostCheckpoints.set(host, checkpoints) - } - return checkpoints -} diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-handover.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-handover.ts index 6f29b81ca25..7ede759ffff 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-handover.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-handover.ts @@ -113,13 +113,17 @@ export async function beginSubmissionHandover( } // Preserve handover time so turn-open cannot re-anchor elapsed work. const requestedAt = structuredAgentSessionHandoverOrigin(ctx.journal, submission) + let releaseCheckpoint: (() => void) | undefined return { run: async (commit) => { try { // A message that opens a turn gets a file checkpoint first, taken before the agent can // write; one that joins a running turn would snapshot the agent mid-edit, so it gets none. if (turnScope.kind === 'thread' && ctx.captureTurnCheckpoint && !attempt?.signal.aborted) { - await ctx.captureTurnCheckpoint(agentJournalSubmissionKey(clientMessageId), attempt?.signal) + releaseCheckpoint = await ctx.captureTurnCheckpoint( + agentJournalSubmissionKey(clientMessageId), + attempt?.signal + ) } let outcome: AgentSessionDispatchOutcome | null try { @@ -221,6 +225,7 @@ export async function beginSubmissionHandover( } }) } finally { + releaseCheckpoint?.() release?.() released() } diff --git a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-input-handover.ts b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-input-handover.ts index 4e4ba3eea4e..faea4b45888 100644 --- a/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-input-handover.ts +++ b/src/main/native-chat/agent-session-wire/delivery/structured-agent-session-input-handover.ts @@ -25,7 +25,7 @@ import { import { structuredAgentSessionEndedChildFailure } from '../termination/structured-agent-session-ended-child-failure' import { sameProviderChild } from '../host/structured-agent-session-provider-child' import { previousExitUnverifiableRefusal } from '../termination/structured-agent-session-child-close' -import { structuredAgentSessionTurnCheckpoint } from '../checkpoints/agent-session-checkpoints' +import { structuredAgentSessionTurnCheckpoint } from '../checkpoints/agent-session-checkpoints-host' type StartFailure = NonNullable> diff --git a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts index 60de1879140..db882e765d6 100644 --- a/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts +++ b/src/main/native-chat/agent-session-wire/host/structured-agent-session-host-types.ts @@ -281,7 +281,8 @@ export type AgentSessionHandoverContext = StructuredAgentSessionCommandHandoverC /** A message the agent took: a chat keeps, where it has none saved, the options it ran. */ recordRanOptions?: ReturnType /** Snapshots the worktree before this message opens a turn; never throws. */ - captureTurnCheckpoint?: (itemId: string, signal?: AbortSignal) => Promise + /** Resolves to a release, called once the message has been handed to the agent. */ + captureTurnCheckpoint?: (itemId: string, signal?: AbortSignal) => Promise<() => void> } export type StructuredAgentSessionConversationLifetime = ReturnType< diff --git a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts index e72995e72c6..d721b694605 100644 --- a/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts +++ b/src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-rewind-files.test.ts @@ -13,7 +13,9 @@ import type { AgentSessionRecordStore } from '../../../../runtime/agent-session/ import { openTestAgentSessionRecordStore } from '../../../../runtime/agent-session/records/agent-session-record-store-test-harness' import { StructuredAgentSessionHost } from '../structured-agent-session-host' import type { AgentSessionDispatchOutcome } from '../../providers/structured-agent-session-adapter' -import { hostAgentSessionCheckpoints } from '../../checkpoints/agent-session-checkpoints' +import { createAgentSessionCheckpoints } from '../../checkpoints/agent-session-checkpoints' +import { hostAgentSessionCheckpoints } from '../../checkpoints/agent-session-checkpoints-host' +import type { AgentSessionRecord } from '../../../../../shared/agent-session/lifecycle/agent-session-record' import { HOST_TEST_NOW, HOST_TEST_SESSION, @@ -199,15 +201,47 @@ describe('rewind with file restore', () => { it('has no checkpoint for unknown messages and refuses a bad undo id', async () => { const attached = await host.attach(caller, hostTestAttachParams(null)) expect(attached, JSON.stringify(attached)).toMatchObject({ ok: true }) - expect(await hostAgentSessionCheckpoints(host).preview(HOST_TEST_SESSION, 'orca:nope')).toEqual({ - available: false, - reason: 'none' - }) - await expect(hostAgentSessionCheckpoints(host).restore(HOST_TEST_SESSION, 'orca:nope')).rejects.toThrow( - 'agent_session_checkpoint_none' - ) - await expect(hostAgentSessionCheckpoints(host).undo(HOST_TEST_SESSION, '../../heads/main')).rejects.toThrow( - 'agent_session_checkpoint_none' + expect(await hostAgentSessionCheckpoints(host).preview(HOST_TEST_SESSION, 'orca:nope')).toEqual( + { + available: false, + reason: 'none' + } ) + await expect( + hostAgentSessionCheckpoints(host).restore(HOST_TEST_SESSION, 'orca:nope') + ).rejects.toThrow('agent_session_checkpoint_none') + await expect( + hostAgentSessionCheckpoints(host).undo(HOST_TEST_SESSION, '../../heads/main') + ).rejects.toThrow('agent_session_checkpoint_none') + }) +}) + +describe('restore admission', () => { + it('refuses while a turn is between its snapshot and its hand-off, or the workspace is busy', async () => { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the checkpoints read only location and launchDirectory. + const record = { + sessionId: 's', + location: { workspaceId: 'w', wslDistro: null }, + launchDirectory: worktree + } as unknown as AgentSessionRecord + const checkpoints = createAgentSessionCheckpoints({ + record: () => record, + isBusy: () => false, + logger: createStructuredAgentSessionLogger(), + now: () => HOST_TEST_NOW + }) + const release = await checkpoints.captureTurn('s', 'orca:one') + await put('app.ts', 'agent\n') + await expect(checkpoints.restore('s', 'orca:one')).rejects.toThrow( + 'agent_session_checkpoint_busy' + ) + expect(await checkpoints.preview('s', 'orca:one')).toMatchObject({ busy: true }) + release() + await expect(checkpoints.restore('s', 'orca:one', async () => true)).rejects.toThrow( + 'agent_session_checkpoint_busy' + ) + expect(await read('app.ts')).toBe('agent\n') + await checkpoints.restore('s', 'orca:one', async () => false) + expect(await read('app.ts')).toBe('v0\n') }) }) diff --git a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-checkpoint-methods.ts b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-checkpoint-methods.ts index d5cd6043f83..41fbae08b85 100644 --- a/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-checkpoint-methods.ts +++ b/src/main/runtime/rpc/methods/structured-sessions/conversation/structured-agent-session-checkpoint-methods.ts @@ -3,32 +3,49 @@ import { defineMethod } from '../../../core' import { requireInstalledStructuredHost } from '../creation/structured-agent-session-gate' -import { hostAgentSessionCheckpoints } from '../../../../../native-chat/agent-session-wire/checkpoints/agent-session-checkpoints' +import type { AgentSessionWorkspaceBusy } from '../../../../../native-chat/agent-session-wire/checkpoints/agent-session-checkpoints' +import { hostAgentSessionCheckpoints } from '../../../../../native-chat/agent-session-wire/checkpoints/agent-session-checkpoints-host' +import { getStructuredAgentSessionHost } from '../../../../../native-chat/agent-session-wire/host/structured-agent-session-registry' +import type { RpcContext } from '../../../core' import { CheckpointItemParams, CheckpointUndoParams } from '../../../../../../shared/rpc-contract/structured-agent-session-checkpoint-params' +/** Any agent working in the chat's workspace (terminal agents included) may be writing files. */ +function terminalAgentsWorking(ctx: RpcContext, sessionId: string): AgentSessionWorkspaceBusy { + return async () => { + const workspaceId = + getStructuredAgentSessionHost()?.deps.store.getRecord(sessionId)?.location.workspaceId + if (!workspaceId) { + return false + } + const ps = await ctx.runtime.getWorktreePs(10_000) + return ps.worktrees.some( + (row) => + row.worktreeId === workspaceId && row.agents.some((agent) => agent.state === 'working') + ) + } +} + export const STRUCTURED_AGENT_SESSION_CHECKPOINT_METHODS = [ defineMethod({ name: 'agentSession.checkpointPreview', permission: 'workspace', params: CheckpointItemParams, handler: async (params, ctx) => - hostAgentSessionCheckpoints(await requireInstalledStructuredHost(ctx, params.sessionId)).preview( - params.sessionId, - params.itemId - ) + hostAgentSessionCheckpoints( + await requireInstalledStructuredHost(ctx, params.sessionId) + ).preview(params.sessionId, params.itemId, terminalAgentsWorking(ctx, params.sessionId)) }), defineMethod({ name: 'agentSession.checkpointRestore', permission: 'workspace', params: CheckpointItemParams, handler: async (params, ctx) => - hostAgentSessionCheckpoints(await requireInstalledStructuredHost(ctx, params.sessionId)).restore( - params.sessionId, - params.itemId - ) + hostAgentSessionCheckpoints( + await requireInstalledStructuredHost(ctx, params.sessionId) + ).restore(params.sessionId, params.itemId, terminalAgentsWorking(ctx, params.sessionId)) }), defineMethod({ name: 'agentSession.checkpointUndo', @@ -37,7 +54,8 @@ export const STRUCTURED_AGENT_SESSION_CHECKPOINT_METHODS = [ handler: async (params, ctx) => hostAgentSessionCheckpoints(await requireInstalledStructuredHost(ctx, params.sessionId)).undo( params.sessionId, - params.undoId + params.undoId, + terminalAgentsWorking(ctx, params.sessionId) ) }) ] diff --git a/src/renderer/src/components/confirmation-dialog-context.ts b/src/renderer/src/components/confirmation-dialog-context.ts index ad85321e955..23b2fa8c206 100644 --- a/src/renderer/src/components/confirmation-dialog-context.ts +++ b/src/renderer/src/components/confirmation-dialog-context.ts @@ -34,8 +34,11 @@ export type ConfirmationDialogOptions = { * `onConfirmed` gets the box's state, only on confirm. */ option?: { label: string + /** Describes the outcome while checked (or always, without `uncheckedDetail`). */ detail?: string + uncheckedDetail?: string defaultChecked: boolean + disabled?: boolean onConfirmed: (checked: boolean) => void } /** Runs when the cancel button settles the prompt, unlike Esc, an outside press or an abort. */ diff --git a/src/renderer/src/components/confirmation-dialog-option.tsx b/src/renderer/src/components/confirmation-dialog-option.tsx new file mode 100644 index 00000000000..ba7f88df470 --- /dev/null +++ b/src/renderer/src/components/confirmation-dialog-option.tsx @@ -0,0 +1,43 @@ +import React from 'react' +import { Checkbox } from '@/components/ui/checkbox' +import { Label } from '@/components/ui/label' +import type { ConfirmationDialogOptions } from '@/components/confirmation-dialog-context' + +/** A confirmation's optional part: sits in the body, right under the description, because it + * changes what the confirm button does. The line under it says what the current state means. */ +export function ConfirmationDialogOption({ + option, + checked, + onCheckedChange +}: { + option: NonNullable + checked: boolean + onCheckedChange: (checked: boolean) => void +}): React.JSX.Element { + const detail = + checked || option.uncheckedDetail === undefined ? option.detail : option.uncheckedDetail + return ( +
+ onCheckedChange(value === true)} + aria-describedby={detail ? 'confirmation-dialog-option-detail' : undefined} + /> +
+ + {detail ? ( +

+ {detail} +

+ ) : null} +
+
+ ) +} diff --git a/src/renderer/src/components/confirmation-dialog.test.tsx b/src/renderer/src/components/confirmation-dialog.test.tsx index 78c6a3c5bc2..10b9d775ac5 100644 --- a/src/renderer/src/components/confirmation-dialog.test.tsx +++ b/src/renderer/src/components/confirmation-dialog.test.tsx @@ -109,18 +109,21 @@ describe('ConfirmationDialogProvider', () => { title: 'Rewind to here?', confirmLabel: 'Rewind', option: { - label: 'Also restore files (3 changed)', - detail: 'Changes made after it are discarded.', + label: 'Also restore 3 changed files', + detail: 'Later changes are discarded.', + uncheckedDetail: 'Files on disk stay as they are.', defaultChecked: true, onConfirmed } }) await userEvent.click(screen.getByRole('button', { name: 'ask' })) - const box = await screen.findByRole('checkbox', { name: 'Also restore files (3 changed)' }) + const box = await screen.findByRole('checkbox', { name: 'Also restore 3 changed files' }) expect(box.getAttribute('aria-checked')).toBe('true') expect(box.getAttribute('aria-describedby')).toBe('confirmation-dialog-option-detail') + expect(screen.getByText('Later changes are discarded.')).toBeTruthy() await userEvent.click(box) + expect(screen.getByText('Files on disk stay as they are.')).toBeTruthy() await userEvent.click(screen.getByRole('button', { name: 'Rewind' })) expect(onConfirmed).toHaveBeenCalledWith(false) diff --git a/src/renderer/src/components/confirmation-dialog.tsx b/src/renderer/src/components/confirmation-dialog.tsx index f59393dd73f..50b1afdf244 100644 --- a/src/renderer/src/components/confirmation-dialog.tsx +++ b/src/renderer/src/components/confirmation-dialog.tsx @@ -20,6 +20,7 @@ import { import { useAppStore } from '@/store' import { useTranslate } from '@/i18n/use-translate' import { cn } from '@/lib/utils' +import { ConfirmationDialogOption } from '@/components/confirmation-dialog-option' type ConfirmationDialogRequest = { id: number @@ -185,6 +186,13 @@ export function ConfirmationDialogProvider({ ) : null} + {displayedRequest?.options.option ? ( + + ) : null} {displayedRequest?.options.fields ? (
{displayedRequest.options.fields.inputs.map((field) => ( @@ -212,34 +220,6 @@ export function ConfirmationDialogProvider({ ))}
) : null} - {displayedRequest?.options.option ? ( -
- setOptionChecked(checked === true)} - aria-describedby={ - displayedRequest.options.option.detail - ? 'confirmation-dialog-option-detail' - : undefined - } - /> -
- - {displayedRequest.options.option.detail ? ( -

- {displayedRequest.options.option.detail} -

- ) : null} -
-
- ) : null} {displayedRequest?.options.dontAskAgain ? (
{ + void confirm({ + title: 'Rewind to here?', + ...nativeChatRewindPrompt(preview, () => {}), + confirmLabel: 'Rewind', + cancelLabel: 'Cancel', + confirmVariant: 'destructive', + cancelVariant: 'ghost' + }) + }, [confirm, preview]) + return null +} + +function prompt(preview: AgentSessionCheckpointPreview | null) { + return defineFixture({ + width: 560, + render: () => ( +
+ + + +
+ ) + }) +} + +/** A: a snapshot exists and files differ. */ +export const restoreFiles = prompt({ + available: true, + changedFiles: 3, + headMoved: true, + createdAt: 0 +}) +/** A, one file: the singular label. */ +export const restoreOneFile = prompt({ + available: true, + changedFiles: 1, + headMoved: false, + createdAt: 0 +}) +/** A while an agent works in the workspace: the choice is off and says why. */ +export const restoreBusy = prompt({ + available: true, + changedFiles: 3, + headMoved: false, + createdAt: 0, + busy: true +}) +/** B: files already match the message. */ +export const filesMatch = prompt({ + available: true, + changedFiles: 0, + headMoved: false, + createdAt: 0 +}) +/** C: no snapshot (older message, older host, or not git). */ +export const noSnapshot = prompt({ available: false, reason: 'none' }) diff --git a/src/renderer/src/components/native-chat/messages/actions/native-chat-rewind-files.ts b/src/renderer/src/components/native-chat/messages/actions/native-chat-rewind-files.ts index 23e70e5eccb..8bf6b239eac 100644 --- a/src/renderer/src/components/native-chat/messages/actions/native-chat-rewind-files.ts +++ b/src/renderer/src/components/native-chat/messages/actions/native-chat-rewind-files.ts @@ -43,22 +43,22 @@ export async function previewNativeChatRewindFiles( const BASE = () => translate( - 'components.native-chat.rewind.confirmationBase', - 'Discard this message and everything after it? The message returns to the composer so you can edit and resend it.' + 'components.native-chat.rewind.removedDescription', + 'This message and everything after it are removed from the chat. The message goes back to the composer so you can edit and resend it.' ) function filesLabel(count: number): string { return translate( - 'components.native-chat.rewind.restoreFiles', - 'Also restore files ({{files}} changed)', - { files: count } + 'components.native-chat.rewind.restoreChangedFiles', + 'Also restore {{count}} changed files', + { count, defaultValue_one: 'Also restore {{count}} changed file' } ) } -function filesDetail(headMoved: boolean): string { +function checkedDetail(headMoved: boolean): string { const detail = translate( - 'components.native-chat.rewind.restoreFilesDetail', - 'Files go back to how they were when this message was sent. Changes made after it are discarded. You can undo this.' + 'components.native-chat.rewind.restoreFilesOutcome', + 'Files go back to how they were when this message was sent. Later changes are discarded. You can undo the file restore afterwards.' ) return headMoved ? `${detail} ${translate( @@ -74,13 +74,26 @@ export function nativeChatRewindPrompt( choose: (restoreFiles: boolean) => void ): Pick { if (preview?.available && preview.changedFiles > 0) { + const busy = preview.busy === true return { description: BASE(), option: { label: filesLabel(preview.changedFiles), - detail: filesDetail(preview.headMoved), - defaultChecked: true, - onConfirmed: choose + detail: busy + ? translate( + 'components.native-chat.rewind.restoreFilesBusy', + "Files can't be restored while the agent is working." + ) + : checkedDetail(preview.headMoved), + uncheckedDetail: busy + ? undefined + : translate( + 'components.native-chat.rewind.keepFilesOutcome', + 'Files on disk stay as they are.' + ), + defaultChecked: !busy, + disabled: busy, + onConfirmed: (checked) => choose(checked && !busy) } } } @@ -101,8 +114,9 @@ export function nativeChatRewindPrompt( } function restoredText(count: number): string { - return translate('components.native-chat.rewind.restored', 'Files restored ({{files}} changed)', { - files: count + return translate('components.native-chat.rewind.restoredFiles', 'Restored {{count}} files', { + count, + defaultValue_one: 'Restored {{count}} file' }) } @@ -110,35 +124,31 @@ function failureText(error: unknown): string { switch (agentSessionCheckpointRefusalOf(error)) { case 'busy': return translate( - 'components.native-chat.rewind.restoreBusy', - "Files weren't restored because the agent is still working. Nothing on disk changed." + 'components.native-chat.rewind.chatRewoundBusy', + "The chat was rewound, but files weren't restored because the agent is still working. Nothing on disk changed." ) case 'merge-conflicts': return translate( - 'components.native-chat.rewind.restoreConflicts', - "Files weren't restored because this worktree has unresolved merge conflicts. Nothing on disk changed." + 'components.native-chat.rewind.chatRewoundConflicts', + "The chat was rewound, but files weren't restored because this workspace has unresolved merge conflicts. Nothing on disk changed." ) case 'blocked-path': return translate( - 'components.native-chat.rewind.restoreBlocked', - "Files weren't restored because a folder now sits where a restored file goes. Nothing on disk changed." + 'components.native-chat.rewind.chatRewoundBlocked', + "The chat was rewound, but files weren't restored because a folder now sits where a restored file goes. Nothing on disk changed." ) case 'none': return translate( - 'components.native-chat.rewind.restoreMissing', - "Files weren't restored because the snapshot for this message is gone. Nothing on disk changed." + 'components.native-chat.rewind.chatRewoundMissing', + "The chat was rewound, but files weren't restored because Orca no longer has the files saved for this message. Nothing on disk changed." ) case 'partial': - return translate( - 'components.native-chat.rewind.restorePartial', - "Orca couldn't restore every file. Undo puts back the files it changed." - ) case 'not-a-repo': case 'unsafe-path': case null: return translate( - 'components.native-chat.rewind.restoreFailed', - "Orca couldn't restore every file. Check the worktree before continuing." + 'components.native-chat.rewind.chatRewoundFailed', + "The chat was rewound, but some files couldn't be restored. Check Source Control before you continue." ) } } @@ -160,7 +170,9 @@ export async function restoreNativeChatRewindFiles( ) return } - toast.success(restoredText(result.changedFiles), { action: undoAction(client, result.undoId) }) + toast.success(restoredText(result.changedFiles), { + action: undoAction(client, result.undoId) + }) } function undoAction(client: NativeChatCheckpointClient, undoId: string) { diff --git a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind-files.test.tsx b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind-files.test.tsx index c1a027e61b9..2298a70a03a 100644 --- a/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind-files.test.tsx +++ b/src/renderer/src/components/native-chat/messages/actions/use-native-chat-rewind-files.test.tsx @@ -84,10 +84,11 @@ describe('rewind with file restore', () => { await act(() => view.result.current.request('user', answer('default', shown))) expect(checkpoints.preview).toHaveBeenCalledWith('user') expect(shown[0]?.option).toMatchObject({ - label: 'Also restore files (3 changed)', + label: 'Also restore 3 changed files', defaultChecked: true }) - expect(shown[0]?.option?.detail).toContain('Changes made after it are discarded') + expect(shown[0]?.option?.detail).toContain('Later changes are discarded') + expect(shown[0]?.option?.uncheckedDetail).toBe('Files on disk stay as they are.') expect(shown[0]?.option?.detail).toContain('Commits made since then stay on the branch') expect(shown[0]?.description).not.toContain('File changes on disk are kept') await vi.waitFor(() => expect(checkpoints.restore).toHaveBeenCalledWith('user')) @@ -95,13 +96,33 @@ describe('rewind with file restore', () => { checkpoints.restore.mock.invocationCallOrder[0]! ) await vi.waitFor(() => expect(toast.success).toHaveBeenCalled()) - expect(toast.success.mock.calls[0]?.[0]).toBe('Files restored (3 changed)') + expect(toast.success.mock.calls[0]?.[0]).toBe('Restored 3 files') const undo = toast.success.mock.calls[0]?.[1]?.action expect(undo.label).toBe('Undo') undo.onClick() await vi.waitFor(() => expect(checkpoints.undo).toHaveBeenCalledWith('1-abcdef01')) }) + it('disables restoring while an agent works in the workspace, and never restores then', async () => { + const checkpoints = client({ + available: true, + changedFiles: 2, + headMoved: false, + createdAt: 1, + busy: true + }) + const shown: ConfirmationDialogOptions[] = [] + const view = renderHook(() => useNativeChatRewind(input(checkpoints))) + await act(() => view.result.current.request('user', answer(true, shown))) + expect(shown[0]?.option).toMatchObject({ + disabled: true, + defaultChecked: false, + detail: "Files can't be restored while the agent is working." + }) + await act(async () => {}) + expect(checkpoints.restore).not.toHaveBeenCalled() + }) + it('keeps files when the box is unticked', async () => { const checkpoints = client({ available: true, changedFiles: 2, headMoved: false, createdAt: 1 }) const view = renderHook(() => useNativeChatRewind(input(checkpoints))) @@ -150,6 +171,7 @@ describe('rewind with file restore', () => { const view = renderHook(() => useNativeChatRewind(input(checkpoints))) await act(() => view.result.current.request('user', answer(true, []))) await vi.waitFor(() => expect(toast.error).toHaveBeenCalled()) + expect(toast.error.mock.calls[0]?.[0]).toContain('The chat was rewound, but') expect(toast.error.mock.calls[0]?.[0]).toContain('unresolved merge conflicts') expect(toast.success).not.toHaveBeenCalled() }) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index 923e688ad7a..b08d0a8a935 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -2040,6 +2040,12 @@ "waitForStart": "Wait for the agent to finish starting.", "waitForTurn": "Wait for the agent to finish responding, or stop it.", "waitMoment": "Wait a moment." + }, + "rewind": { + "restoreChangedFiles_one": "Also restore {{count}} changed file", + "restoreChangedFiles_other": "Also restore {{count}} changed files", + "restoredFiles_one": "Restored {{count}} file", + "restoredFiles_other": "Restored {{count}} files" } }, "onboarding": { diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index 97823e56b22..276b466e0ca 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -21853,20 +21853,23 @@ "confirm": "Rewind", "cancel": "Cancel", "action": "Rewind to here", - "confirmationBase": "Discard this message and everything after it? The message returns to the composer so you can edit and resend it.", - "restoreFiles": "Also restore files ({{files}} changed)", - "restoreFilesDetail": "Files go back to how they were when this message was sent. Changes made after it are discarded. You can undo this.", "restoreFilesCommitsStay": "Commits made since then stay on the branch.", "filesAlreadyMatch": "Files on disk already match this message.", - "restored": "Files restored ({{files}} changed)", - "restoreBusy": "Files weren't restored because the agent is still working. Nothing on disk changed.", - "restoreConflicts": "Files weren't restored because this worktree has unresolved merge conflicts. Nothing on disk changed.", - "restoreBlocked": "Files weren't restored because a folder now sits where a restored file goes. Nothing on disk changed.", - "restoreMissing": "Files weren't restored because the snapshot for this message is gone. Nothing on disk changed.", - "restoreFailed": "Orca couldn't restore every file. Check the worktree before continuing.", - "restorePartial": "Orca couldn't restore every file. Undo puts back the files it changed.", "undoRestore": "Undo", - "undoneRestore": "Files are back to how they were before the rewind." + "undoneRestore": "Files are back to how they were before the rewind.", + "removedDescription": "This message and everything after it are removed from the chat. The message goes back to the composer so you can edit and resend it.", + "restoreChangedFiles_one": "Also restore {{count}} changed file", + "restoreChangedFiles_other": "Also restore {{count}} changed files", + "restoreFilesOutcome": "Files go back to how they were when this message was sent. Later changes are discarded. You can undo the file restore afterwards.", + "restoreFilesBusy": "Files can't be restored while the agent is working.", + "keepFilesOutcome": "Files on disk stay as they are.", + "restoredFiles_one": "Restored {{count}} file", + "restoredFiles_other": "Restored {{count}} files", + "chatRewoundBusy": "The chat was rewound, but files weren't restored because the agent is still working. Nothing on disk changed.", + "chatRewoundConflicts": "The chat was rewound, but files weren't restored because this workspace has unresolved merge conflicts. Nothing on disk changed.", + "chatRewoundBlocked": "The chat was rewound, but files weren't restored because a folder now sits where a restored file goes. Nothing on disk changed.", + "chatRewoundMissing": "The chat was rewound, but files weren't restored because Orca no longer has the files saved for this message. Nothing on disk changed.", + "chatRewoundFailed": "The chat was rewound, but some files couldn't be restored. Check Source Control before you continue." }, "drop": { "messageTitle": "Drop to attach to this message", diff --git a/src/shared/agent-session/lifecycle/agent-session-checkpoint.ts b/src/shared/agent-session/lifecycle/agent-session-checkpoint.ts index 8ff5a4370bc..27b9f3dce33 100644 --- a/src/shared/agent-session/lifecycle/agent-session-checkpoint.ts +++ b/src/shared/agent-session/lifecycle/agent-session-checkpoint.ts @@ -18,6 +18,8 @@ export type AgentSessionCheckpointPreview = /** Commits were made after the snapshot; they stay on the branch. */ headMoved: boolean createdAt: number + /** An agent is working in this workspace now, so a restore would refuse. */ + busy?: boolean } export type AgentSessionCheckpointRestoreResult = { diff --git a/tests/e2e/native-chat-rewind-restore-files.live.spec.ts b/tests/e2e/native-chat-rewind-restore-files.live.spec.ts index 21c66b2974c..baa0bede6c3 100644 --- a/tests/e2e/native-chat-rewind-restore-files.live.spec.ts +++ b/tests/e2e/native-chat-rewind-restore-files.live.spec.ts @@ -86,7 +86,9 @@ test.describe('rewind with file restore, live agent', () => { const call = async (method: string, params: unknown, timeoutMs = 60_000): Promise => (await host.client.call(method, params, { timeoutMs })).result try { - const added = await call<{ repo: { id: string } }>('repo.add', { path: worktree }) + const added = await call<{ repo: { id: string } }>('repo.add', { + path: worktree + }) let worktreeId = '' await expect .poll(async () => { @@ -115,7 +117,9 @@ test.describe('rewind with file restore, live agent', () => { }) let fence = 0 await expect - .poll(async () => (fence = (await tail()).page.fence ?? 0), { timeout: 120_000 }) + .poll(async () => (fence = (await tail()).page.fence ?? 0), { + timeout: 120_000 + }) .toBeGreaterThan(0) const send = async (prompt: string): Promise => { const clientOperationId = createStructuredAgentSessionOperationId(randomUUID) @@ -153,7 +157,9 @@ test.describe('rewind with file restore, live agent', () => { quietPolls = newest === lastSequence ? quietPolls + 1 : 0 lastSequence = newest if (!replied) { - const submission = page.submissions.find((entry) => entry.clientMessageId === clientOperationId) + const submission = page.submissions.find( + (entry) => entry.clientMessageId === clientOperationId + ) console.log( `[rewind-files live] waiting: dispatch=${submission?.dispatchState} refs=${git(worktree, 'for-each-ref', '--format=%(refname)', 'refs/orca/').split('\n').length} last=${JSON.stringify(page.items.at(-1)?.body).slice(0, 120)}` ) @@ -179,9 +185,9 @@ test.describe('rewind with file restore, live agent', () => { expect(git(worktree, 'diff', '--cached', '--name-only')).toBe('staged.txt') expect(git(worktree, 'stash', 'list')).toBe('') const refs = git(worktree, 'for-each-ref', '--format=%(refname)', 'refs/orca/checkpoints/') - expect(refs.split('\n').filter((ref) => ref.includes('/turn/')).length).toBeGreaterThanOrEqual( - 2 - ) + expect( + refs.split('\n').filter((ref) => ref.includes('/turn/')).length + ).toBeGreaterThanOrEqual(2) // Rewind the chat to the second message (as the UI does), then restore its files. const itemId = agentJournalSubmissionKey(second)