diff --git a/packages/opencode/src/session/revert.ts b/packages/opencode/src/session/revert.ts index 03e5afd085e0..a1f1cef6d964 100644 --- a/packages/opencode/src/session/revert.ts +++ b/packages/opencode/src/session/revert.ts @@ -9,6 +9,9 @@ import { MessageV2 } from "./message-v2" import { SessionID, MessageID, PartID } from "./schema" import { SessionRunState } from "./run-state" import { SessionSummary } from "./summary" +import { InstanceState } from "@/effect/instance-state" +import { NamedError } from "@opencode-ai/core/util/error" +import path from "path" export const RevertInput = Schema.Struct({ sessionID: SessionID, @@ -69,7 +72,8 @@ const layer = Layer.effect( rev.snapshot = session.revert?.snapshot ?? (yield* snap.track()) if (session.revert?.snapshot) yield* snap.restore(session.revert.snapshot) - yield* snap.revert(patches) + const kept = yield* snap.revert(patches) + if (kept.length) yield* reportKept(input.sessionID, kept) if (rev.snapshot) rev.diff = yield* snap.diff(rev.snapshot) const index = all.findIndex((msg) => msg.info.id === rev.messageID) const range = index < 0 ? [] : all.slice(index) @@ -88,6 +92,18 @@ const layer = Layer.effect( return yield* sessions.get(input.sessionID).pipe(Effect.orDie) }) + const reportKept = Effect.fnUntraced(function* (sessionID: SessionID, files: string[]) { + const ctx = yield* InstanceState.context + const names = files.map((file) => path.relative(ctx.worktree, file).replaceAll("\\", "/")) + const listed = names.slice(0, 5).join(", ") + (names.length > 5 ? ` and ${names.length - 5} more` : "") + const count = names.length === 1 ? "1 file" : `${names.length} files` + const message = `Revert kept ${count} as is because the snapshot store no longer has the earlier version: ${listed}` + yield* events.publish(Session.Event.Error, { + sessionID, + error: new NamedError.Unknown({ message }).toObject(), + }) + }) + const unrevert = Effect.fn("SessionRevert.unrevert")(function* (input: { sessionID: SessionID }) { yield* Effect.logInfo("unreverting", { sessionID: input.sessionID }) yield* state.assertNotBusy(input.sessionID) diff --git a/packages/opencode/src/snapshot/index.ts b/packages/opencode/src/snapshot/index.ts index 4da9bc3ca864..a2734aa07f56 100644 --- a/packages/opencode/src/snapshot/index.ts +++ b/packages/opencode/src/snapshot/index.ts @@ -39,7 +39,8 @@ export interface Interface { readonly track: () => Effect.Effect readonly patch: (hash: string) => Effect.Effect readonly restore: (snapshot: string) => Effect.Effect - readonly revert: (patches: Patch[]) => Effect.Effect + /** Returns the files it left as they are because the snapshot store no longer has their earlier content. */ + readonly revert: (patches: Patch[]) => Effect.Effect readonly diff: (hash: string) => Effect.Effect readonly diffFull: (from: string, to: string) => Effect.Effect } @@ -422,6 +423,11 @@ const layer: Layer.Layer { { git: true }, ), ) + + it.live( + "a revert whose snapshot was pruned keeps the files and says which", + provideTmpdirInstance( + (dir) => + Effect.gen(function* () { + const session = yield* Session.Service + const revert = yield* SessionRevert.Service + const snapshot = yield* Snapshot.Service + const bridge = yield* EventV2Bridge.Service + const errors: string[] = [] + const off = yield* bridge.listen((event) => { + if (event.type !== Session.Event.Error.type) return Effect.void + const data = Option.getOrUndefined(Schema.decodeUnknownOption(Session.Event.Error.data)(event.data)) + if (data?.error?.name === "UnknownError") errors.push(data.error.data.message) + return Effect.void + }) + yield* Effect.addFinalizer(() => off) + + yield* write(path.join(dir, "a.txt"), "a0") + const sid = (yield* session.create({})).id + const u = yield* user(sid) + yield* text(sid, u.id, "edit a.txt") + const a = yield* assistant(sid, u.id, dir) + const before = yield* snapshot.track() + if (!before) throw new Error("expected snapshot") + yield* write(path.join(dir, "a.txt"), "a1") + const patch = yield* snapshot.patch(before) + yield* session.updatePart({ + id: PartID.ascending(), + messageID: a.id, + sessionID: sid, + type: "patch", + hash: patch.hash, + files: patch.files, + }) + + const ctx = yield* InstanceState.context + const gitdir = path.join(Global.Path.data, "snapshot", ctx.project.id, Hash.fast(ctx.worktree)) + yield* Effect.promise(() => $`git --git-dir ${gitdir} gc --quiet --prune=now`.quiet()) + + yield* revert.revert({ sessionID: sid, messageID: u.id }) + + expect(yield* read(path.join(dir, "a.txt"))).toBe("a1") + expect((yield* session.get(sid)).revert?.messageID).toBe(u.id) + expect(errors).toEqual([ + "Revert kept 1 file as is because the snapshot store no longer has the earlier version: a.txt", + ]) + }), + { git: true }, + ), + ) }) diff --git a/packages/opencode/test/snapshot/snapshot.test.ts b/packages/opencode/test/snapshot/snapshot.test.ts index a39624087c63..9947c46cefd7 100644 --- a/packages/opencode/test/snapshot/snapshot.test.ts +++ b/packages/opencode/test/snapshot/snapshot.test.ts @@ -3,9 +3,12 @@ import { $ } from "bun" import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner" import { LayerNode } from "@opencode-ai/core/effect/layer-node" import { FSUtil } from "@opencode-ai/core/fs-util" +import { Global } from "@opencode-ai/core/global" +import { Hash } from "@opencode-ai/core/util/hash" import fs from "fs/promises" import path from "path" import { Effect, Fiber, Layer } from "effect" +import { InstanceState } from "../../src/effect/instance-state" import { Snapshot } from "../../src/snapshot" import { disposeAllInstances, @@ -277,6 +280,47 @@ it.instance( { git: true }, ) +// What `cleanup()` does to a snapshot older than its prune window: snapshot trees have no refs, so once the +// store has moved on they are unreachable and `git gc` deletes them. +const pruneSnapshotStore = Effect.fn("SnapshotTest.pruneSnapshotStore")(function* (worktree: string) { + const ctx = yield* InstanceState.context + const gitdir = path.join(Global.Path.data, "snapshot", ctx.project.id, Hash.fast(ctx.worktree)) + yield* exec(worktree, ["git", "--git-dir", gitdir, "gc", "--quiet", "--prune=now"]) +}) + +it.instance( + "revert keeps files whose earlier content the snapshot store no longer has", + withTrackedSnapshot(({ tmp, snapshot, before }) => + Effect.gen(function* () { + yield* write(`${tmp.path}/a.txt`, "edited after the snapshot") + yield* write(`${tmp.path}/new.txt`, "NEW") + const patch = yield* snapshot.patch(before) + yield* pruneSnapshotStore(tmp.path) + + const kept = yield* snapshot.revert([patch]) + + expect(yield* readText(`${tmp.path}/a.txt`)).toBe("edited after the snapshot") + expect(yield* readText(`${tmp.path}/new.txt`)).toBe("NEW") + expect(kept.toSorted()).toEqual([fwd(tmp.path, "a.txt"), fwd(tmp.path, "new.txt")]) + }), + ), + { git: true }, +) + +it.instance( + "revert still deletes a file the readable snapshot records as absent, and reports nothing", + withTrackedSnapshot(({ tmp, snapshot, before }) => + Effect.gen(function* () { + yield* write(`${tmp.path}/new.txt`, "NEW") + yield* write(`${tmp.path}/a.txt`, "edited") + expect(yield* snapshot.revert([yield* snapshot.patch(before)])).toEqual([]) + expect(yield* exists(`${tmp.path}/new.txt`)).toBe(false) + expect(yield* readText(`${tmp.path}/a.txt`)).toBe(tmp.extra.aContent) + }), + ), + { git: true }, +) + it.instance( "revert non-existent file", withTrackedSnapshot(({ tmp, snapshot, before }) =>