Skip to content

Commit 663ae8d

Browse files
author
Houman Moallemi
committed
fix(core): honor steered model switches and harden agent delivery
- applySelection gains an applyAgent mode: steered prompts that change the agent still switch the model; only the agent defers to the prompt - admission.steer refuses agent-differing user rows so move-to-steer cannot promote an agent change mid-turn - promotion applies the payload agent only for queued rows, so steered rows can never flip the agent of a running turn - sessions without a stored agent compare against the configured default agent, so SDK sessions still steer prompts carrying it - test fixtures provide the Agent service where prompt admission resolves it
1 parent f325022 commit 663ae8d

8 files changed

Lines changed: 95 additions & 26 deletions

File tree

‎packages/app/src/composer/submit.test.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -209,10 +209,10 @@ describe("Composer submission", () => {
209209

210210
test.each([
211211
// The agent selection rides the admission: the server defers a change to the
212-
// delivery boundary, so a differing selection makes no switch requests now.
212+
// delivery boundary. The model still switches now, as any steered model change does.
213213
{
214214
current: { agent: "plan", model: { id: "old", providerID: "old" } },
215-
calls: ["admit", "send"],
215+
calls: ["admit", "switch-model", "send"],
216216
},
217217
// An unchanged selection sends without a model request to wait on.
218218
{
@@ -223,7 +223,7 @@ describe("Composer submission", () => {
223223
// settles before admission, whose row it would also delete.
224224
{
225225
current: { agent: "plan", model: { id: "old", providerID: "old" }, revert: { messageID: "msg_reverted" } },
226-
calls: ["revert-commit", "admit", "send"],
226+
calls: ["revert-commit", "switch-model", "admit", "send"],
227227
},
228228
])("admits the prompt with its selection before sending one captured value: $calls", async (row) => {
229229
const state = createMemoryComposerState({ prompt: "ship it" }).capture()
@@ -435,9 +435,11 @@ describe("Composer submission", () => {
435435
expect(attempts).toHaveLength(4)
436436
expect(new Set(attempts).size).toBe(1)
437437
// The selection rides the admission, so a retry re-admits the same payload:
438-
// two submissions, each admitted twice (the auto-retry after the failure).
439-
const submitted = ["admit", "send"]
440-
expect(calls).toEqual([...submitted, ...submitted, ...submitted, ...submitted])
438+
// two submissions, each admitted twice (the auto-retry after the failure). The
439+
// retried admission reuses the first commit, so it switches the model only once.
440+
const submitted = ["admit", "switch-model", "send"]
441+
const retried = ["admit", "send"]
442+
expect(calls).toEqual([...submitted, ...retried, ...submitted, ...retried])
441443
expect(statuses).toEqual(["running", "idle", "running", "idle"])
442444
expect(state.current()).toEqual(prompt)
443445
expect(state.context.items()).toMatchObject([
@@ -576,7 +578,7 @@ describe("Composer submission", () => {
576578
const run = running()
577579

578580
await run.submit()
579-
expect(run.calls).toEqual(["admit", "send", "background"])
581+
expect(run.calls).toEqual(["admit", "switch-model", "send", "background"])
580582

581583
await run.submit()
582584
expect(run.calls.filter((call) => call === "background")).toHaveLength(1)

‎packages/app/src/composer/submit.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -534,13 +534,16 @@ async function applySelection(
534534
selection: ComposerSelection,
535535
track?: ModelSelection["trackSessionCommit"],
536536
beforeModel?: () => Promise<void>,
537+
applyAgent = true,
537538
) {
538539
const cancel = track?.(session.id, selection)
539540

540541
try {
541542
const current = session.current()
542543

543-
if (current?.agent !== selection.agent) {
544+
// The agent can also ride the admitted prompt, where the server defers it to
545+
// the delivery boundary; only the model still commits here in that case.
546+
if (applyAgent && current?.agent !== selection.agent) {
544547
await session.api.switchAgent({ sessionID: session.id, agent: selection.agent })
545548
}
546549

@@ -588,7 +591,7 @@ async function sendPrompt(
588591

589592
const agentChanged = session.current()?.agent !== value.selection.agent
590593
const commit = () =>
591-
value.delivery === "steer" && !agentChanged ? applySelection(session, value.selection, track, settle) : settle()
594+
value.delivery === "steer" ? applySelection(session, value.selection, track, settle, !agentChanged) : settle()
592595
// The data layer admits the prompt locally before it commits the selection, so a steer shows as pending while the
593596
// selection commits. A staged revert settles before admission instead: its committed echo removes every local row
594597
// from its boundary on. Only an idle session stages one, and a prompt into it starts work rather than showing as

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

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -259,16 +259,29 @@ export const make = Effect.fn("SessionInbox.make")(function* () {
259259
),
260260
)
261261

262-
const steer = Effect.fn("SessionInbox.steer")((input: PendingRef) =>
263-
publishMutation(
262+
const steer = Effect.fn("SessionInbox.steer")(function* (input: PendingRef) {
263+
const row = yield* find(db, input.id)
264+
if (row?.sessionID === input.sessionID && row.type === "user") {
265+
const payload = decodeUser(row.payload)
266+
const session = yield* db
267+
.select({ agent: SessionTable.agent })
268+
.from(SessionTable)
269+
.where(eq(SessionTable.id, input.sessionID))
270+
.get()
271+
.pipe(Effect.orDie)
272+
// An agent-changing prompt must stay queued: promoting it as a steer would
273+
// apply the selection mid-turn and reconfigure the running turn.
274+
if (payload.agent !== undefined && payload.agent !== (session?.agent ?? undefined)) return
275+
}
276+
yield* publishMutation(
264277
input,
265278
bus.publish(SessionEvent.InboxDeliveryChanged, {
266279
sessionID: input.sessionID,
267280
inboxID: input.id,
268281
delivery: "steer",
269282
}),
270-
),
271-
)
283+
)
284+
})
272285

273286
const queue = Effect.fn("SessionInbox.queue")((input: PendingRef) =>
274287
publishMutation(
@@ -546,8 +559,10 @@ const publish = Effect.fn("SessionInbox.publish")(function* (
546559
return Effect.die(new LifecycleConflict({ id: row.id }))
547560
return Effect.gen(function* () {
548561
// Promotion is a turn boundary, the only safe point to apply a prompt's agent
549-
// selection: the projector persists it before the message becomes visible.
550-
if (row.type === "user") {
562+
// selection: the projector persists it before the message becomes visible. Only
563+
// queued rows apply it — a steered row delivers into the running turn, whose
564+
// agent must not change mid-flight.
565+
if (row.type === "user" && row.delivery === "queue") {
551566
const payload = decodeUser(row.payload)
552567
if (payload.agent) {
553568
const session = yield* db

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

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
export * as Session from "./session.js"
22

33
import { DateTime, Effect, Fiber, Scope } from "effect"
4-
import type { Agent } from "@opencode/schema/agent"
4+
import { Agent } from "../agent.js"
55
import type { Model } from "@opencode/schema/model"
66
import type { Permission } from "@opencode/schema/permission"
77
import { Event } from "@opencode/schema/event"
@@ -157,22 +157,28 @@ export const make = Effect.fn("Session.make")(function* () {
157157
Effect.gen(function* () {
158158
const session = yield* get(sessionID)
159159
const messageID = input.id ?? SessionMessage.ID.create()
160-
// A prompt that selects a different agent must never deliver mid-turn: an agent
161-
// change reconfigures permissions and tools, which is only safe at a turn boundary.
162-
// Queueing it defers the selection to the idle boundary where promotion applies it.
163-
const request =
164-
input.agent !== undefined && input.agent !== session.agent ? { ...input, delivery: "queue" as const } : input
165160
const admitted = yield* Effect.gen(function* () {
166161
const existing = yield* admission.reconcile({
167162
id: messageID,
168163
sessionID: session.id,
169164
type: "user",
170-
delivery: request.delivery ?? "steer",
165+
delivery: input.delivery ?? "steer",
171166
})
172167
if (existing) return existing
173168
// Preparation, the staged revert commit and admission share one acquisition of the session's location
174169
// services, so projections see its config whoever called prompt.
175170
return yield* Effect.gen(function* () {
171+
// A prompt that selects a different agent must never deliver mid-turn: an agent
172+
// change reconfigures permissions and tools, which is only safe at a turn boundary.
173+
// Queueing it defers the selection to the idle boundary where promotion applies it.
174+
// Sessions without a stored agent compare against the configured default, so SDK
175+
// sessions still steer prompts carrying that default.
176+
const agents = yield* Agent.Service
177+
const effective = session.agent ?? (yield* agents.select()).id
178+
const request =
179+
input.agent !== undefined && input.agent !== effective
180+
? { ...input, delivery: "queue" as const }
181+
: input
176182
const item = yield* restore(SessionPrompt.prepare({ session, messageID, input: request }))
177183
// Commit a staged revert only after preparation succeeds, before admitting new work.
178184
if (session.revert) yield* SessionRevert.commit(bus, session)

‎packages/core/test/fixture/prompt-location.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { FileSystem } from "@opencode/core/filesystem"
2+
import { Agent } from "@opencode/core/agent"
23
import { Bus } from "@opencode/core/bus"
34
import { Image } from "@opencode/core/image"
45
import { LocationServiceMap } from "@opencode/core/location-service-map"
@@ -20,7 +21,7 @@ export const promptLocationNode = makeGlobalNode({
2021
const bus = yield* Bus.Service
2122
return yield* LayerMap.make(
2223
(_ref: Location.Ref) =>
23-
LayerNode.compile(LayerNode.group([PluginHooks.node, Image.node, Skill.node, Plugin.node]), {
24+
LayerNode.compile(LayerNode.group([PluginHooks.node, Image.node, Skill.node, Plugin.node, Agent.node]), {
2425
replacements: [
2526
Bus.node.replace(Layer.succeed(Bus.Service, bus)),
2627
Plugin.node.replace(Layer.mock(Plugin.Service, { awaitActivation: Effect.void })),

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

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { describe, expect } from "bun:test"
22
import { and, eq } from "drizzle-orm"
33
import { Cause, Context, DateTime, Deferred, Effect, Exit, Fiber, Layer, Scope } from "effect"
4-
import { Agent } from "@opencode/schema/agent"
4+
import { Agent } from "@opencode/core/agent"
55
import { Event } from "@opencode/schema/event"
66
import { Model } from "@opencode/schema/model"
77
import { Money } from "@opencode/schema/money"
@@ -137,6 +137,10 @@ const setup = Effect.fnUntraced(function* (options?: {
137137
get: (id) => Effect.succeed(id === skillInfo.id ? skillInfo : undefined),
138138
}),
139139
options?.snapshot?.(ref) ?? Layer.mock(Snapshot.Service, {}),
140+
// Prompt admission resolves the effective agent through the location services.
141+
Layer.mock(Agent.Service, {
142+
select: (id) => Effect.succeed({ id: id ?? Agent.ID.make("build"), info: undefined }),
143+
}),
140144
Layer.mock(Plugin.Service, {
141145
awaitActivation: Effect.sync(() => {
142146
activationWaits.push(ref)

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

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ const locations = makeGlobalNode({
9090
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
9191
Layer.mergeAll(
9292
ref.directory === mediaDirectory ? mediaBlob : Layer.empty,
93-
LayerNode.compile(LayerNode.group([PluginHooks.node, Skill.node]), {
93+
LayerNode.compile(LayerNode.group([PluginHooks.node, Skill.node, Agent.node]), {
9494
replacements: [Bus.node.replace(Layer.succeed(Bus.Service, bus))],
9595
}),
9696
Layer.mock(Image.Service, {
@@ -768,6 +768,22 @@ describe("Session.prompt", () => {
768768
}),
769769
)
770770

771+
it.effect("steers a prompt carrying the default agent into a session without a stored agent", () =>
772+
Effect.gen(function* () {
773+
yield* setup
774+
const session = yield* Session.Service
775+
776+
const same = yield* session.prompt({
777+
sessionID,
778+
text: "Steer the turn",
779+
agent: Agent.ID.make("build"),
780+
resume: false,
781+
})
782+
783+
expect(same).toMatchObject({ type: "user", delivery: "steer" })
784+
}),
785+
)
786+
771787
it.effect("wakes execution when an exact prompt retry recovers a committed message", () =>
772788
Effect.gen(function* () {
773789
yield* setup
@@ -1326,4 +1342,25 @@ describe("Session.inbox", () => {
13261342
expect(yield* eventCount(Bus.versionedType(SessionEvent.InboxCancelled.type, 1))).toBe(1)
13271343
}),
13281344
)
1345+
1346+
it.effect("keeps an agent-changing prompt queued when it is steered", () =>
1347+
Effect.gen(function* () {
1348+
yield* setup
1349+
const session = yield* Session.Service
1350+
const queued = yield* session.prompt({
1351+
sessionID,
1352+
text: "Follow up as reviewer",
1353+
agent: Agent.ID.make("reviewer"),
1354+
resume: false,
1355+
})
1356+
expect(queued).toMatchObject({ delivery: "queue" })
1357+
1358+
yield* session.steerInbox({ sessionID, inboxID: queued.id })
1359+
1360+
// Steered promotion would apply the selection mid-turn, so the row stays
1361+
// queued and its agent applies at the idle boundary instead.
1362+
expect(yield* session.inbox(sessionID)).toMatchObject([{ id: queued.id, delivery: "queue" }])
1363+
expect(yield* eventCount(Bus.versionedType(SessionEvent.InboxDeliveryChanged.type, 1))).toBe(0)
1364+
}),
1365+
)
13291366
})

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import path from "path"
33
import { describe, expect } from "bun:test"
44
import { Duration, Effect, Layer, LayerMap } from "effect"
55
import { Database } from "@opencode/core/database/database"
6+
import { Agent } from "@opencode/core/agent"
67
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
78
import { LayerNode } from "@opencode/util/effect/layer-node"
89
import { makeGlobalNode } from "@opencode/util/effect/app-node"
@@ -58,7 +59,7 @@ const locations = makeGlobalNode({
5859
).pipe(
5960
Layer.provideMerge(
6061
LayerNode.compile(
61-
LayerNode.group([PluginHooks.node, Image.node, Skill.node, Config.node, ManagedPolicy.node]),
62+
LayerNode.group([PluginHooks.node, Image.node, Skill.node, Config.node, ManagedPolicy.node, Agent.node]),
6263
{
6364
replacements: [
6465
Config.node.replace(Config.testLayer()),

0 commit comments

Comments
 (0)