From 7a88529d383efcac49056be381419a0eaef08cb0 Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Thu, 18 Jun 2026 01:17:43 +0800 Subject: [PATCH 1/4] refactor(app): extract the model picker's set/cycle into createModelActions Behavior-preserving: pulls the model picker's set/cycle out of the Local context's init into an exported, dependency-injected factory (mirroring createPromptBinding). The wiring was previously only reachable by mounting the whole context, so the recordRecent side-effect had no unit coverage. --- packages/app/src/context/local.tsx | 106 +++++++++++++++++++---------- 1 file changed, 71 insertions(+), 35 deletions(-) diff --git a/packages/app/src/context/local.tsx b/packages/app/src/context/local.tsx index 91ab3b388..c35f3acff 100644 --- a/packages/app/src/context/local.tsx +++ b/packages/app/src/context/local.tsx @@ -104,6 +104,58 @@ export function localSavedStoreKey(directory: string | undefined) { 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: (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 + recent: () => Array + 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: () => { @@ -377,46 +429,30 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({ 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) }, From d622949a0812154d5f527de37fe0d7f2d205ef1e Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Thu, 18 Jun 2026 01:17:49 +0800 Subject: [PATCH 2/4] test(app): cover the model picker's recordRecent wiring Guards the recent-model default against a refactor that drops the wiring: an explicit pick (set(item, { recent: true })) records to the server's recent-model default; a plain set() and cycle() never do. The existing ModelState/route/defaultModel tests would all stay green without this. --- packages/app/src/context/local.test.ts | 56 ++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/packages/app/src/context/local.test.ts b/packages/app/src/context/local.test.ts index 41f6ae90f..f263da59d 100644 --- a/packages/app/src/context/local.test.ts +++ b/packages/app/src/context/local.test.ts @@ -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 @@ -18,6 +20,7 @@ beforeAll(async () => { })) const mod = await import("./local") + createModelActions = mod.createModelActions localSavedStoreKey = mod.localSavedStoreKey localPersistReadyForAction = mod.localPersistReadyForAction pruneLocalSavedStores = mod.pruneLocalSavedStores @@ -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: (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" }]) + }) +}) From 69b942c99aec2c2357f49a3c0bafe25306cd10eb Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Thu, 18 Jun 2026 01:17:55 +0800 Subject: [PATCH 3/4] docs(provider): trim model-state comments to the load-bearing constraints The header told the upstream-TUI backstory and the recordRecent doc read like a PR description. Keep only what a maintainer needs: writes the recent list in state/model.json, ENOENT starts empty, other read failures skip to protect sibling state, atomic rename for the unlocked reader. --- packages/opencode/src/provider/model-state.ts | 31 ++++--------------- 1 file changed, 6 insertions(+), 25 deletions(-) diff --git a/packages/opencode/src/provider/model-state.ts b/packages/opencode/src/provider/model-state.ts index cb6a1e93d..ac3ceab83 100644 --- a/packages/opencode/src/provider/model-state.ts +++ b/packages/opencode/src/provider/model-state.ts @@ -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 { @@ -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 { const file = path.join(Global.Path.state, "model.json") From 6962ff2b53aee709dab10563b0b4e71bcae1d6d4 Mon Sep 17 00:00:00 2001 From: Yuhan Lei Date: Thu, 18 Jun 2026 16:12:56 +0800 Subject: [PATCH 4/4] test(app): guard recordRecent at the picker call site, not Local.set MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The first cut extracted createModelActions and tested set(item,{recent:true}) directly. That bypassed the real wiring: deleting { recent: true } from the model picker's onSelect left the test green, so it never guarded the regression the PR is named for. It also added test-only production surface (an 8-param DI factory) the component did not need — the picker already exposes a ModelPickerState injection seam. Drop createModelActions; restore Local's inline set/cycle. Move the picker's one write path into model-picker-select.ts (selectModel) — a dependency-free sibling the test imports without loading the component (Kobalte pulls solid-js's client-only API, which throws under the server-condition test runtime; mirrors sidebar-item-navigation.ts). ModelList.onSelect now calls selectModel, and the unit test asserts an explicit pick passes { recent: true }. Verified by dropping the flag and watching the test go red. The programmatic-set / cycle "do not record recent" assertions are dropped with the factory: they have no light real-path seam (only a full LocalProvider mount, the heavy e2e an earlier review vetoed). The picker call site is the high-value guard. Claude-Session: https://claude.ai/code/session_01PWbeoRm3mmxYxKae2Kj6Z7 --- .../prompt-input/model-picker-select.test.ts | 26 +++++ .../prompt-input/model-picker-select.ts | 16 +++ .../components/prompt-input/model-picker.tsx | 5 +- packages/app/src/context/local.test.ts | 56 --------- packages/app/src/context/local.tsx | 106 ++++++------------ 5 files changed, 79 insertions(+), 130 deletions(-) create mode 100644 packages/app/src/components/prompt-input/model-picker-select.test.ts create mode 100644 packages/app/src/components/prompt-input/model-picker-select.ts diff --git a/packages/app/src/components/prompt-input/model-picker-select.test.ts b/packages/app/src/components/prompt-input/model-picker-select.test.ts new file mode 100644 index 000000000..0b989e539 --- /dev/null +++ b/packages/app/src/components/prompt-input/model-picker-select.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, test } from "bun:test" +import { selectModel } from "./model-picker-select" + +// Guards the recordRecent wiring at the picker's call site: an explicit pick must +// pass { recent: true } so the choice becomes the server's recent-model default — +// what a model-less session (e.g. a Telegram /new) inherits. Dropping the flag +// from selectModel is exactly the regression this catches; a test on the Local +// model.set alone never would, because it bypasses the picker's call site. +describe("model picker selectModel", () => { + function spy() { + const calls: Array<{ item: unknown; options: unknown }> = [] + return { set: (item: unknown, options: unknown) => calls.push({ item, options }), calls } + } + + test("an explicit pick records the recent-model default", () => { + const model = spy() + selectModel(model, { id: "claude", provider: { id: "anthropic" } }) + expect(model.calls).toEqual([{ item: { providerID: "anthropic", modelID: "claude" }, options: { recent: true } }]) + }) + + test("clearing the selection still routes through as an explicit pick", () => { + const model = spy() + selectModel(model, undefined) + expect(model.calls).toEqual([{ item: undefined, options: { recent: true } }]) + }) +}) diff --git a/packages/app/src/components/prompt-input/model-picker-select.ts b/packages/app/src/components/prompt-input/model-picker-select.ts new file mode 100644 index 000000000..0ac8f0188 --- /dev/null +++ b/packages/app/src/components/prompt-input/model-picker-select.ts @@ -0,0 +1,16 @@ +import type { ModelKey } from "@/context/models" + +// Split out of model-picker.tsx so it can be unit-tested without loading the +// component (Kobalte pulls solid-js's client-only API, which throws under the +// server-condition test runtime). Mirrors sidebar-item-navigation.ts. +type ModelSetter = { + set: (item: ModelKey | undefined, options?: { recent?: boolean }) => void +} + +// The picker's one write path. An explicit pick always mirrors the choice to the +// server's recent-model default (the `{ recent: true }`), which a model-less +// session — a Telegram /new, say — then inherits. Dropping that flag is the +// regression model-picker.test.ts guards. +export function selectModel(model: ModelSetter, choice: { id: string; provider: { id: string } } | undefined) { + model.set(choice ? { modelID: choice.id, providerID: choice.provider.id } : undefined, { recent: true }) +} diff --git a/packages/app/src/components/prompt-input/model-picker.tsx b/packages/app/src/components/prompt-input/model-picker.tsx index 45eae7e59..e1cf3af7f 100644 --- a/packages/app/src/components/prompt-input/model-picker.tsx +++ b/packages/app/src/components/prompt-input/model-picker.tsx @@ -14,6 +14,7 @@ import { useLanguage } from "@/context/language" import { compareModelsForDisplay } from "@/utils/model-order" import { modelSupportsInput } from "@/components/prompt-input/attachment-routing" import { translateVariant } from "@/components/prompt-input/variant-label" +import { selectModel } from "./model-picker-select" const isFree = (provider: string, cost: { input: number } | undefined) => provider === "opencode" && (!cost || cost.input === 0) @@ -86,9 +87,7 @@ const ModelList: Component<{ )} onSelect={(x) => { - model.set(x ? { modelID: x.id, providerID: x.provider.id } : undefined, { - recent: true, - }) + selectModel(model, x) props.onSelect() }} > diff --git a/packages/app/src/context/local.test.ts b/packages/app/src/context/local.test.ts index f263da59d..41f6ae90f 100644 --- a/packages/app/src/context/local.test.ts +++ b/packages/app/src/context/local.test.ts @@ -1,13 +1,11 @@ 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 @@ -20,7 +18,6 @@ beforeAll(async () => { })) const mod = await import("./local") - createModelActions = mod.createModelActions localSavedStoreKey = mod.localSavedStoreKey localPersistReadyForAction = mod.localPersistReadyForAction pruneLocalSavedStores = mod.pruneLocalSavedStores @@ -102,56 +99,3 @@ 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: (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" }]) - }) -}) diff --git a/packages/app/src/context/local.tsx b/packages/app/src/context/local.tsx index c35f3acff..91ab3b388 100644 --- a/packages/app/src/context/local.tsx +++ b/packages/app/src/context/local.tsx @@ -104,58 +104,6 @@ export function localSavedStoreKey(directory: string | undefined) { 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: (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 - recent: () => Array - 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: () => { @@ -429,30 +377,46 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({ 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: modelActions.cycle, - set: modelActions.set, + 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(() => {}) + }) + }, visible(item: ModelKey) { return models.visible(item) },