Skip to content

Commit 5842081

Browse files
committed
fix(tui): keep the model selector on the session's model when the loaded page has no user message
The prompt copied a session's model from its last user message once per session switch, and did nothing when none was loaded. A long agent run leaves only assistant messages in the first page, so the selector kept the previous session's model. Fall back to the newest assistant message, and stay unsynced until the model is actually applied so a session opened before its provider's models load still gets it.
1 parent 76006a0 commit 5842081

3 files changed

Lines changed: 90 additions & 24 deletions

File tree

‎packages/tui/src/component/prompt/index.tsx‎

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { createEffect, createMemo, onMount, createSignal, onCleanup, on, Show, S
1313
import { registerOpencodeSpinner } from "../register-spinner"
1414
import path from "path"
1515
import { fileURLToPath } from "url"
16-
import { useLocal } from "../../context/local"
16+
import { lastRunConfig, useLocal } from "../../context/local"
1717
import { Flag } from "@opencode-ai/core/flag/flag"
1818
import { tint, useTheme } from "../../context/theme"
1919
import { EmptyBorder, SplitBorder } from "../../ui/border"
@@ -308,27 +308,28 @@ export function Prompt(props: PromptProps) {
308308
),
309309
)
310310

311-
// Initialize agent/model/variant from last user message when session changes
311+
// Initialize agent/model/variant from the session's last run when the session changes.
312+
// Stays unsynced until the model is actually applied, so a session opened before its provider's
313+
// models or its messages have loaded does not keep the previous session's model.
312314
let syncedSessionID: string | undefined
313315
createEffect(() => {
314316
const sessionID = props.sessionID
315-
const msg = lastUserMessage()
317+
const last = sessionID ? lastRunConfig(sync.data.message[sessionID] ?? []) : undefined
316318

317319
if (sessionID !== syncedSessionID) {
318-
if (!sessionID || !msg) return
319-
320-
syncedSessionID = sessionID
320+
if (!sessionID || !last) return
321321

322322
// Only set agent if it's a primary agent (not a subagent)
323-
const isPrimaryAgent = local.agent.list().some((x) => x.name === msg.agent)
324-
if (msg.agent && isPrimaryAgent) {
325-
// Keep command line --agent if specified.
326-
if (!args.agent) local.agent.set(msg.agent)
327-
if (msg.model) {
328-
local.model.set(msg.model)
329-
local.model.variant.set(msg.model.variant)
330-
}
323+
const isPrimaryAgent = local.agent.list().some((x) => x.name === last.agent)
324+
if (!last.agent || !isPrimaryAgent) {
325+
syncedSessionID = sessionID
326+
return
331327
}
328+
// Keep command line --agent if specified.
329+
if (!args.agent) local.agent.set(last.agent)
330+
if (!local.model.set(last.model, { silent: true })) return
331+
local.model.variant.set(last.variant)
332+
syncedSessionID = sessionID
332333
}
333334
})
334335

‎packages/tui/src/context/local.tsx‎

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { useTheme } from "./theme"
1313
import { useToast } from "../ui/toast"
1414
import { useRoute } from "./route"
1515
import { usePermission } from "./permission"
16+
import type { AssistantMessage, UserMessage } from "@opencode-ai/sdk/v2"
1617

1718
export type LocalTheme = {
1819
secondary: RGBA
@@ -48,6 +49,24 @@ export function recentModels(
4849
.map((item) => ({ providerID: item.providerID, modelID: item.modelID }))
4950
}
5051

52+
/**
53+
* The agent, model and variant a session last ran with. A long agent run can leave only assistant
54+
* messages in the loaded page, so fall back to the newest one; compaction summaries run on their own model.
55+
*/
56+
export function lastRunConfig(messages: readonly (UserMessage | AssistantMessage)[]) {
57+
const user = messages.findLast((message): message is UserMessage => message.role === "user")
58+
if (user) return { agent: user.agent, model: user.model, variant: user.model.variant }
59+
const assistant = messages.findLast(
60+
(message): message is AssistantMessage => message.role === "assistant" && !message.summary,
61+
)
62+
if (!assistant) return undefined
63+
return {
64+
agent: assistant.agent,
65+
model: { providerID: assistant.providerID, modelID: assistant.modelID },
66+
variant: assistant.variant,
67+
}
68+
}
69+
5170
export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
5271
name: "Local",
5372
init: () => {
@@ -317,23 +336,25 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
317336
setModelStore("recent", recentModels(next, modelStore.recent))
318337
save()
319338
},
320-
set(model: { providerID: string; modelID: string }, options?: { recent?: boolean }) {
321-
batch(() => {
339+
set(model: { providerID: string; modelID: string }, options?: { recent?: boolean; silent?: boolean }) {
340+
return batch(() => {
322341
if (!isModelValid(model)) {
323-
toast.show({
324-
message: `Model ${model.providerID}/${model.modelID} is not valid`,
325-
variant: "warning",
326-
duration: 3000,
327-
})
328-
return
342+
if (!options?.silent)
343+
toast.show({
344+
message: `Model ${model.providerID}/${model.modelID} is not valid`,
345+
variant: "warning",
346+
duration: 3000,
347+
})
348+
return false
329349
}
330350
const a = agent.current()
331-
if (!a) return
351+
if (!a) return false
332352
setModelStore("model", a.name, model)
333353
if (options?.recent) {
334354
setModelStore("recent", recentModels(model, modelStore.recent))
335355
save()
336356
}
357+
return true
337358
})
338359
},
339360
toggleFavorite(model: { providerID: string; modelID: string }) {

‎packages/tui/test/context/local.test.ts‎

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,49 @@
11
import { expect, test } from "bun:test"
2-
import { parseModel, recentModels } from "../../src/context/local"
2+
import type { AssistantMessage, UserMessage } from "@opencode-ai/sdk/v2"
3+
import { lastRunConfig, parseModel, recentModels } from "../../src/context/local"
4+
5+
const user = (model: string, time: number) =>
6+
({
7+
role: "user",
8+
agent: "build",
9+
time: { created: time },
10+
model: { ...parseModel(model), variant: "high" },
11+
}) as UserMessage
12+
13+
const assistant = (model: string, time: number, extra: Partial<AssistantMessage> = {}) =>
14+
({
15+
role: "assistant",
16+
agent: "build",
17+
time: { created: time },
18+
...parseModel(model),
19+
variant: "low",
20+
...extra,
21+
}) as unknown as AssistantMessage
22+
23+
test("last run config follows the newest user message", () => {
24+
expect(
25+
lastRunConfig([user("a/one", 1), assistant("a/one", 2), user("cursor/sonnet", 3), assistant("a/one", 4)]),
26+
).toEqual({
27+
agent: "build",
28+
model: { providerID: "cursor", modelID: "sonnet", variant: "high" },
29+
variant: "high",
30+
})
31+
})
32+
33+
test("last run config falls back to the newest assistant message when no user message is loaded", () => {
34+
expect(
35+
lastRunConfig([
36+
assistant("cursor/sonnet", 1),
37+
assistant("cursor/sonnet", 2),
38+
assistant("openai/luna", 3, { summary: true, agent: "compaction" }),
39+
]),
40+
).toEqual({
41+
agent: "build",
42+
model: { providerID: "cursor", modelID: "sonnet" },
43+
variant: "low",
44+
})
45+
expect(lastRunConfig([])).toBeUndefined()
46+
})
347

448
test("parses model IDs containing slashes", () => {
549
expect(parseModel("provider/family/model")).toEqual({

0 commit comments

Comments
 (0)