Repository navigation
fix(provider): record the picked model so model-less sessions inherit it #1347
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 8 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
3511130
fix(provider): persist last-used model so model-less sessions inherit it
Astro-Han 3db6a46
fix(provider): exclude slash-command models from recent default
Astro-Han 6505f42
fix(provider): only an explicit model selection seeds the recent default
Astro-Han 1731f4b
refactor(provider): reuse shared isRecord in model-state
Astro-Han 019a2be
fix(opencode): exclude agent-pinned models from recent default + isol…
Astro-Han d15a11d
refactor(provider): record recent model on explicit pick, not the pro…
Astro-Han ae0beac
test(provider): cover POST /provider/recent through the live route
Astro-Han 8d87301
test(provider): await the afterEach cleanup in model-state.test.ts
Astro-Han 780ae73
fix(provider): write model.json atomically so unlocked readers never …
Astro-Han 309c197
fix(provider): drop malformed entries when normalizing model.json recent
Astro-Han 8a0e141
test(app): cover the picker -> recordRecent wiring via an extracted h…
Astro-Han 02656d2
test(provider): assert no model.json write on a 400 /provider/recent
Astro-Han 057abd8
refactor(app): inline the recordRecent call back into model.set
Astro-Han 8c62eb2
test(provider): drop the weak concurrency atomicity test
Astro-Han File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| import fs from "fs/promises" | ||
| import path from "path" | ||
| import { afterEach, beforeEach, describe, expect, test } from "bun:test" | ||
| import { Global } from "@opencode-ai/core/global" | ||
| import { ModelState } from "./model-state" | ||
|
|
||
| const model = { providerID: "deepseek", modelID: "deepseek-chat" } | ||
| const other = { providerID: "qwen", modelID: "qwen-max" } | ||
|
|
||
| describe("applyRecent", () => { | ||
| test("promotes the model to the front of recent", () => { | ||
| const next = ModelState.applyRecent({ recent: [other] }, model) | ||
| expect(next.recent).toEqual([model, other]) | ||
| }) | ||
|
|
||
| test("dedupes a model that is already present", () => { | ||
| const next = ModelState.applyRecent({ recent: [other, model] }, model) | ||
| expect(next.recent).toEqual([model, other]) | ||
| }) | ||
|
|
||
| test("preserves sibling fields (favorite/variant)", () => { | ||
| const next = ModelState.applyRecent({ recent: [], favorite: ["x"], variant: { agent: "fast" } }, model) | ||
| expect(next.favorite).toEqual(["x"]) | ||
| expect(next.variant).toEqual({ agent: "fast" }) | ||
| }) | ||
|
|
||
| test("caps the list at max, keeping the newest", () => { | ||
| const previous = Array.from({ length: 60 }, (_, i) => ({ providerID: "p", modelID: `m${i}` })) | ||
| const next = ModelState.applyRecent({ recent: previous }, model, 50) | ||
| const recent = next.recent as Array<{ providerID: string; modelID: string }> | ||
| expect(recent).toHaveLength(50) | ||
| expect(recent[0]).toEqual(model) | ||
| }) | ||
|
|
||
| test("tolerates missing or garbage current contents", () => { | ||
| expect(ModelState.applyRecent(undefined, model).recent).toEqual([model]) | ||
| expect(ModelState.applyRecent({ recent: "nope" }, model).recent).toEqual([model]) | ||
| expect(ModelState.applyRecent("not an object", model).recent).toEqual([model]) | ||
| }) | ||
| }) | ||
|
|
||
| describe("recordRecent", () => { | ||
| // Global.Path.state is the process-wide state dir (isolated per test process by | ||
| // the XDG override in test/preload.ts). Clear model.json around each test. | ||
| const modelFile = () => path.join(Global.Path.state, "model.json") | ||
|
|
||
| beforeEach(async () => { | ||
| await fs.mkdir(Global.Path.state, { recursive: true }) | ||
| await fs.rm(modelFile(), { force: true }) | ||
| }) | ||
| afterEach(async () => await fs.rm(modelFile(), { force: true })) | ||
|
|
||
| test("promotes the model while preserving sibling state on a normal file", async () => { | ||
| await fs.writeFile(modelFile(), JSON.stringify({ recent: [other], favorite: ["x"], variant: { agent: "fast" } })) | ||
| await ModelState.recordRecent(model) | ||
| const after = JSON.parse(await fs.readFile(modelFile(), "utf8")) | ||
| expect(after.recent[0]).toEqual(model) | ||
| expect(after.favorite).toEqual(["x"]) | ||
| expect(after.variant).toEqual({ agent: "fast" }) | ||
| }) | ||
|
|
||
| test("creates the file from empty when it is missing (ENOENT)", async () => { | ||
| await ModelState.recordRecent(model) | ||
| const after = JSON.parse(await fs.readFile(modelFile(), "utf8")) | ||
| expect(after.recent).toEqual([model]) | ||
| }) | ||
|
|
||
| test("does NOT overwrite a file it cannot parse, so sibling state survives", async () => { | ||
| // A non-ENOENT read failure (here, corrupt JSON) must skip the write rather | ||
| // than clobber a file that may still hold favorite/variant under the damage. | ||
| await fs.writeFile(modelFile(), "{ not valid json") | ||
| await ModelState.recordRecent(model) | ||
| expect(await fs.readFile(modelFile(), "utf8")).toBe("{ not valid json") | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| import path from "path" | ||
| import { Global } from "@opencode-ai/core/global" | ||
| import { Filesystem } from "../util/filesystem" | ||
| import { Flock } from "../util/flock" | ||
| import { isRecord } from "../util/record" | ||
|
|
||
| /** | ||
| * Persists the user's picked model into `state/model.json`'s `recent` list — 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 { | ||
| providerID: string | ||
| modelID: string | ||
| } | ||
|
|
||
| // Keep enough history that defaultModel() can fall through to an older choice | ||
| // when the most-recent provider/model is no longer connected. | ||
| export const MAX_RECENT = 50 | ||
|
|
||
| /** | ||
| * Pure: compute the next model.json contents, promoting `model` to the front of | ||
| * `recent` (deduped, capped) while preserving every other field (favorite, | ||
| * variant, …) so a write here never clobbers what the rest of opencode owns. | ||
| */ | ||
| export function applyRecent(current: unknown, model: ModelRef, max: number = MAX_RECENT): Record<string, unknown> { | ||
| const base = isRecord(current) ? current : {} | ||
| const previous = Array.isArray(base.recent) ? base.recent : [] | ||
| const deduped = previous.filter( | ||
| (entry) => !(isRecord(entry) && entry.providerID === model.providerID && entry.modelID === model.modelID), | ||
| ) | ||
| const recent = [{ providerID: model.providerID, modelID: model.modelID }, ...deduped].slice(0, max) | ||
| return { ...base, recent } | ||
| } | ||
|
|
||
| function isEnoent(err: unknown): boolean { | ||
| return typeof err === "object" && err !== null && (err as { code?: string }).code === "ENOENT" | ||
| } | ||
|
|
||
| /** | ||
| * Best-effort persist of the user's picked model. Locked read-modify-write so a | ||
| * concurrent CLI/desktop writer can neither corrupt the file (writeJson is not | ||
| * atomic) 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. | ||
| */ | ||
| export async function recordRecent(model: ModelRef): Promise<void> { | ||
| const file = path.join(Global.Path.state, "model.json") | ||
| try { | ||
| await Flock.withLock(`model-state:${file}`, async () => { | ||
| let current: unknown | ||
| try { | ||
| current = await Filesystem.readJson<unknown>(file) | ||
| } catch (err) { | ||
| if (!isEnoent(err)) return | ||
| current = undefined | ||
| } | ||
| await Filesystem.writeJson(file, applyRecent(current, model)) | ||
| }) | ||
| } catch { | ||
| // recording recent is best-effort — it must not surface to the caller | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
58 changes: 58 additions & 0 deletions
58
packages/opencode/test/server/provider-recent-route.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import { afterEach, beforeEach, describe, expect, test } from "bun:test" | ||
| import fs from "fs/promises" | ||
| import path from "path" | ||
| import { Global } from "@opencode-ai/core/global" | ||
| import { Instance } from "../../src/project/instance" | ||
| import { Server } from "../../src/server/server" | ||
| import { resetDatabase } from "../fixture/db" | ||
| import { tmpdir } from "../fixture/fixture" | ||
|
|
||
| // The real entry path the desktop picker hits: POST /provider/recent must route, | ||
| // validate the body, and land the pick in state/model.json's `recent` — the list | ||
| // Provider.defaultModel() reads for a model-less session. Asserting through the | ||
| // live route guards the route path, the request body schema, and the handler -> | ||
| // model.json wiring all at once (the unit tests only cover ModelState directly). | ||
| const modelFile = () => path.join(Global.Path.state, "model.json") | ||
|
|
||
| afterEach(async () => { | ||
| await Instance.disposeAll() | ||
| await resetDatabase() | ||
| await fs.rm(modelFile(), { force: true }) | ||
| }) | ||
|
|
||
| describe("POST /provider/recent", () => { | ||
| beforeEach(async () => { | ||
| await fs.mkdir(Global.Path.state, { recursive: true }) | ||
| await fs.rm(modelFile(), { force: true }) | ||
| }) | ||
|
|
||
| test("persists the posted model to the front of model.json recent", async () => { | ||
| await using tmp = await tmpdir({ git: true }) | ||
| const app = Server.Default().app | ||
|
|
||
| const response = await app.request("/provider/recent", { | ||
| method: "POST", | ||
| headers: { "x-opencode-directory": tmp.path, "content-type": "application/json" }, | ||
| body: JSON.stringify({ providerID: "deepseek", modelID: "deepseek-chat" }), | ||
| }) | ||
|
|
||
| expect(response.status).toBe(200) | ||
| expect(await response.json()).toBe(true) | ||
|
|
||
| const recent = JSON.parse(await fs.readFile(modelFile(), "utf-8")).recent | ||
| expect(recent[0]).toEqual({ providerID: "deepseek", modelID: "deepseek-chat" }) | ||
| }) | ||
|
|
||
| test("rejects a body missing modelID (request schema is enforced)", async () => { | ||
| await using tmp = await tmpdir({ git: true }) | ||
| const app = Server.Default().app | ||
|
|
||
| const response = await app.request("/provider/recent", { | ||
| method: "POST", | ||
| headers: { "x-opencode-directory": tmp.path, "content-type": "application/json" }, | ||
| body: JSON.stringify({ providerID: "deepseek" }), | ||
| }) | ||
|
|
||
| expect(response.status).toBe(400) | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.