Skip to content

Commit 653d353

Browse files
committed
fix(core): settle a declined tool call as the user's stop
A declined permission or a dismissed question ends the turn with a bare self-interrupt, which the settle reads as a shutdown. The turn then keeps its execution claim, is reported as `session.execution.interrupted` with reason `shutdown`, projects no idle outcome, and resumes at the next server start with "The server restarted while you were working…", so the model goes on with the work the user declined. Clients that wait out a shutdown (opencode.el) also keep the session busy after the reject. The step now names the stop before interrupting: the drain input gains `reportDeclined`, which the execution layer wires to the coordinator's new `stopReason(key, "user")`. The settle releases the claim and cancels the session's jobs as for any user interrupt. Teardown is unchanged: a location that shuts down is closed before its pending asks are failed, and the step completes those for continuation before it reaches the decline. This follows upstream PR anomalyco#54344 (closed unmerged) for upstream issue anomalyco#54180.
1 parent 5cb8fb7 commit 653d353

8 files changed

Lines changed: 129 additions & 5 deletions

File tree

‎packages/core/src/session/execution.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,15 @@ export const layer = Layer.effect(
9090
const session = yield* store.get(sessionID)
9191
if (!session) return yield* Effect.die(new Error(`Session not found: ${sessionID}`))
9292
const result = yield* SessionRunner.Service.use((runner) =>
93-
runner.drain({ sessionID, force, continuation, promotable }),
93+
runner.drain({
94+
sessionID,
95+
force,
96+
continuation,
97+
promotable,
98+
// A declined tool call stops the turn deliberately, so the settle must not read it as an
99+
// unowned teardown: that reason is what keeps the claim and resumes after a restart.
100+
reportDeclined: () => coordinator.stopReason(sessionID, "user"),
101+
}),
94102
).pipe(
95103
instances.provide(session),
96104
Effect.tapCause((cause) =>

‎packages/core/src/session/run-coordinator.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ export interface Coordinator<Key, E, Reason = never> {
2020
* interrupted.
2121
*/
2222
readonly interrupt: (key: Key, reason?: Reason) => Effect.Effect<boolean>
23+
/**
24+
* Names the reason for a stop the drain decides on its own. Such a drain interrupts its own fiber,
25+
* so no caller reaches `interrupt`, and the settle could not tell that stop from an unowned
26+
* teardown. Records the reason only: the drain still interrupts itself, and wakes stay unclaimed.
27+
*/
28+
readonly stopReason: (key: Key, reason: Reason) => Effect.Effect<void>
2329
/** Resolves once no execution is active for the key. Returns immediately when already idle and never starts work. */
2430
readonly awaitIdle: (key: Key) => Effect.Effect<void>
2531
}
@@ -161,6 +167,12 @@ export const make = <Key, E, Reason = never>(options: {
161167
return true
162168
})
163169

170+
const stopReason = (key: Key, reason: Reason) =>
171+
Effect.sync(() => {
172+
const execution = executions.get(key)
173+
if (execution !== undefined) execution.interruptionReason = reason
174+
})
175+
164176
// One execution's `done` already spans coalesced continuations; re-check after it
165177
// settles to cover a successor execution started by a late doorbell.
166178
const awaitIdle = (key: Key): Effect.Effect<void> =>
@@ -170,5 +182,13 @@ export const make = <Key, E, Reason = never>(options: {
170182
return Deferred.await(execution.done).pipe(Effect.ignoreCause, Effect.andThen(awaitIdle(key)))
171183
})
172184

173-
return { active: Effect.sync(() => new Set(executions.keys())), isActive, run, wake, interrupt, awaitIdle }
185+
return {
186+
active: Effect.sync(() => new Set(executions.keys())),
187+
isActive,
188+
run,
189+
wake,
190+
interrupt,
191+
stopReason,
192+
awaitIdle,
193+
}
174194
})

‎packages/core/src/session/runner/index.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ export interface Interface {
3636
readonly continuation?: Continuation
3737
/** "steer" settles the active intent without promoting queued next-turn work. */
3838
readonly promotable?: Promotable
39+
/**
40+
* Reports that the drain is stopping because the user declined a tool call. The drain interrupts
41+
* its own fiber, so it names the stop here; the execution layer then settles a deliberate stop
42+
* that releases its claim instead of resuming the turn at the next server start.
43+
*/
44+
readonly reportDeclined?: () => Effect.Effect<void>
3945
}) => Effect.Effect<DrainResult, RunError>
4046
}
4147

‎packages/core/src/session/runner/llm.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ const layer = Layer.effect(
205205
while (true) {
206206
const next = yield* advanceToStep()
207207
if (next._tag !== "Ready") return next
208-
continuing = yield* runStep(next.context, step)
208+
continuing = yield* runStep(next.context, step, input.reportDeclined)
209209
step++
210210
force = false
211211
entering = false
@@ -220,7 +220,11 @@ const layer = Layer.effect(
220220
})
221221

222222
/** Owns logical Step policy; each attempt owns its streaming, tools, and durable settlement. */
223-
const runStep = Effect.fn("SessionRunner.runStep")(function* (first: SessionContext.Loaded, step: number) {
223+
const runStep = Effect.fn("SessionRunner.runStep")(function* (
224+
first: SessionContext.Loaded,
225+
step: number,
226+
reportDeclined: (() => Effect.Effect<void>) | undefined,
227+
) {
224228
const sessionID = first.session.id
225229
let assistantMessageID = SessionMessage.ID.create()
226230
const retry = yield* SessionRunnerRetry.make(bus, sessionID)
@@ -299,6 +303,7 @@ const layer = Layer.effect(
299303
.pipe(Effect.map((result) => result.status === "completed"))
300304
: Effect.succeed(false),
301305
),
306+
reportDeclined,
302307
})
303308
const completed = yield* SessionStep.Outcome.$match(outcome, {
304309
Completed: (outcome) => Effect.succeed(outcome.needsContinuation),

‎packages/core/src/session/runner/step.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ interface Input {
5757
readonly recoverContinuation: boolean
5858
/** The runner owns compaction policy; the attempt invokes it only before durable output. */
5959
readonly recoverOverflow: Effect.Effect<boolean>
60+
/** Names the stop a declined tool call makes, so settlement releases the turn instead of resuming it. */
61+
readonly reportDeclined?: () => Effect.Effect<void>
6062
}
6163

6264
const TOOLS_INTERRUPTED = { type: "aborted", message: "Tool execution interrupted" } as const
@@ -282,6 +284,9 @@ export const make = Effect.gen(function* () {
282284
if (Exit.isFailure(stream)) return yield* Effect.failCause(stream.cause)
283285
if (tools.declines.length > 0) {
284286
if (input.isLocationClosed()) return Outcome.Completed({ needsContinuation: true })
287+
// A decline is the user's own stop, not a process that vanished: name it here, because
288+
// this fiber interrupts itself and nothing outside the drain can tell the settle why.
289+
if (input.reportDeclined) yield* input.reportDeclined()
285290
return yield* Effect.interrupt
286291
}
287292
if (tools.interrupted && tools.failure) return yield* Effect.failCause(tools.failure)

‎packages/core/test/session-execution.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,45 @@ describe("SessionExecution lifecycle", () => {
142142
}),
143143
)
144144

145+
it.effect("settles a declined tool call as a user stop that never resurrects", () =>
146+
Effect.gen(function* () {
147+
const database = yield* Database.Service
148+
const bus = yield* Bus.Service
149+
const sessionID = Session.ID.make("ses_claim_declined")
150+
yield* seedSessions(database, [sessionID])
151+
152+
const draining = yield* Deferred.make<void>()
153+
const drained: Session.ID[] = []
154+
const interrupted: SessionEvent.Execution.Interrupted[] = []
155+
const scope = yield* Scope.make()
156+
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
157+
// The runner names the stop and then interrupts itself, as a declined Step does.
158+
const context = yield* buildExecution(scope, (input) =>
159+
Effect.suspend(() => {
160+
drained.push(input.sessionID)
161+
const report = input.reportDeclined ?? (() => Effect.void)
162+
return Deferred.succeed(draining, undefined).pipe(Effect.andThen(report()), Effect.andThen(Effect.interrupt))
163+
}),
164+
)
165+
const execution = Context.get(context, SessionExecution.Service)
166+
const restart = Context.get(context, SessionRestart.Service)
167+
yield* bus.project(SessionEvent.Execution.Interrupted, (event) => Effect.sync(() => void interrupted.push(event)))
168+
169+
yield* execution.resume(sessionID).pipe(Effect.forkScoped)
170+
yield* Deferred.await(draining)
171+
yield* execution.awaitIdle(sessionID)
172+
173+
// A decline is the user's own stop: it settles as "user" and releases the claim, where an
174+
// unnamed interrupt reads as "shutdown" and holds the claim for the next server start.
175+
expect(interrupted.map((event) => event.data.reason)).toEqual(["user"])
176+
expect((yield* claims(database))[sessionID]).toBe(false)
177+
178+
// The recovery sweep finds nothing left to resume.
179+
yield* restart.resumeSuspendedSessions
180+
expect(drained).toEqual([sessionID])
181+
}),
182+
)
183+
145184
it.effect("reports an idle interrupt as a no-op", () =>
146185
Effect.gen(function* () {
147186
const sessionID = Session.ID.make("ses_idle_cancel")

‎packages/core/test/session-run-coordinator.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,33 @@ describe("SessionRunCoordinator", () => {
314314
}),
315315
)
316316

317+
it.effect("settles a drain that stops itself with the reason it named, keeping its wakes", () =>
318+
Effect.gen(function* () {
319+
let runs = 0
320+
const reasons: Array<string | undefined> = []
321+
let stop: (key: string) => Effect.Effect<void> = () => Effect.void
322+
const coordinator = yield* SessionRunCoordinator.make<string, never, string>({
323+
drain: (key) => Effect.suspend(() => (++runs === 2 ? stop(key) : Effect.void)),
324+
settled: (_key, _exit, reason) => Effect.sync(() => void reasons.push(reason)),
325+
})
326+
// Work recorded before the stop is a new admission, not part of the stopped intent.
327+
stop = (key) =>
328+
coordinator
329+
.wake(key)
330+
.pipe(Effect.andThen(coordinator.stopReason(key, "user")), Effect.andThen(Effect.interrupt))
331+
332+
// Naming a stop while idle records nothing for a later execution.
333+
yield* coordinator.stopReason("session", "early")
334+
yield* coordinator.run("session")
335+
const exit = yield* coordinator.run("session").pipe(Effect.exit)
336+
yield* coordinator.awaitIdle("session")
337+
338+
expect(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)).toBeTrue()
339+
expect(runs).toBe(3)
340+
expect(reasons).toEqual([undefined, "user", undefined])
341+
}),
342+
)
343+
317344
it.effect("runs a wake registered during interruption cleanup", () =>
318345
Effect.gen(function* () {
319346
const firstStarted = yield* Deferred.make<void>()

‎packages/core/test/session-runner.test.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,8 @@ const makeRunnerState = (compaction?: SessionRunnerModel.Resolved["compaction"])
219219
authorizations: new Array<Tool.Context>(),
220220
executions: new Array<string>(),
221221
closedTransports: new Array<Session.ID>(),
222+
// Sessions whose drain named a declined tool call as its stop, in call order.
223+
declineReports: new Array<Session.ID>(),
222224
blockTools: (count = 1) =>
223225
Effect.acquireRelease(
224226
Effect.all({ started: Deferred.make<void>(), release: Deferred.make<void>() }).pipe(
@@ -446,7 +448,12 @@ const layer = Layer.unwrap(
446448
continuation?: SessionRunner.Continuation,
447449
): Effect.Effect<void, SessionRunner.RunError> {
448450
return sessionRunner
449-
.drain({ sessionID, force, continuation })
451+
.drain({
452+
sessionID,
453+
force,
454+
continuation,
455+
reportDeclined: () => Effect.sync(() => void state.declineReports.push(sessionID)),
456+
})
450457
.pipe(
451458
Effect.flatMap((result) =>
452459
result._tag === "Complete" ? Effect.void : drain(sessionID, false, result.continuation),
@@ -5110,6 +5117,9 @@ describe("SessionRunnerLLM", () => {
51105117

51115118
expect(exit._tag).toBe("Failure")
51125119
if (exit._tag === "Failure") expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true)
5120+
// The step names the stop before interrupting, so settlement can release the declined turn
5121+
// instead of reading the interrupt as an unowned teardown and resuming it after a restart.
5122+
expect(s.declineReports).toEqual([sessionID])
51135123
expect(s.requests).toHaveLength(1)
51145124
expect(yield* s.context).toMatchObject([
51155125
Expected.user("Call declined"),
@@ -5151,6 +5161,8 @@ describe("SessionRunnerLLM", () => {
51515161

51525162
yield* s.resume
51535163

5164+
// Feedback keeps the turn going, so it is no stop at all.
5165+
expect(s.declineReports).toEqual([])
51545166
expect(s.requests).toHaveLength(2)
51555167
expect(yield* s.context).toMatchObject([
51565168
Expected.user("Call corrected"),
@@ -5215,6 +5227,8 @@ describe("SessionRunnerLLM", () => {
52155227

52165228
expect(exit._tag).toBe("Failure")
52175229
if (exit._tag === "Failure") expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true)
5230+
// Dismissing a question is the user's stop too.
5231+
expect(s.declineReports).toEqual([sessionID])
52185232
expect(s.requests).toHaveLength(1)
52195233
expect(yield* s.context).toMatchObject([
52205234
Expected.user("Ask then stop"),

0 commit comments

Comments
 (0)