Skip to content
Merged
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
57 changes: 38 additions & 19 deletions packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1226,9 +1226,11 @@ const layer = Layer.effect(
return { info, parts }
}, Effect.scoped)

const prompt: (input: PromptInput) => Effect.Effect<SessionV1.WithParts, Image.Error> = Effect.fn(
"SessionPrompt.prompt",
)(function* (input: PromptInput) {
const promptWithEpoch = Effect.fn("SessionPrompt.prompt")(function* (
input: PromptInput,
initialEpoch?: number,
) {
const epoch = initialEpoch ?? (yield* state.cancelEpoch(input.sessionID))
const session = yield* sessions.get(input.sessionID).pipe(Effect.orDie)
yield* revert.cleanup(session)
const message = yield* createUserMessage(input)
Expand All @@ -1244,9 +1246,12 @@ const layer = Layer.effect(
}

if (input.noReply === true) return message
return yield* loop({ sessionID: input.sessionID, messageID: message.info.id })
return yield* loopWithEpoch({ sessionID: input.sessionID, messageID: message.info.id }, epoch)
})

const prompt: (input: PromptInput) => Effect.Effect<SessionV1.WithParts, Image.Error> = (input) =>
promptWithEpoch(input)

const lastAssistant = Effect.fnUntraced(function* (sessionID: SessionID) {
const match = yield* sessions.findMessage(sessionID, (m) => m.info.role !== "user").pipe(Effect.orDie)
if (Option.isSome(match)) return match.value
Expand Down Expand Up @@ -1877,30 +1882,38 @@ const layer = Layer.effect(
}
})

const loop: (input: LoopInput) => Effect.Effect<SessionV1.WithParts> = Effect.fn("SessionPrompt.loop")(function* (
input: LoopInput,
) {
const loopWithEpoch = Effect.fn("SessionPrompt.loop")(function* (input: LoopInput, initialEpoch?: number) {
// A loop call arriving while another run is active joins that run and
// its own runLoop work never executes (the runner keeps a single run),
// so the caller's freshly persisted user message could stay unanswered
// while the caller received the old run's result (#410). Re-enter until
// a run has actually answered this caller's message; if a newer user
// message overtook it and got answered instead, return the latest state
// rather than spinning on a superseded prompt.
// A cancel that ends the run this caller joined must not be followed by a
// fresh run for the caller's queued message: cancel releases queued callers.
const epoch = yield* state.cancelEpoch(input.sessionID)
// A cancel that happens while a prompt/command is preparing or while this
// caller is waiting to (re-)enter the loop must not be followed by a fresh
// run: cancel releases callers already submitted to the session.
const epoch = initialEpoch ?? (yield* state.cancelEpoch(input.sessionID))
let last: SessionV1.WithParts | undefined
while (true) {
if ((yield* state.cancelEpoch(input.sessionID)) !== epoch) {
yield* state.awaitCancel(input.sessionID)
return last ?? (yield* lastAssistant(input.sessionID))
}
const result = yield* state.ensureRunning(
input.sessionID,
lastAssistant(input.sessionID),
runLoop(input.sessionID).pipe(Effect.ensuring(settleOrphanedParts(input.sessionID))),
)
last = result
if (!input.messageID || (result.info.role === "assistant" && result.info.parentID === input.messageID))
return result
// Checked before every other re-entry path: once the run this caller joined was
// cancelled, no queued prompt (this one or a newer one) may start a fresh run.
if ((yield* state.cancelEpoch(input.sessionID)) !== epoch) return result
if ((yield* state.cancelEpoch(input.sessionID)) !== epoch) {
yield* state.awaitCancel(input.sessionID)
return result
}

const msgs = yield* sessions
.messages({ sessionID: input.sessionID })
Expand All @@ -1914,6 +1927,8 @@ const layer = Layer.effect(
}
})

const loop: (input: LoopInput) => Effect.Effect<SessionV1.WithParts> = (input) => loopWithEpoch(input)

const shell: (input: ShellInput) => Effect.Effect<SessionV1.WithParts, Session.BusyError> = Effect.fn(
"SessionPrompt.shell",
)(function* (input: ShellInput) {
Expand All @@ -1922,6 +1937,7 @@ const layer = Layer.effect(
})

const command = Effect.fn("SessionPrompt.command")(function* (input: CommandInput) {
const epoch = yield* state.cancelEpoch(input.sessionID)
yield* Effect.logInfo("command", {
"session.id": input.sessionID,
command: input.command,
Expand Down Expand Up @@ -2042,14 +2058,17 @@ const layer = Layer.effect(
{ parts },
)

const result = yield* prompt({
sessionID: input.sessionID,
messageID: input.messageID,
model: userModel,
agent: userAgent,
parts,
variant: input.variant,
})
const result = yield* promptWithEpoch(
{
sessionID: input.sessionID,
messageID: input.messageID,
model: userModel,
agent: userAgent,
parts,
variant: input.variant,
},
epoch,
)
yield* events.publish(Command.Event.Executed, {
name: input.command,
sessionID: input.sessionID,
Expand Down
59 changes: 52 additions & 7 deletions packages/opencode/src/session/run-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { InstanceState } from "@/effect/instance-state"
import { SessionV1 } from "@opencode-ai/core/v1/session"
import { Runner } from "@/effect/runner"
import { BackgroundJob } from "@/background/job"
import { Effect, Latch, Layer, Scope, Context } from "effect"
import { Effect, Deferred, Latch, Layer, Scope, Context } from "effect"
import { Session } from "./session"
import { SessionID } from "./schema"
import { SessionStatus } from "./status"
Expand All @@ -15,6 +15,8 @@ export interface Interface {
readonly cancelBackground: (sessionID: SessionID) => Effect.Effect<void>
/** Counts foreground cancels of a session's active run; lets a queued caller tell it was cancelled. */
readonly cancelEpoch: (sessionID: SessionID) => Effect.Effect<number>
/** Waits for any in-flight foreground cancellation of `sessionID` to finish settling. */
readonly awaitCancel: (sessionID: SessionID) => Effect.Effect<void>
readonly ensureRunning: (
sessionID: SessionID,
onInterrupt: Effect.Effect<SessionV1.WithParts>,
Expand All @@ -41,16 +43,18 @@ const layer = Layer.effect(
const scope = yield* Scope.Scope
const runners = new Map<SessionID, Runner.Runner<SessionV1.WithParts>>()
const epochs = new Map<SessionID, number>()
const cancelling = new Map<SessionID, Deferred.Deferred<void>>()
yield* Effect.addFinalizer(
Effect.fnUntraced(function* () {
yield* Effect.forEach(runners.values(), (runner) => runner.cancel, {
concurrency: "unbounded",
discard: true,
})
runners.clear()
cancelling.clear()
}),
)
return { runners, epochs, scope }
return { runners, epochs, cancelling, scope }
}),
)

Expand Down Expand Up @@ -79,29 +83,61 @@ const layer = Layer.effect(
if (existing?.busy) yield* busyError(sessionID)
})

const cancelForeground = Effect.fn("SessionRunState.cancelForeground")(function* (sessionID: SessionID) {
const bumpEpoch = (data: { epochs: Map<SessionID, number> }, sessionID: SessionID) => {
data.epochs.set(sessionID, (data.epochs.get(sessionID) ?? 0) + 1)
}

const cancelForegroundImpl = Effect.fnUntraced(function* (sessionID: SessionID, alreadyBumped: boolean) {
const data = yield* InstanceState.get(state)
if (!alreadyBumped) bumpEpoch(data, sessionID)
const existing = data.runners.get(sessionID)
if (!existing) {
const inflight = data.cancelling.get(sessionID)
if (inflight) {
yield* Deferred.await(inflight)
return
}
yield* status.set(sessionID, { type: "idle" })
return
}
data.epochs.set(sessionID, (data.epochs.get(sessionID) ?? 0) + 1)
yield* existing.cancel
const done = yield* Deferred.make<void>()
const prev = data.cancelling.get(sessionID)
data.cancelling.set(sessionID, done)
yield* existing.cancel.pipe(
Effect.ensuring(
Effect.gen(function* () {
if (prev) yield* Deferred.await(prev)
if (data.cancelling.get(sessionID) === done) data.cancelling.delete(sessionID)
yield* Deferred.succeed(done, void 0)
}),
),
)
})

const cancelForeground = Effect.fn("SessionRunState.cancelForeground")(function* (sessionID: SessionID) {
yield* cancelForegroundImpl(sessionID, false)
})

const cancelEpoch = Effect.fn("SessionRunState.cancelEpoch")(function* (sessionID: SessionID) {
const data = yield* InstanceState.get(state)
return data.epochs.get(sessionID) ?? 0
})

const awaitCancel = Effect.fn("SessionRunState.awaitCancel")(function* (sessionID: SessionID) {
const data = yield* InstanceState.get(state)
const inflight = data.cancelling.get(sessionID)
if (inflight) yield* Deferred.await(inflight)
})

const cancelBackground = Effect.fn("SessionRunState.cancelBackground")(function* (sessionID: SessionID) {
yield* cancelBackgroundJobs(background, sessionID)
})

const cancel = Effect.fn("SessionRunState.cancel")(function* (sessionID: SessionID) {
const data = yield* InstanceState.get(state)
bumpEpoch(data, sessionID)
yield* cancelBackground(sessionID)
yield* cancelForeground(sessionID)
yield* cancelForegroundImpl(sessionID, true)
})

const ensureRunning = Effect.fn("SessionRunState.ensureRunning")(function* (
Expand All @@ -123,7 +159,16 @@ const layer = Layer.effect(
.pipe(Effect.catchTag("RunnerBusy", () => Effect.fail(busyError(sessionID))))
})

return Service.of({ assertNotBusy, cancel, cancelForeground, cancelBackground, cancelEpoch, ensureRunning, startShell })
return Service.of({
assertNotBusy,
cancel,
cancelForeground,
cancelBackground,
cancelEpoch,
awaitCancel,
ensureRunning,
startShell,
})
}),
)

Expand Down
Loading
Loading