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
194 changes: 172 additions & 22 deletions packages/core/src/session/revert.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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
}

Expand All @@ -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<RelativePath, Snapshot.ID>()
if (original) {
for (const file of input.session.revert?.files ?? []) restore.set(RelativePath.make(file.file), original)
Expand Down Expand Up @@ -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<RelativePath, Snapshot.ID>()
const steps: Step[] = []
const pending = new Map<SessionSchema.ID, readonly SessionMessage.AssistantTool[]>([[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<SessionSchema.ID, SessionMessage.AssistantTool[]>()
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<string>`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<SessionMessage.ID>()
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<SessionMessage.ID>`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<RelativePath, Snapshot.ID>()
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<RelativePath, { time: number; tree: Snapshot.ID; child: boolean }>()
const snapshots = yield* Snapshot.Service
const comparisons = new Map<string, Set<RelativePath>>()
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
})
13 changes: 6 additions & 7 deletions packages/core/src/tool/plugin/subagent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down
Loading
Loading