Skip to content

Commit 8997be2

Browse files
iceteaSAsjawhar
andcommitted
fix(session): preserve agent and model on injected prompts without explicit fields
An injected prompt omitting agent/model falls back to the default agent’s configured model, silently switching the session and busting the provider cache prefix. createUserMessage reads the durable session row and the last agent-carrying user message before falling back to defaults; a genuine agent switch still adopts the new agent’s model, and variant is preserved on the same precedence. Revives the fix from anomalyco#35195 (closed by the inactivity bot, unmerged), extended to also preserve the session variant and to only adopt the new agent’s model on a genuine agent switch. Co-authored-by: Sami Jawhar <[email protected]>
1 parent 7cb044e commit 8997be2

2 files changed

Lines changed: 279 additions & 6 deletions

File tree

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -633,7 +633,18 @@ const layer = Layer.effect(
633633
})
634634

635635
const createUserMessage = Effect.fn("SessionPrompt.createUserMessage")(function* (input: PromptInput) {
636-
const agentName = input.agent
636+
// The durable session row survives compaction and records the current
637+
// agent/model, so synthetic prompts that omit either field do not fall
638+
// back to configured defaults.
639+
const current = yield* sessions.get(input.sessionID).pipe(Effect.orDie)
640+
const prev =
641+
input.agent || current.agent
642+
? undefined
643+
: (yield* MessageV2.filterCompactedEffect(input.sessionID).pipe(Effect.provideService(Database.Service, database))).findLast(
644+
(m): m is SessionV1.WithParts & { info: SessionV1.User } =>
645+
m.info.role === "user" && !!m.info.agent,
646+
)
647+
const agentName = input.agent ?? current.agent ?? prev?.info.agent
637648
const ag = agentName ? yield* agents.get(agentName) : yield* agents.defaultInfo()
638649
if (!ag) {
639650
const available = (yield* agents.list()).filter((a) => !a.hidden).map((a) => a.name)
@@ -643,15 +654,27 @@ const layer = Layer.effect(
643654
throw error
644655
}
645656

646-
const model = input.model ?? ag.model ?? (yield* currentModel(input.sessionID))
657+
// A genuine agent switch gets the new agent's configured model; an
658+
// injected prompt for the current agent keeps the session model.
659+
const switched = !!current.agent && ag.name !== current.agent
660+
const sessionModel =
661+
!switched && current.model
662+
? {
663+
providerID: ProviderV2.ID.make(current.model.providerID),
664+
modelID: ModelV2.ID.make(current.model.id),
665+
variant: current.model.variant === "default" ? undefined : current.model.variant,
666+
}
667+
: undefined
668+
const model = input.model ?? sessionModel ?? prev?.info.model ?? ag.model ?? (yield* currentModel(input.sessionID))
647669
const same = ag.model && model.providerID === ag.model.providerID && model.modelID === ag.model.modelID
648670
const full =
649671
!input.variant && ag.variant && same
650672
? yield* provider
651673
.getModel(model.providerID, model.modelID)
652674
.pipe(Effect.catchIf(Provider.ModelNotFoundError.isInstance, () => Effect.succeed(undefined)))
653675
: undefined
654-
const variant = input.variant ?? (ag.variant && full?.variants?.[ag.variant] ? ag.variant : undefined)
676+
const modelVariant = model === sessionModel ? sessionModel.variant : model === prev?.info.model ? prev.info.model.variant : undefined
677+
const variant = input.variant ?? modelVariant ?? (ag.variant && full?.variants?.[ag.variant] ? ag.variant : undefined)
655678

656679
const info: SessionV1.User = {
657680
id: input.messageID ?? MessageID.ascending(),
@@ -669,7 +692,6 @@ const layer = Layer.effect(
669692
format: input.format,
670693
}
671694

672-
const current = yield* sessions.get(input.sessionID).pipe(Effect.orDie)
673695
if (
674696
current.agent !== info.agent ||
675697
current.model?.providerID !== info.model.providerID ||

‎packages/opencode/test/session/prompt.test.ts‎

Lines changed: 253 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import { SystemPrompt } from "../../src/session/system"
4646
import { Shell } from "@opencode-ai/core/shell"
4747
import { Snapshot } from "../../src/snapshot"
4848
import { ToolRegistry } from "@/tool/registry"
49+
import { TaskTool, type TaskPromptOps } from "../../src/tool/task"
4950
import { Truncate } from "@/tool/truncate"
5051
import { CrossSpawnSpawner } from "@opencode-ai/core/cross-spawn-spawner"
5152
import { Ripgrep } from "@opencode-ai/core/ripgrep"
@@ -165,6 +166,7 @@ const blockingProcessor = Layer.succeed(
165166
)
166167

167168
const runtimeFlags = RuntimeFlags.layer({ experimentalEventSystem: true })
169+
const backgroundRuntimeFlags = RuntimeFlags.layer({ experimentalEventSystem: true, experimentalBackgroundSubagents: true })
168170

169171
const testLLMServerNode = LayerNode.make({ service: TestLLMServer, layer: TestLLMServer.layer, deps: [] })
170172

@@ -208,12 +210,18 @@ const promptRoot = LayerNode.group([
208210
RuntimeFlags.node,
209211
])
210212

211-
function makePrompt(input?: { mcpInstructions?: MCP.ServerInstructions[]; processor?: "blocking" }) {
213+
type PromptTestInput = {
214+
mcpInstructions?: MCP.ServerInstructions[]
215+
processor?: "blocking"
216+
runtimeFlags?: Layer.Layer<RuntimeFlags.Service>
217+
}
218+
219+
function makePrompt(input?: PromptTestInput) {
212220
const replacements = [
213221
[SessionSummary.node, summary],
214222
[LSP.node, lsp],
215223
[MCP.node, makeMcp(input?.mcpInstructions)],
216-
[RuntimeFlags.node, runtimeFlags],
224+
[RuntimeFlags.node, input?.runtimeFlags ?? runtimeFlags],
217225
] as const
218226
if (input?.processor === "blocking") {
219227
return LayerNode.compile(promptRoot, [...replacements, [SessionProcessor.node, blockingProcessor]])
@@ -241,6 +249,9 @@ function makeHttpNoLLMServer(input?: { mcpInstructions?: MCP.ServerInstructions[
241249

242250
const it = testEffect(makeHttp())
243251
const noLLMServer = testEffect(makeHttpNoLLMServer())
252+
const backgroundNoLLMServer = testEffect(
253+
makePrompt({ runtimeFlags: backgroundRuntimeFlags }) as unknown as Layer.Layer<any, any, never>,
254+
)
244255
const raceNoLLMServer = testEffect(makeHttpNoLLMServer({ processor: "blocking" }))
245256
const withMcpInstructions = testEffect(
246257
makeHttp({
@@ -2333,6 +2344,7 @@ noLLMServer.instance(
23332344
const match = yield* prompt.prompt({
23342345
sessionID: session.id,
23352346
agent: "build",
2347+
model: ref,
23362348
noReply: true,
23372349
parts: [{ type: "text", text: "hello again" }],
23382350
})
@@ -2468,3 +2480,242 @@ noLLMServer.instance(
24682480
}),
24692481
30_000,
24702482
)
2483+
2484+
// Agent/model preservation
2485+
2486+
noLLMServer.instance(
2487+
"prompt without agent and model preserves current session agent and model",
2488+
() =>
2489+
Effect.gen(function* () {
2490+
const prompt = yield* SessionPrompt.Service
2491+
const sessions = yield* Session.Service
2492+
const session = yield* sessions.create({})
2493+
2494+
yield* prompt.prompt({
2495+
sessionID: session.id,
2496+
agent: "build",
2497+
model: ref,
2498+
noReply: true,
2499+
parts: [{ type: "text", text: "hello" }],
2500+
})
2501+
2502+
const next = yield* prompt.prompt({
2503+
sessionID: session.id,
2504+
noReply: true,
2505+
parts: [{ type: "text", text: "hello again" }],
2506+
})
2507+
if (next.info.role !== "user") throw new Error("expected user message")
2508+
expect(next.info.agent).toBe("build")
2509+
expect(next.info.model).toEqual(ref)
2510+
2511+
yield* sessions.remove(session.id)
2512+
}),
2513+
{
2514+
config: {
2515+
...cfg,
2516+
default_agent: "plan",
2517+
},
2518+
},
2519+
)
2520+
2521+
noLLMServer.instance(
2522+
"explicit agent without model keeps the session's current model",
2523+
() =>
2524+
Effect.gen(function* () {
2525+
const prompt = yield* SessionPrompt.Service
2526+
const sessions = yield* Session.Service
2527+
const session = yield* sessions.create({})
2528+
2529+
yield* prompt.prompt({
2530+
sessionID: session.id,
2531+
agent: "build",
2532+
model: { providerID: ProviderV2.ID.make("opencode"), modelID: ModelV2.ID.make("kimi-k2.5-free") },
2533+
noReply: true,
2534+
parts: [{ type: "text", text: "hello" }],
2535+
})
2536+
2537+
const next = yield* prompt.prompt({
2538+
sessionID: session.id,
2539+
agent: "build",
2540+
noReply: true,
2541+
parts: [{ type: "text", text: "notification" }],
2542+
})
2543+
if (next.info.role !== "user") throw new Error("expected user message")
2544+
expect(next.info.agent).toBe("build")
2545+
expect(next.info.model.providerID).toBe(ProviderV2.ID.make("opencode"))
2546+
expect(next.info.model.modelID).toBe(ModelV2.ID.make("kimi-k2.5-free"))
2547+
2548+
yield* sessions.remove(session.id)
2549+
}),
2550+
{
2551+
config: {
2552+
...cfg,
2553+
agent: {
2554+
build: {
2555+
model: "test/test-model",
2556+
},
2557+
},
2558+
},
2559+
},
2560+
)
2561+
2562+
noLLMServer.instance(
2563+
"explicit agent switch without model uses the new agent's model",
2564+
() =>
2565+
Effect.gen(function* () {
2566+
const prompt = yield* SessionPrompt.Service
2567+
const sessions = yield* Session.Service
2568+
const session = yield* sessions.create({})
2569+
2570+
yield* prompt.prompt({
2571+
sessionID: session.id,
2572+
agent: "build",
2573+
model: { providerID: ProviderV2.ID.make("opencode"), modelID: ModelV2.ID.make("kimi-k2.5-free") },
2574+
noReply: true,
2575+
parts: [{ type: "text", text: "hello" }],
2576+
})
2577+
2578+
const next = yield* prompt.prompt({
2579+
sessionID: session.id,
2580+
agent: "plan",
2581+
noReply: true,
2582+
parts: [{ type: "text", text: "switch" }],
2583+
})
2584+
if (next.info.role !== "user") throw new Error("expected user message")
2585+
expect(next.info.agent).toBe("plan")
2586+
expect(next.info.model.providerID).toBe(ProviderV2.ID.make("test"))
2587+
expect(next.info.model.modelID).toBe(ModelV2.ID.make("test-model"))
2588+
2589+
yield* sessions.remove(session.id)
2590+
}),
2591+
{
2592+
config: {
2593+
...cfg,
2594+
agent: {
2595+
plan: {
2596+
model: "test/test-model",
2597+
},
2598+
},
2599+
},
2600+
},
2601+
)
2602+
2603+
noLLMServer.instance(
2604+
"prompt without agent, model, and variant preserves the current variant",
2605+
() =>
2606+
Effect.gen(function* () {
2607+
const prompt = yield* SessionPrompt.Service
2608+
const sessions = yield* Session.Service
2609+
const session = yield* sessions.create({})
2610+
2611+
yield* prompt.prompt({
2612+
sessionID: session.id,
2613+
agent: "build",
2614+
model: ref,
2615+
variant: "xhigh",
2616+
noReply: true,
2617+
parts: [{ type: "text", text: "hello" }],
2618+
})
2619+
2620+
const next = yield* prompt.prompt({
2621+
sessionID: session.id,
2622+
noReply: true,
2623+
parts: [{ type: "text", text: "hello again" }],
2624+
})
2625+
if (next.info.role !== "user") throw new Error("expected user message")
2626+
expect(next.info.agent).toBe("build")
2627+
expect(next.info.model).toEqual({ ...ref, variant: "xhigh" })
2628+
2629+
yield* sessions.remove(session.id)
2630+
}),
2631+
{
2632+
config: {
2633+
...cfg,
2634+
provider: {
2635+
...cfg.provider,
2636+
test: {
2637+
...cfg.provider.test,
2638+
models: {
2639+
"test-model": {
2640+
...cfg.provider.test.models["test-model"],
2641+
variants: { xhigh: {}, high: {} },
2642+
},
2643+
},
2644+
},
2645+
},
2646+
default_agent: "plan",
2647+
},
2648+
},
2649+
)
2650+
2651+
backgroundNoLLMServer.instance(
2652+
"background completion injection preserves the parent session model",
2653+
() =>
2654+
Effect.gen(function* () {
2655+
const prompt = yield* SessionPrompt.Service
2656+
const sessions = yield* Session.Service
2657+
const parent = yield* sessions.create({ permission: [{ permission: "*", pattern: "*", action: "allow" }] })
2658+
const seeded = yield* seed(parent.id)
2659+
yield* sessions.setAgentModel({
2660+
sessionID: parent.id,
2661+
agent: "build",
2662+
model: { id: ref.modelID, providerID: ref.providerID, variant: "default" },
2663+
time: Date.now(),
2664+
})
2665+
2666+
const taskInfo = yield* TaskTool
2667+
const task = yield* taskInfo.init()
2668+
const promptOps: TaskPromptOps = {
2669+
cancel: () => Effect.void,
2670+
resolvePromptParts: () => Effect.succeed([{ type: "text", text: "child prompt" }]),
2671+
prompt: (input) => prompt.prompt({ ...input, noReply: true }).pipe(Effect.orDie),
2672+
}
2673+
2674+
yield* task.execute(
2675+
{
2676+
description: "background completion",
2677+
prompt: "child prompt",
2678+
subagent_type: "build",
2679+
background: true,
2680+
},
2681+
{
2682+
sessionID: parent.id,
2683+
messageID: seeded.assistant.id,
2684+
agent: "build",
2685+
abort: new AbortController().signal,
2686+
messages: [],
2687+
metadata: () => Effect.void,
2688+
ask: () => Effect.void,
2689+
extra: { bypassAgentCheck: true, promptOps },
2690+
},
2691+
)
2692+
2693+
const injected = yield* pollWithTimeout(
2694+
Effect.gen(function* () {
2695+
const messages = yield* sessions.messages({ sessionID: parent.id })
2696+
const match = messages.findLast(
2697+
(message) =>
2698+
message.info.role === "user" &&
2699+
message.parts.some((part) => part.type === "text" && part.synthetic === true),
2700+
)
2701+
if (match?.info.role === "user") return match
2702+
}),
2703+
"timed out waiting for background completion injection",
2704+
)
2705+
2706+
if (injected.info.role !== "user") throw new Error("expected user message")
2707+
expect(injected.info.agent).toBe("build")
2708+
expect(injected.info.model).toEqual(ref)
2709+
}),
2710+
{
2711+
config: {
2712+
...cfg,
2713+
agent: {
2714+
build: {
2715+
model: "test/other-model",
2716+
},
2717+
},
2718+
},
2719+
},
2720+
10_000,
2721+
)

0 commit comments

Comments
 (0)