Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
6 changes: 6 additions & 0 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 @@ -411,6 +411,12 @@
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) {
Expand Down
75 changes: 75 additions & 0 deletions packages/opencode/src/provider/model-state.test.ts
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")
})
})
78 changes: 78 additions & 0 deletions packages/opencode/src/provider/model-state.ts
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"
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
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
}
}
}
35 changes: 34 additions & 1 deletion packages/opencode/src/server/instance/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import { Config } from "../../config/config"
import { Provider } from "../../provider/provider"
import { ModelsDev } from "../../provider/models"
import { ProviderAuth } from "../../provider/auth"
import { ProviderID } from "../../provider/schema"
import { ModelState } from "../../provider/model-state"
import { ProviderID, ModelID } from "../../provider/schema"
import { AppRuntime } from "../../effect/app-runtime"
import { mapValues } from "remeda"
import { errors } from "../error"
Expand Down Expand Up @@ -191,5 +192,37 @@ export const ProviderRoutes = lazy(() =>
)
return c.json(true)
},
)
.post(
"/recent",
describeRoute({
summary: "Record recent model",
description:
"Persist the user's picked model as the recent default that model-less sessions (e.g. a Telegram /new) inherit. Called by the desktop model picker on an explicit pick.",
operationId: "provider.recordRecent",
responses: {
200: {
description: "Recorded",
content: {
"application/json": {
schema: resolver(z.boolean()),
},
},
},
...errors(400),
},
}),
validator(
"json",
z.object({
providerID: ProviderID.zod.meta({ description: "Provider ID" }),
modelID: ModelID.zod.meta({ description: "Model ID" }),
}),
),
async (c) => {
const { providerID, modelID } = c.req.valid("json")
await ModelState.recordRecent({ providerID, modelID })
return c.json(true)
},
),
)
52 changes: 52 additions & 0 deletions packages/opencode/test/provider/provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Plugin } from "../../src/plugin/index"
import { Auth } from "../../src/auth"
import { ModelsDev } from "../../src/provider"
import { Provider } from "../../src/provider"
import { ModelState } from "../../src/provider/model-state"
import { withPawWorkProviders } from "../../src/provider/pawwork-providers"
import { localProviderImportSpec, stripOpenAIResponseInputIDs } from "../../src/provider/provider"
import { ProviderID, ModelID } from "../../src/provider/schema"
Expand Down Expand Up @@ -717,6 +718,57 @@ test("defaultModel respects config model setting", async () => {
})
})

test("defaultModel returns a model seeded into recent via recordRecent (model.json round-trip)", async () => {
// The read half of the recent-model chain: recordRecent writes state/model.json,
// and defaultModel must pick it up ahead of the provider's own first model. If
// recordRecent's format drifts or defaultModel stops reading recent, this fails.
await using tmp = await tmpdir({
init: async (dir) => {
await Bun.write(
path.join(dir, "opencode.json"),
JSON.stringify({
$schema: "https://opencode.ai/config.json",
provider: {
"custom-openai": {
name: "Custom OpenAI",
npm: "@ai-sdk/openai-compatible",
env: [],
models: {
"model-a": { name: "Model A", tool_call: true, limit: { context: 1000, output: 100 } },
"model-b": { name: "Model B", tool_call: true, limit: { context: 1000, output: 100 } },
},
options: { apiKey: "test-key", baseURL: "https://custom.openai.com/v1" },
},
},
}),
)
},
})
// model.json is process-wide (XDG_STATE_HOME from the test preload), so it is
// shared with prompt.test.ts. Start clean so "empty recent" holds regardless of
// run order, and remove our write afterward so it can't leak into other tests.
const stateModel = path.join(Global.Path.state, "model.json")
await unlink(stateModel).catch(() => {})
try {
await Instance.provide({
directory: tmp.path,
fn: async () => {
// With an empty recent, defaultModel falls through to the provider's first model.
const fallback = await defaultModel()
// Seed the OTHER model — the one defaultModel would not pick on its own.
const other = String(fallback.modelID) === "model-a" ? "model-b" : "model-a"
await ModelState.recordRecent({ providerID: ProviderID.make("custom-openai"), modelID: ModelID.make(other) })
const after = await defaultModel()
expect(String(after.providerID)).toBe("custom-openai")
expect(String(after.modelID)).toBe(other)
expect(String(after.modelID)).not.toBe(String(fallback.modelID))
},
})
} finally {
await unlink(stateModel).catch(() => {})
}
})

test("provider with baseURL from config", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
Expand Down
58 changes: 58 additions & 0 deletions packages/opencode/test/server/provider-recent-route.test.ts
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)
})
})
40 changes: 40 additions & 0 deletions packages/sdk/js/src/v2/gen/sdk.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ import type {
ProviderOauthAuthorizeResponses,
ProviderOauthCallbackErrors,
ProviderOauthCallbackResponses,
ProviderRecordRecentErrors,
ProviderRecordRecentResponses,
PtyConnectErrors,
PtyConnectResponses,
PtyConnectTokenErrors,
Expand Down Expand Up @@ -3302,6 +3304,44 @@ export class Provider extends HeyApiClient {
})
}

public recordRecent<ThrowOnError extends boolean = false>(
parameters: {
directory?: string
workspace?: string
providerID: string
modelID: string
},
options?: Options<never, ThrowOnError>,
) {
const params = buildClientParams(
[parameters],
[
{
args: [
{ in: "query", key: "directory" },
{ in: "query", key: "workspace" },
{ in: "body", key: "providerID" },
{ in: "body", key: "modelID" },
],
},
],
)
return (options?.client ?? this.client).post<
ProviderRecordRecentResponses,
ProviderRecordRecentErrors,
ThrowOnError
>({
url: "/provider/recent",
...options,
...params,
headers: {
"Content-Type": "application/json",
...options?.headers,
...params.headers,
},
})
}

private _oauth?: Oauth
get oauth(): Oauth {
return (this._oauth ??= new Oauth({ client: this.client }))
Expand Down
Loading