From 19fada91b8208cb6625a270bc385dd68bf49e802 Mon Sep 17 00:00:00 2001 From: BELLEAvery <117633793+BELLEAvery@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:24:46 +0800 Subject: [PATCH] fix(core): scope revert to delegated subagent steps --- packages/core/src/session/revert.ts | 194 +++++++++++++++++++--- packages/core/src/tool/plugin/subagent.ts | 13 +- packages/core/test/session-revert.test.ts | 161 ++++++++++++++++++ packages/core/test/tool-subagent.test.ts | 13 +- 4 files changed, 350 insertions(+), 31 deletions(-) diff --git a/packages/core/src/session/revert.ts b/packages/core/src/session/revert.ts index 6bffb3c4017d..a7dd95ce22b9 100644 --- a/packages/core/src/session/revert.ts +++ b/packages/core/src/session/revert.ts @@ -1,8 +1,10 @@ export * as SessionRevert from "./revert.js" -import { and, asc, eq, gt } from "drizzle-orm" -import { Effect } from "effect" +import { and, asc, eq, gt, gte, isNull, lte, sql } from "drizzle-orm" +import { Effect, Schema } from "effect" +import { Event } from "@opencode/schema/event" import { Database } from "../database/database.js" +import { EventTable } from "../event/sql.js" import { Bus } from "../bus.js" import { Instance } from "../instance/service.js" import { RelativePath } from "../schema.js" @@ -12,10 +14,11 @@ import { MessageNotFoundError } from "./error.js" import { SessionMessage } from "./message.js" import { SessionSchema } from "./schema.js" import { SessionHistory } from "./history.js" -import { SessionMessageTable } from "./sql.js" +import { SessionMessageTable, SessionTable } from "./sql.js" interface BoundaryInput { - readonly sessionID: SessionSchema.ID + readonly files?: boolean + readonly session: SessionSchema.Info readonly messageID: SessionMessage.ID } @@ -31,7 +34,7 @@ export const stage = Effect.fn("SessionRevert.stage")(function* (input: { return yield* Effect.gen(function* () { const snapshot = yield* Snapshot.Service const original = input.session.revert?.snapshot ?? (yield* snapshot.capture()) - const next = yield* plan(database.db, { sessionID: input.session.id, messageID: input.messageID }) + const next = yield* plan(database.db, input, original) const restore = new Map() if (original) { for (const file of input.session.revert?.files ?? []) restore.set(RelativePath.make(file.file), original) @@ -80,33 +83,180 @@ export const commit = Effect.fn("SessionRevert.commit")(function* (bus: Bus.Inte }) }) -const plan = Effect.fn("SessionRevert.plan")(function* (db: Database.Interface["db"], input: BoundaryInput) { +const plan = Effect.fn("SessionRevert.plan")(function* ( + db: Database.Interface["db"], + input: BoundaryInput, + original: Snapshot.ID | undefined, +) { const boundary = yield* db .select({ seq: SessionMessageTable.seq }) .from(SessionMessageTable) - .where(and(eq(SessionMessageTable.session_id, input.sessionID), eq(SessionMessageTable.id, input.messageID))) + .where(and(eq(SessionMessageTable.session_id, input.session.id), eq(SessionMessageTable.id, input.messageID))) .get() .pipe(Effect.orDie) - if (!boundary) return yield* new MessageNotFoundError(input) - const rows = yield* db - .select() + if (!boundary) return yield* new MessageNotFoundError({ sessionID: input.session.id, messageID: input.messageID }) + if (input.files === false) return new Map() + const steps: Step[] = [] + const pending = new Map([[input.session.id, []]]) + for (const [sessionID, calls] of pending) { + const child = sessionID !== input.session.id + const ranges = child ? yield* delegatedRanges(db, sessionID, calls) : [{ after: boundary.seq, before: Infinity }] + if (!ranges.length) continue + const rows = yield* db + .select() + .from(SessionMessageTable) + .where( + and( + eq(SessionMessageTable.session_id, sessionID), + eq(SessionMessageTable.type, "assistant"), + gt(SessionMessageTable.seq, ranges[0]!.after), + ), + ) + .orderBy(asc(SessionMessageTable.seq)) + .all() + .pipe(Effect.orDie) + const included = child ? rows.filter((row) => ranges.some((r) => row.seq > r.after && row.seq < r.before)) : rows + const children = yield* db + .select({ id: SessionTable.id }) + .from(SessionTable) + .where( + and( + eq(SessionTable.parent_id, sessionID), + eq(SessionTable.project_id, input.session.projectID), + eq(SessionTable.directory, input.session.location.directory), + input.session.location.workspaceID + ? eq(SessionTable.workspace_id, input.session.location.workspaceID) + : isNull(SessionTable.workspace_id), + ), + ) + .all() + .pipe(Effect.orDie) + const owned = new Set(children.map((item) => item.id)) + const delegated = new Map() + for (const row of owned.size ? yield* SessionHistory.withParts(db, included) : included) { + const message = SessionHistory.decodeMessageRowSync(row) + if (message.type !== "assistant") continue + if (message.snapshot?.files?.length) steps.push({ message, child }) + if (!owned.size) continue + for (const part of message.content) { + if (part.type !== "tool" || part.name !== "subagent" || part.state.status === "streaming") continue + const id = part.state.metadata?.sessionID + if (!Schema.is(SessionSchema.ID)(id) || !owned.has(id) || pending.has(id)) continue + const list = delegated.get(id) ?? [] + list.push(part) + delegated.set(id, list) + } + } + for (const [id, refs] of delegated) pending.set(id, refs) + } + + return yield* restoreFiles(steps, original) +}) + +const delegatedRanges = Effect.fnUntraced(function* ( + db: Database.Interface["db"], + sessionID: SessionSchema.ID, + calls: readonly SessionMessage.AssistantTool[], +) { + const prompts = yield* db + .select({ + id: SessionMessageTable.id, + seq: SessionMessageTable.seq, + created: SessionMessageTable.time_created, + text: sql`json_extract(${SessionMessageTable.data}, '$.text')`, + }) .from(SessionMessageTable) - .where( - and( - eq(SessionMessageTable.session_id, input.sessionID), - eq(SessionMessageTable.type, "assistant"), - gt(SessionMessageTable.seq, boundary.seq), - ), - ) + .where(and(eq(SessionMessageTable.session_id, sessionID), eq(SessionMessageTable.type, "user"))) .orderBy(asc(SessionMessageTable.seq)) .all() .pipe(Effect.orDie) + const selected = new Set() + for (const call of calls) { + if (call.state.status === "streaming") continue + const id = call.state.metadata?.promptMessageID + if (Schema.is(SessionMessage.ID)(id)) { + selected.add(id) + continue + } + // Older calls stored only the child ID. A launch created its first prompt. For a + // follow-up, require a unique matching admission during that specific tool call. + if (!call.state.input.sessionID) { + if (prompts[0]) selected.add(prompts[0].id) + continue + } + const text = call.state.input.prompt + const started = (call.time.ran ?? call.time.created).epochMilliseconds + const completed = call.time.completed?.epochMilliseconds + if (completed === undefined || typeof text !== "string") continue + const enqueued = yield* db + .select({ id: sql`json_extract(${EventTable.data}, '$.inboxID')` }) + .from(EventTable) + .where( + and( + eq(EventTable.aggregate_id, sessionID), + eq( + EventTable.type, + Event.versionedType(SessionEvent.InboxEnqueued.type, SessionEvent.InboxEnqueued.durable.version), + ), + gte(EventTable.created, started), + lte(EventTable.created, completed), + ), + ) + .all() + .pipe(Effect.orDie) + const admitted = new Set(enqueued.map((item) => item.id)) + const matches = prompts.filter( + (p) => p.text === text && (admitted.has(p.id) || (p.created >= started && p.created <= completed)), + ) + if (matches.length === 1) selected.add(matches[0]!.id) + } + return prompts.flatMap((prompt, i) => + selected.has(prompt.id) ? [{ after: prompt.seq, before: prompts[i + 1]?.seq ?? Infinity }] : [], + ) +}) + +type Step = { message: SessionMessage.Assistant; child: boolean } + +const restoreFiles = Effect.fnUntraced(function* (steps: Step[], original: Snapshot.ID | undefined) { const files = new Map() - for (const row of rows) { - const message = SessionHistory.decodeMessageRowSync(row) - if (message.type !== "assistant" || !message.snapshot?.start) continue - for (const file of message.snapshot.files ?? []) - if (!files.has(file)) files.set(file, message.snapshot.start) + const last = new Map() + const snapshots = yield* Snapshot.Service + const comparisons = new Map>() + const changed = Effect.fnUntraced(function* (from: Snapshot.ID, to: Snapshot.ID, file: RelativePath) { + if (from === to) return false + const key = from + ":" + to + const cached = comparisons.get(key) + if (cached) return cached.has(file) + const paths = new Set(yield* snapshots.files({ from, to })) + comparisons.set(key, paths) + return paths.has(file) + }) + + if (steps.some((step) => step.child)) + steps.sort((a, b) => a.message.time.created.epochMilliseconds - b.message.time.created.epochMilliseconds) + for (const { message, child } of steps) { + const tree = message.snapshot + if (!tree?.start) continue + const start = message.time.created.epochMilliseconds + const end = (message.time.completed ?? message.time.created).epochMilliseconds + for (const file of tree.files ?? []) { + const previous = last.get(file) + // If someone edited the path between two delegated steps, only undo back to that edit. + if ( + !files.has(file) || + (previous && + (previous.child || child) && + previous.time <= start && + (yield* changed(previous.tree, tree.start, file))) + ) + files.set(file, tree.start) + if (tree.end && (!previous || previous.time <= end)) last.set(file, { time: end, tree: tree.end, child }) + } } + // The last child edit may itself have been superseded before revert was requested. + if (original) + for (const [file, end] of last) { + if (end.child && (yield* changed(end.tree, original, file))) files.delete(file) + } return files }) diff --git a/packages/core/src/tool/plugin/subagent.ts b/packages/core/src/tool/plugin/subagent.ts index 07a4cfb0ddbb..61b7f43303e8 100644 --- a/packages/core/src/tool/plugin/subagent.ts +++ b/packages/core/src/tool/plugin/subagent.ts @@ -191,7 +191,7 @@ export const Plugin = { ((yield* sessions.active).has(existing.id) || (yield* jobs.get(existing.id))?.status === "running") yield* context.progress({ sessionID: child.id, status: "running" }) - yield* sessions + const prompt = yield* sessions .prompt({ sessionID: child.id, text: @@ -214,14 +214,13 @@ export const Plugin = { description: input.description, } yield* subagents.start(recovery) - return backgroundResult(child.id) - }).pipe( - Effect.map((output) => ({ + const output = backgroundResult(child.id) + return { output, content: output.output, - metadata: { sessionID: output.sessionID, status: output.status }, - })), - ), + metadata: { sessionID: child.id, status: output.status, promptMessageID: prompt.id }, + } + }), }), ) .pipe(Effect.orDie) diff --git a/packages/core/test/session-revert.test.ts b/packages/core/test/session-revert.test.ts index bc3906857760..139e244e4e7b 100644 --- a/packages/core/test/session-revert.test.ts +++ b/packages/core/test/session-revert.test.ts @@ -118,4 +118,165 @@ describe("Session.revert files", () => { // Real Location/plugin startup and Git snapshots can exceed five seconds under CI load. { timeout: 15_000 }, ) + + it.live( + "reverts only child steps delegated by the selected parent prompts", + () => + Effect.gen(function* () { + const tmp = yield* tmpdirScoped() + const directory = tmp.path + yield* Effect.promise(() => $`git init -q`.cwd(directory).quiet()) + const sessions = yield* Session.Service + const database = yield* Database.Service + const bus = yield* Bus.Service + const root = yield* sessions.create({ location: { directory: AbsolutePath.make(directory) } }) + const first = yield* sessions.create({ parentID: root.id }) + const second = yield* sessions.create({ parentID: root.id }) + + yield* Effect.gen(function* () { + const plugins = yield* Plugin.Service + yield* plugins.awaitActivation + const snapshots = yield* Snapshot.Service + const prompt = Effect.fnUntraced(function* (sessionID: Session.ID, text: string) { + const result = yield* sessions.prompt({ sessionID, text, resume: false }) + yield* SessionInbox.promote(database.db, bus, sessionID, "steer") + return result.id + }) + const step = Effect.fnUntraced(function* ( + sessionID: Session.ID, + action: (assistantMessageID: SessionMessage.ID) => Effect.Effect, + ) { + const assistantMessageID = SessionMessage.ID.create() + const start = (yield* snapshots.capture())! + yield* bus.publish(SessionEvent.Step.Started, { + sessionID, + assistantMessageID, + agent: Agent.defaultID, + model: { id: Model.ID.make("test-model"), providerID: Provider.ID.make("test-provider") }, + snapshot: start, + started: Date.now(), + }) + yield* action(assistantMessageID) + const end = (yield* snapshots.capture())! + yield* bus.publish(SessionEvent.Step.Ended, { + sessionID, + assistantMessageID, + finish: "stop", + cost: Money.USD.zero, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + snapshot: end, + files: yield* snapshots.files({ from: start, to: end }), + }) + }) + const delegate = (child: Session.ID, followup?: SessionMessage.ID) => + step(root.id, (assistantMessageID) => + Effect.gen(function* () { + const call = { sessionID: root.id, assistantMessageID, id: "call" } + yield* bus.publish(SessionEvent.Tool.Input.Started, { ...call, name: "subagent" }) + yield* bus.publish(SessionEvent.Tool.Called, { + ...call, + input: followup ? { sessionID: child } : {}, + executed: false, + }) + yield* bus.publish(SessionEvent.Tool.Success, { + ...call, + executed: false, + content: [{ type: "text", text: "started" }], + metadata: { sessionID: child, ...(followup ? { promptMessageID: followup } : {}) }, + }) + }), + ) + const write = (name: string, text: string) => + Effect.promise(() => Bun.write(path.join(directory, name), text)) + const read = (name: string) => Effect.promise(() => fs.readFile(path.join(directory, name), "utf8")) + + yield* prompt(root.id, "A") + yield* delegate(first.id) + yield* prompt(first.id, "first task") + const boundary = yield* prompt(root.id, "B") + yield* delegate(second.id) + yield* prompt(second.id, "second task") + yield* step(second.id, () => Effect.all([write("owned", "B"), write("shared", "B"), write("between", "B")])) + yield* step(first.id, () => + Effect.all([write("shared", "A"), write("unrelated", "A"), write("between", "A")]), + ) + const followup = yield* prompt(root.id, "Follow up on B") + const next = yield* prompt(second.id, "follow-up") + yield* delegate(second.id, next) + yield* step(second.id, () => Effect.all([write("owned", "follow-up"), write("between", "follow-up")])) + yield* prompt(second.id, "Independent prompt directly to the child") + yield* step(second.id, () => write("independent", "keep")) + + yield* sessions.revert.stage({ sessionID: root.id, messageID: followup }) + expect(yield* read("owned")).toBe("B") + yield* sessions.revert.clear(root.id) + expect(yield* read("owned")).toBe("follow-up") + const result = yield* sessions.revert.stage({ sessionID: root.id, messageID: boundary }) + expect(result.files?.map((f) => f.file)).toEqual(["between", "owned"]) + expect(yield* read("between")).toBe("A") + expect(yield* Effect.promise(() => Bun.file(path.join(directory, "owned")).exists())).toBe(false) + expect(yield* read("shared")).toBe("A") + expect(yield* read("unrelated")).toBe("A") + expect(yield* read("independent")).toBe("keep") + yield* sessions.revert.clear(root.id) + expect(yield* read("owned")).toBe("follow-up") + + const legacyBoundary = yield* prompt(root.id, "Legacy follow-up") + yield* step(root.id, (assistantMessageID) => + Effect.gen(function* () { + const call = { sessionID: root.id, assistantMessageID, id: "legacy-call" } + yield* bus.publish(SessionEvent.Tool.Input.Started, { ...call, name: "subagent" }) + yield* bus.publish(SessionEvent.Tool.Called, { + ...call, + input: { sessionID: second.id, prompt: "Legacy child prompt" }, + executed: false, + }) + yield* sessions + .prompt({ sessionID: second.id, text: "Legacy child prompt", resume: false }) + .pipe(Effect.orDie) + yield* bus.publish(SessionEvent.Tool.Success, { + ...call, + executed: false, + content: [{ type: "text", text: "queued" }], + metadata: { sessionID: second.id }, + }) + }), + ) + yield* Effect.promise(() => Bun.sleep(10)) + yield* SessionInbox.promote(database.db, bus, second.id, "steer") + yield* step(second.id, () => write("owned", "legacy")) + + const legacyRevert = yield* sessions.revert.stage({ sessionID: root.id, messageID: legacyBoundary }) + expect(legacyRevert.files?.map((file) => file.file)).toEqual(["owned"]) + expect(yield* read("owned")).toBe("follow-up") + yield* sessions.revert.clear(root.id) + + const nestedBoundary = yield* prompt(root.id, "Delegate a nested task") + const childPrompt = yield* prompt(second.id, "Ask a grandchild") + yield* delegate(second.id, childPrompt) + const grandchild = yield* sessions.create({ parentID: second.id }) + yield* step(second.id, (assistantMessageID) => + Effect.gen(function* () { + const call = { sessionID: second.id, assistantMessageID, id: "nested-call" } + yield* bus.publish(SessionEvent.Tool.Input.Started, { ...call, name: "subagent" }) + yield* bus.publish(SessionEvent.Tool.Called, { ...call, input: {}, executed: false }) + yield* bus.publish(SessionEvent.Tool.Success, { + ...call, + executed: false, + content: [{ type: "text", text: "started" }], + metadata: { sessionID: grandchild.id }, + }) + }), + ) + yield* prompt(grandchild.id, "Edit a nested file") + yield* step(grandchild.id, () => write("nested", "grandchild")) + + const nestedRevert = yield* sessions.revert.stage({ sessionID: root.id, messageID: nestedBoundary }) + expect(nestedRevert.files?.map((file) => file.file)).toEqual(["nested"]) + expect(yield* Effect.promise(() => Bun.file(path.join(directory, "nested")).exists())).toBe(false) + expect(yield* read("owned")).toBe("legacy") + }).pipe(Effect.provide(LocationServiceMap.Service.get(root.location))) + }), + { timeout: 15_000 }, + ) }) diff --git a/packages/core/test/tool-subagent.test.ts b/packages/core/test/tool-subagent.test.ts index 23570d1131df..be1cf204f335 100644 --- a/packages/core/test/tool-subagent.test.ts +++ b/packages/core/test/tool-subagent.test.ts @@ -412,6 +412,7 @@ describe("SubagentTool", () => { expect(settled.metadata).toEqual({ sessionID: outputSessionID(settled.metadata), status: "running", + promptMessageID: expect.any(String), }) expect((yield* sessions.get(outputSessionID(settled.metadata))).parentID).toBe(parent.id) }), @@ -452,7 +453,11 @@ describe("SubagentTool", () => { const child = yield* sessions.get(outputSessionID(settled.metadata)) expect(settled.output).toMatchObject({ sessionID: child.id, status: "running" }) expect(settled.output.output).toContain(`sessionID: ${child.id}`) - expect(settled.metadata).toEqual({ sessionID: child.id, status: "running" }) + expect(settled.metadata).toEqual({ + sessionID: child.id, + status: "running", + promptMessageID: expect.any(String), + }) expect(progress[0]).toEqual({ sessionID: child.id, status: "running" }) expect(child).toMatchObject({ parentID: parent.id, @@ -849,7 +854,11 @@ describe("SubagentTool", () => { expect(settled.metadata).toMatchObject({ status: "running", }) - expect(settled.metadata).toEqual({ sessionID: childID, status: "running" }) + expect(settled.metadata).toEqual({ + sessionID: childID, + status: "running", + promptMessageID: expect.any(String), + }) expect(settled.content).toEqual([{ type: "text", text: expect.stringContaining(`sessionID: ${childID}`) }]) const admission = Array.from(yield* Fiber.join(admitted))[0]