mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 19:07:41 +00:00
fix(checkpoints): nested repos, undo coverage, workspace-wide busy; W10 copy
- Refuse a restore that would write or delete inside a nested repository, and verify every on-disk path it touches is in the undo tree first (git add can skip a path without failing). - A turn counts as busy from its snapshot until the hand-off; terminal agents working in the workspace make restores refuse; the preview reports busy and the dialog disables the files choice. - W10 copy: statement description, i18n plurals, state-dependent detail line, option directly under the description, 'The chat was rewound, but…' errors. - Index restore keeps skip-worktree bits; large-file scan honours the deadline. - Component fixture for the rewind prompt states.
This commit is contained in:
@@ -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,
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
|
||||
@@ -71,6 +71,19 @@ export function overwrittenUnsnapshottedPaths(repo: CheckpointRepo, target: Work
|
||||
}
|
||||
}
|
||||
|
||||
async function hasGitDir(
|
||||
repo: CheckpointRepo,
|
||||
folder: string,
|
||||
cache: Map<string, boolean>
|
||||
): Promise<boolean> {
|
||||
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<string, boolean>()
|
||||
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<void> {
|
||||
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
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<string>
|
||||
): Promise<void> {
|
||||
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
|
||||
|
||||
@@ -18,7 +18,10 @@ async function listRefs(repo: CheckpointRepo, prefix: string): Promise<RefAge[]>
|
||||
.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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string[]> {
|
||||
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 }
|
||||
|
||||
@@ -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<string, Promise<unknown>>()
|
||||
export function serialize<T>(root: string, task: () => Promise<T>): Promise<T> {
|
||||
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<string, number>()
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<StructuredAgentSessionHostDeps, 'store' | 'resolveWorkspacePath' | 'logger' | 'now'>
|
||||
readStatusSummary: (sessionId: string) => { status: string | null } | undefined
|
||||
}
|
||||
const hostCheckpoints = new WeakMap<CheckpointHost, AgentSessionCheckpoints>()
|
||||
|
||||
/** 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
|
||||
}
|
||||
@@ -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<typeof agentSessionCheckpointRefusalMessage>[
|
||||
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<string, Promise<unknown>>()
|
||||
function serialize<T>(root: string, task: () => Promise<T>): Promise<T> {
|
||||
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<boolean>
|
||||
|
||||
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<void> => {
|
||||
): 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<AgentSessionCheckpointPreview> => {
|
||||
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<AgentSessionCheckpointRestoreResult> => {
|
||||
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<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<StructuredAgentSessionHostDeps, 'store' | 'resolveWorkspacePath' | 'logger' | 'now'>
|
||||
readStatusSummary: (sessionId: string) => { status: string | null } | undefined
|
||||
}
|
||||
const hostCheckpoints = new WeakMap<CheckpointHost, AgentSessionCheckpoints>()
|
||||
|
||||
/** 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
|
||||
}
|
||||
|
||||
+6
-1
@@ -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()
|
||||
}
|
||||
|
||||
+1
-1
@@ -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<ReturnType<typeof startThatFailedWhileQueued>>
|
||||
|
||||
|
||||
@@ -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<StructuredAgentSessionRanRecorder>
|
||||
/** Snapshots the worktree before this message opens a turn; never throws. */
|
||||
captureTurnCheckpoint?: (itemId: string, signal?: AbortSignal) => Promise<void>
|
||||
/** 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<
|
||||
|
||||
+44
-10
@@ -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')
|
||||
})
|
||||
})
|
||||
|
||||
+28
-10
@@ -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)
|
||||
)
|
||||
})
|
||||
]
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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<ConfirmationDialogOptions['option']>
|
||||
checked: boolean
|
||||
onCheckedChange: (checked: boolean) => void
|
||||
}): React.JSX.Element {
|
||||
const detail =
|
||||
checked || option.uncheckedDetail === undefined ? option.detail : option.uncheckedDetail
|
||||
return (
|
||||
<div className="flex items-start gap-2">
|
||||
<Checkbox
|
||||
id="confirmation-dialog-option"
|
||||
className="mt-0.5"
|
||||
checked={checked}
|
||||
disabled={option.disabled}
|
||||
onCheckedChange={(value) => onCheckedChange(value === true)}
|
||||
aria-describedby={detail ? 'confirmation-dialog-option-detail' : undefined}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="confirmation-dialog-option">{option.label}</Label>
|
||||
{detail ? (
|
||||
<p
|
||||
id="confirmation-dialog-option-detail"
|
||||
className="text-xs text-muted-foreground"
|
||||
aria-live="polite"
|
||||
>
|
||||
{detail}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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}
|
||||
</DialogHeader>
|
||||
</div>
|
||||
{displayedRequest?.options.option ? (
|
||||
<ConfirmationDialogOption
|
||||
option={displayedRequest.options.option}
|
||||
checked={optionChecked ?? displayedRequest.options.option.defaultChecked}
|
||||
onCheckedChange={setOptionChecked}
|
||||
/>
|
||||
) : null}
|
||||
{displayedRequest?.options.fields ? (
|
||||
<div className="space-y-3">
|
||||
{displayedRequest.options.fields.inputs.map((field) => (
|
||||
@@ -212,34 +220,6 @@ export function ConfirmationDialogProvider({
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
{displayedRequest?.options.option ? (
|
||||
<div className="flex items-start gap-2">
|
||||
<Checkbox
|
||||
id="confirmation-dialog-option"
|
||||
className="mt-0.5"
|
||||
checked={optionChecked ?? displayedRequest.options.option.defaultChecked}
|
||||
onCheckedChange={(checked) => setOptionChecked(checked === true)}
|
||||
aria-describedby={
|
||||
displayedRequest.options.option.detail
|
||||
? 'confirmation-dialog-option-detail'
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="confirmation-dialog-option">
|
||||
{displayedRequest.options.option.label}
|
||||
</Label>
|
||||
{displayedRequest.options.option.detail ? (
|
||||
<p
|
||||
id="confirmation-dialog-option-detail"
|
||||
className="text-xs text-muted-foreground"
|
||||
>
|
||||
{displayedRequest.options.option.detail}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{displayedRequest?.options.dontAskAgain ? (
|
||||
<div className="flex items-center gap-2">
|
||||
<Checkbox
|
||||
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { useEffect } from 'react'
|
||||
import { defineFixture } from '../../../../component-fixtures/component-fixture'
|
||||
import { ConfirmationDialogProvider } from '@/components/confirmation-dialog'
|
||||
import { useConfirmationDialog } from '@/components/confirmation-dialog-context'
|
||||
import type { AgentSessionCheckpointPreview } from '../../../../../../shared/agent-session/lifecycle/agent-session-checkpoint'
|
||||
import { nativeChatRewindPrompt } from './native-chat-rewind-files'
|
||||
|
||||
function OpenRewindPrompt({ preview }: { preview: AgentSessionCheckpointPreview | null }) {
|
||||
const confirm = useConfirmationDialog()
|
||||
useEffect(() => {
|
||||
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: () => (
|
||||
<div className="h-[340px]">
|
||||
<ConfirmationDialogProvider>
|
||||
<OpenRewindPrompt preview={preview} />
|
||||
</ConfirmationDialogProvider>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** 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' })
|
||||
+40
-28
@@ -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<ConfirmationDialogOptions, 'description' | 'option'> {
|
||||
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) {
|
||||
|
||||
+25
-3
@@ -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()
|
||||
})
|
||||
|
||||
+6
@@ -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": {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -86,7 +86,9 @@ test.describe('rewind with file restore, live agent', () => {
|
||||
const call = async <T>(method: string, params: unknown, timeoutMs = 60_000): Promise<T> =>
|
||||
(await host.client.call<T>(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<string> => {
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user