Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
56 changes: 56 additions & 0 deletions packages/app/src/context/local.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { beforeAll, describe, expect, mock, test } from "bun:test"
import type {
createModelActions as CreateModelActions,
localSavedStoreKey as LocalSavedStoreKey,
localPersistReadyForAction as LocalPersistReadyForAction,
pruneLocalSavedStores as PruneLocalSavedStores,
shouldRestoreLocalSessionModel as ShouldRestoreLocalSessionModel,
} from "./local"

let createModelActions: typeof CreateModelActions
let localSavedStoreKey: typeof LocalSavedStoreKey
let localPersistReadyForAction: typeof LocalPersistReadyForAction
let pruneLocalSavedStores: typeof PruneLocalSavedStores
Expand All @@ -18,6 +20,7 @@ beforeAll(async () => {
}))

const mod = await import("./local")
createModelActions = mod.createModelActions
localSavedStoreKey = mod.localSavedStoreKey
localPersistReadyForAction = mod.localPersistReadyForAction
pruneLocalSavedStores = mod.pruneLocalSavedStores
Expand Down Expand Up @@ -99,3 +102,56 @@ describe("pruneLocalSavedStores", () => {
expect(disposed).toEqual(["oldest"])
})
})

describe("createModelActions recent-model wiring", () => {
// Two connected models, the first "current" — enough to exercise set() and
// cycle() without standing up the Local context.
function setup() {
const calls = {
recordRecent: [] as Array<{ providerID: string; modelID: string }>,
pushRecent: [] as Array<{ providerID: string; modelID: string }>,
write: [] as Array<{ providerID: string; modelID: string } | undefined>,
}
const recent = [
{ provider: { id: "anthropic" }, id: "claude" },
{ provider: { id: "openai" }, id: "gpt" },
]
const actions = createModelActions({
batch: <T>(fn: () => T): T => fn(),
recordLast: () => {},
write: (item) => calls.write.push(item),
setVisibility: () => {},
pushRecent: (item) => calls.pushRecent.push(item),
recordRecent: async (ref) => {
calls.recordRecent.push(ref)
},
recent: () => recent,
current: () => recent[0],
})
return { actions, calls }
}

test("an explicit pick mirrors the choice to the server's recent-model default", () => {
const { actions, calls } = setup()
actions.set({ providerID: "anthropic", modelID: "claude" }, { recent: true })
expect(calls.recordRecent).toEqual([{ providerID: "anthropic", modelID: "claude" }])
expect(calls.pushRecent).toEqual([{ providerID: "anthropic", modelID: "claude" }])
})

test("a non-recent set (programmatic / agent-pinned) never touches the server default", () => {
const { actions, calls } = setup()
actions.set({ providerID: "anthropic", modelID: "claude" })
expect(calls.recordRecent).toEqual([])
expect(calls.pushRecent).toEqual([])
// the selection is still applied locally — it just isn't promoted to default
expect(calls.write).toEqual([{ providerID: "anthropic", modelID: "claude" }])
})

test("cycling between recent models never re-records the default", () => {
const { actions, calls } = setup()
actions.cycle(1)
expect(calls.recordRecent).toEqual([])
// cycle still moved the selection on to the next recent model
expect(calls.write).toEqual([{ providerID: "openai", modelID: "gpt" }])
})
})
106 changes: 71 additions & 35 deletions packages/app/src/context/local.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { createSimpleContext } from "@opencode-ai/ui/context"
import { base64Encode } from "@opencode-ai/util/encode"
import { useParams } from "@solidjs/router"
Expand Down Expand Up @@ -104,6 +104,58 @@
return directory || undefined
}

// The model picker's set/cycle wiring, extracted so local.test.ts can assert it
// without standing up the whole context. The one rule worth pinning: only an
// explicit pick — set(item, { recent: true }) — mirrors the choice to the
// server's recent-model default; a plain set() and cycle() (which routes through
// set with no options) never do, so an agent's pinned model or a programmatic
// switch can't leak into a model-less session's default.
type ModelEntry = { provider: { id: string }; id: string }
export function createModelActions(deps: {
batch: <T>(fn: () => T) => T
recordLast: (item: ModelKey | undefined) => void
write: (item: ModelKey | undefined) => void
setVisibility: (item: ModelKey) => void
pushRecent: (item: ModelKey) => void
recordRecent: (ref: { providerID: string; modelID: string }) => Promise<unknown>
recent: () => Array<ModelEntry | undefined>
current: () => ModelEntry | undefined
}) {
const set = (item: ModelKey | undefined, options?: { recent?: boolean }) => {
deps.batch(() => {
deps.recordLast(item)
deps.write(item)
if (!item) return
deps.setVisibility(item)
if (!options?.recent) return
deps.pushRecent(item)
// Mirror an explicit pick to the server's recent-model default so a
// model-less session (e.g. a Telegram /new) inherits the user's actual
// choice. Best-effort: a failure here must not disrupt the pick.
void deps.recordRecent({ providerID: item.providerID, modelID: item.modelID }).catch(() => {})
})
}

const cycle = (direction: 1 | -1) => {
const items = deps.recent()
const item = deps.current()
if (!item) return

const index = items.findIndex((entry) => entry?.provider.id === item.provider.id && entry?.id === item.id)
if (index === -1) return

let next = index + direction
if (next < 0) next = items.length - 1
if (next >= items.length) next = 0

const entry = items[next]
if (!entry) return
set({ providerID: entry.provider.id, modelID: entry.id })
}

return { set, cycle }
}

export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
name: "Local",
init: () => {
Expand Down Expand Up @@ -377,46 +429,30 @@

const recent = createMemo(() => models.recent.list().map(models.find).filter(Boolean))

const modelActions = createModelActions({
batch,
recordLast: (item) =>
setStore("last", {
type: "model",
agent: agent.current()?.name,
model: item ?? null,
variant: selected(),
}),
write: (item) => write({ model: item }),
setVisibility: (item) => models.setVisibility(item, true),
pushRecent: (item) => models.recent.push(item),
recordRecent: (ref) => sdk.client.provider.recordRecent(ref),
recent,
current,
})

const model = {
ready: models.ready,
current,
recent,
list: models.list,
cycle(direction: 1 | -1) {
const items = recent()
const item = current()
if (!item) return

const index = items.findIndex((entry) => entry?.provider.id === item.provider.id && entry?.id === item.id)
if (index === -1) return

let next = index + direction
if (next < 0) next = items.length - 1
if (next >= items.length) next = 0

const entry = items[next]
if (!entry) return
model.set({ providerID: entry.provider.id, modelID: entry.id })
},
set(item: ModelKey | undefined, options?: { recent?: boolean }) {
batch(() => {
setStore("last", {
type: "model",
agent: agent.current()?.name,
model: item ?? null,
variant: selected(),
})
write({ model: item })
if (!item) return
models.setVisibility(item, true)
if (!options?.recent) return
models.recent.push(item)
// Mirror an explicit pick to the server's recent-model default so a
// model-less session (e.g. a Telegram /new) inherits the user's actual
// choice. Best-effort: a failure here must not disrupt the pick.
void sdk.client.provider.recordRecent({ providerID: item.providerID, modelID: item.modelID }).catch(() => {})
})
},
cycle: modelActions.cycle,
set: modelActions.set,
visible(item: ModelKey) {
return models.visible(item)
},
Expand Down
31 changes: 6 additions & 25 deletions packages/opencode/src/provider/model-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,8 @@ import { Flock } from "../util/flock"
import { isRecord } from "../util/record"

/**
* Persists the user's picked model into `state/model.json`'s `recent` list — the
* Writes the user's picked model to the `recent` list in `state/model.json`, the
* source `Provider.defaultModel()` reads when a prompt carries no explicit model.
* Upstream opencode wrote this list from the TUI; PawWork replaced the TUI with
* the desktop UI and kept only the reader, so a fresh session with no model
* (e.g. a Telegram `/new`) fell through to the first configured provider instead
* of the user's actual choice.
*
* This restores the writer, driven by the one place that truly knows the user
* chose a model: the desktop model picker, which calls the `/provider/recent`
* endpoint on an explicit pick. Recording at that single event — rather than
* inferring intent from the prompt path — keeps an agent's pinned model, a
* slash command, automation, or a subagent from ever leaking into the default,
* with no provenance guessing.
*/
export namespace ModelState {
export interface ModelRef {
Expand Down Expand Up @@ -57,19 +46,11 @@ export namespace ModelState {
}

/**
* Best-effort persist of the user's picked model. Locked read-modify-write so a
* concurrent CLI/desktop writer can neither corrupt the file nor drop sibling
* fields. A failure here must never break the caller.
*
* Only a missing file (ENOENT) starts from empty state. A parse error,
* permission error, or transient read failure means the file may still hold
* sibling state (favorite, variant, …); writing a fresh `{recent}` over it
* would clobber that, so such a read failure skips this write instead.
*
* The write itself is atomic (temp file + rename): `Provider.defaultModel()`
* reads this file unlocked and treats a parse failure as empty recent, and
* `writeFile` is not atomic — rename guarantees a concurrent reader sees the old
* or the new complete file, never a half-written one.
* Best-effort, locked read-modify-write. Only a missing file (ENOENT) starts
* from empty; any other read failure skips the write so sibling state (favorite,
* variant, …) is never clobbered. The temp-file + rename keeps the unlocked
* `defaultModel()` reader from ever seeing a half-written file, and failures
* never reach the caller.
*/
export async function recordRecent(model: ModelRef): Promise<void> {
const file = path.join(Global.Path.state, "model.json")
Expand Down
Loading