Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion packages/opencode/src/session/revert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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)
Expand Down
15 changes: 12 additions & 3 deletions packages/opencode/src/snapshot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,8 @@ export interface Interface {
readonly track: () => Effect.Effect<string | undefined>
readonly patch: (hash: string) => Effect.Effect<Patch>
readonly restore: (snapshot: string) => Effect.Effect<void>
readonly revert: (patches: Patch[]) => Effect.Effect<void>
/** Returns the files it left as they are because the snapshot store no longer has their earlier content. */
readonly revert: (patches: Patch[]) => Effect.Effect<string[]>
readonly diff: (hash: string) => Effect.Effect<string>
readonly diffFull: (from: string, to: string) => Effect.Effect<FileDiff[]>
}
Expand Down Expand Up @@ -422,6 +423,11 @@ const layer: Layer.Layer<Service, never, FSUtil.Service | AppProcess.Service | C
}
}

const kept: string[] = []

// A file is deleted only when the snapshot tree is readable and has no entry for it. A tree the
// store no longer has (pruned by cleanup, or a store recreated for a moved worktree) makes ls-tree
// fail, which says nothing about whether the file existed, so the file is left alone.
const single = Effect.fnUntraced(function* (op: (typeof ops)[number]) {
yield* Effect.logInfo("reverting", { file: op.file, hash: op.hash })
const result = yield* git([...core, ...args(["checkout", op.hash, "--", op.file])], {
Expand All @@ -431,11 +437,13 @@ const layer: Layer.Layer<Service, never, FSUtil.Service | AppProcess.Service | C
const tree = yield* git([...core, ...args(["ls-tree", op.hash, "--", op.rel])], {
cwd: state.worktree,
})
if (tree.code === 0 && tree.text.trim()) {
yield* Effect.logInfo("file existed in snapshot but checkout failed, keeping", {
if (tree.code !== 0 || tree.text.trim()) {
yield* Effect.logWarning("earlier content is not in the snapshot store, keeping", {
file: op.file,
hash: op.hash,
stderr: tree.code === 0 ? result.stderr : tree.stderr,
})
kept.push(op.file)
return
}
yield* Effect.logInfo("file did not exist in snapshot, deleting", { file: op.file, hash: op.hash })
Expand Down Expand Up @@ -519,6 +527,7 @@ const layer: Layer.Layer<Service, never, FSUtil.Service | AppProcess.Service | C

i = j
}
return kept
}),
)
})
Expand Down
68 changes: 66 additions & 2 deletions packages/opencode/test/session/revert-compact.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@ import { SessionProjector } from "@opencode-ai/core/session/projector"
import fs from "fs/promises"
import path from "path"
import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
import { Effect } from "effect"
import { Effect, Option, Schema } from "effect"
import { Session } from "@/session/session"

import { SessionRevert } from "../../src/session/revert"
import { EventV2Bridge } from "@/event-v2-bridge"
import { InstanceState } from "@/effect/instance-state"
import { Global } from "@opencode-ai/core/global"
import { Hash } from "@opencode-ai/core/util/hash"
import { $ } from "bun"
import { MessageV2 } from "../../src/session/message-v2"
import { Snapshot } from "../../src/snapshot"
import { MessageID, PartID, SessionID } from "../../src/session/schema"
Expand All @@ -19,7 +24,14 @@ import { ModelV2 } from "@opencode-ai/core/model"

const it = testEffect(
LayerNode.compile(
LayerNode.group([Session.node, SessionRevert.node, Snapshot.node, SessionProjector.node, CrossSpawnSpawner.node]),
LayerNode.group([
Session.node,
SessionRevert.node,
Snapshot.node,
SessionProjector.node,
CrossSpawnSpawner.node,
EventV2Bridge.node,
]),
),
)

Expand Down Expand Up @@ -680,4 +692,56 @@ describe("revert + compact workflow", () => {
{ 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 },
),
)
})
44 changes: 44 additions & 0 deletions packages/opencode/test/snapshot/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 }) =>
Expand Down
Loading