Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
OpenCode: Refresh re-reads the provider's models, and a model id can be typed by hand
milind-soni62e66fee0b8a
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.tsindex b3b6c40077..3c94c77cff 100644--- a/server/drivers/acp/core.ts+++ b/server/drivers/acp/core.ts@@ -102,12 +102,12 @@ export interface AcpSupport {modelVariants?: boolean;/** Default CLI binary name if the instance config doesn't override it. */defaultCli: string;- /** Optional live model catalog; a failed lookup keeps the last usable one. `config` lets a- * support ask the binary it will spawn, not whatever is on PATH. */+ /** Optional live model catalog; a failed lookup keeps the last usable one. `config` lets a support ask the binary+ * it will spawn, not whatever is on PATH; `fresh` is the person's Refresh, which may bypass the CLI's own cache. */resolveModels?(environment: Record<string, string | undefined>,config: AcpConfig,- instanceId: string,+ instanceId: string, fresh?: boolean,): ModelCatalog | Promise<ModelCatalog>;/** Some managed agents are not probed at app startup; their Refresh is the only lookup. */resolveModelsOnCreate?: boolean;@@ -341,10 +341,10 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>let models = support.resolveModels && support.resolveModelsOnCreate === false? readStartupModelCache(instanceId) ?? support.models : support.models;let accountModels: ReadonlySet<string> | null = null;- const refreshModels = async () => {+ const refreshModels = async (fresh = false) => {if (!support.resolveModels) return;try {- const resolved = await support.resolveModels(childEnv(), config, instanceId);+ const resolved = await support.resolveModels(childEnv(), config, instanceId, fresh);if (resolved.options.length) {models = resolved;accountModels = new Set(resolved.options.map((option) => option.id));@@ -1687,7 +1687,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>get models() {return models;},- refreshModels: support.resolveModels ? refreshModels : undefined,+ refreshModels: support.resolveModels ? () => refreshModels(true) : undefined,...(startupModelRefresh ? { startupModelRefresh } : {}),...(deviceSignIn ? {startAuthentication: () => deviceSignIn.start(),diff --git a/server/drivers/acp/opencode-go.ts b/server/drivers/acp/opencode-go.tsindex 6079074f41..ebb0d9bf9c 100644--- a/server/drivers/acp/opencode-go.ts+++ b/server/drivers/acp/opencode-go.ts@@ -13,6 +13,7 @@ import { applyStandaloneSpawnEnv } from "../../engine-install.ts";import { OPENCODE_STANDALONE } from "./opencode-release.ts";import { createAcpDriver, type AccountErrorCode, type AcpConfig, type AcpSupport } from "./core.ts";import { acpModelOption, acpVariantOption, offeredModels } from "./config-options.ts";+import { declareTypedOpenCodeModel } from "./opencode-typed-model.ts";import { parseOpenCodeLogLine } from "./quiet-status.ts";import type { ModelCatalog, ModelVariantOption, ProviderDriver, ProviderErrorCode } from "../../contracts.ts";import { titleCaseModelId } from "../../contracts.ts";@@ -21,6 +22,7 @@ import { execCli, killCliTree, spawnCli } from "../../procs.ts";const NO_MODELS: ModelCatalog = { default: "", options: [] };const lastSuccessfulCatalog = new Map<string, ModelCatalog>();+const catalogRevisions = new Map<string, number>();/** `models --verbose` (V1) prints Zen prices, cost 0 meaning free; V2 prints none, so a `-free` id suffix is the fallback. */const freeModels = new Set<string>();const paidModels = new Set<string>();@@ -33,6 +35,7 @@ const discoveryProbeCache = new Map<string, { expiresAt: number; result: Promiseexport type OpenCodeCatalogLoader = (environment: Record<string, string | undefined>,cli: string,+ options?: { refresh?: boolean },) => Promise<ModelCatalog>;function labelForModel(id: string): string {@@ -227,6 +230,19 @@ function runOpenCodeModelsVerbose(});}+/** OpenCode (1.19.4) lists models from its models.dev cache, or without one the snapshot built into it, and neither+ * `opencode models` nor `opencode acp` refetches it; `models --refresh` does, and the next process reads it. */+function refreshOpenCodeModelCache(cli: string, environment: Record<string, string | undefined>): Promise<void> {+ return new Promise((resolve) => {+ execCli(cli, ["models", "--refresh"], { timeout: DISCOVERY_TIMEOUT_MS, maxBuffer: 8 * 1024 * 1024, env: environment }, () => resolve());+ });+}++function sameModelIds(left: ModelCatalog | undefined, right: ModelCatalog): boolean {+ const ids = new Set(left?.options.map((option) => option.id));+ return ids.size === right.options.length && right.options.every((option) => ids.has(option.id));+}+function runGit(directory: string, args: string[]): Promise<void> {const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_")));return new Promise((resolveRun, rejectRun) => {@@ -419,7 +435,9 @@ function withEfforts(export async function discoverOpenCodeModels(environment: Record<string, string | undefined>,cli = "opencode",+ options: { refresh?: boolean } = {},): Promise<ModelCatalog> {+ if (options.refresh) await refreshOpenCodeModelCache(cli, environment);const probeSession = () => probeOpenCodeSession(cli, environment);const readMetadata = () => runOpenCodeModelsVerbose(cli, environment).then(parseOpenCodeModels);let [session, verbose] = await Promise.allSettled([probeSession(), readMetadata()]);@@ -445,10 +463,18 @@ export async function discoverOpenCodeModels(catalog = { default: preferredOpenCodeModel(metadata.options.map((option) => option.id)), options: metadata.options };}if (!catalog) return lastSuccessfulCatalog.get(cli) ?? NO_MODELS;+ if (options.refresh && !sameModelIds(lastSuccessfulCatalog.get(cli), catalog)) {+ catalogRevisions.set(cli, (catalogRevisions.get(cli) ?? 0) + 1);+ }lastSuccessfulCatalog.set(cli, catalog);return catalog;}+/** A running `opencode acp` keeps the catalog it started with, so a refresh that changed it needs a fresh process. */+export function openCodeSpawnFingerprint(env: Record<string, string | undefined>, cli: string): string {+ return `${openCodeLoginsFingerprint(env)}#${catalogRevisions.get(cli) ?? 0}`;+}+/** Whether this OpenCode offers any model; Zen's free models need no login. */export async function canRunOpenCode(environment: Record<string, string | undefined>,@@ -471,6 +497,7 @@ export async function canRunOpenCode(export function resetOpenCodeModelCache() {discoveryFolder = null;lastSuccessfulCatalog.clear();+ catalogRevisions.clear();discoveryProbeCache.clear();freeModels.clear();paidModels.clear();@@ -851,12 +878,12 @@ const support = (loadCatalog: OpenCodeCatalogLoader, ownAccess = new Map<string,ownMcpOverHttp: true,// OpenCode 1.18.27's build agent lists 13 tools of its own (bash, read, edit, task, skill…); room for a newer CLI's.engineTools: 24,- resolveTurnModel: (model, env) => model ? ensureOpenCodeInjectModel(model, env) : model,+ resolveTurnModel: (model, env) => model ? declareTypedOpenCodeModel(env, model) ?? ensureOpenCodeInjectModel(model, env) : model,transformEnv: (env, config, instanceId, instanceEnvironment) => {withholdProviderKeysWhenManaged(env, config, instanceId, instanceEnvironment);applyStandaloneSpawnEnv(OPENCODE_STANDALONE, env, config.cli);},- spawnFingerprint: openCodeLoginsFingerprint,+ spawnFingerprint: (env, config) => openCodeSpawnFingerprint(env, config.cli),applyTurnEnv: (env, { fullAuto, botId, cwd }) => {if (openMausOwnsWorkingFolder(cwd)) env.OPENCODE_DISABLE_PROJECT_CONFIG = "1";if (!fullAuto) {@@ -880,8 +907,8 @@ const support = (loadCatalog: OpenCodeCatalogLoader, ownAccess = new Map<string,},classifyError: classifyOpenCodeError,describeAccountError: describeOpenCodeAccountError,- resolveModels: async (environment, config) => mergeLocalInject(- await loadCatalog(environment, config.cli),+ resolveModels: async (environment, config, _instanceId, fresh) => mergeLocalInject(+ await loadCatalog(environment, config.cli, { refresh: fresh === true }),environment,),buildPromptText: (turn) => turn.system ? `${turn.system}\n\n${turn.text}` : turn.text,diff --git a/server/drivers/acp/opencode-refresh.test.ts b/server/drivers/acp/opencode-refresh.test.tsnew file mode 100644index 0000000000..df61bb4b14--- /dev/null+++ b/server/drivers/acp/opencode-refresh.test.ts@@ -0,0 +1,151 @@+import { afterEach, describe, expect, it } from "vitest";+import { mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { typedOpenCodeModel, typedOpenCodeModelId } from "../../../shared/opencode-model-id.ts";+import { removeTempDir } from "../../testing/cleanup.ts";+import { recordEvents, type EventRecorder } from "../../testing/events.ts";+import type { ModelCatalog, ProviderInstance } from "../../contracts.ts";+import {+ createOpenCodeDriver,+ discoverOpenCodeModels,+ openCodeSpawnFingerprint,+ resetOpenCodeModelCache,+ type OpenCodeCatalogLoader,+} from "./opencode-go.ts";+import { declareTypedOpenCodeModel } from "./opencode-typed-model.ts";++const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "testing", "fake-acp-cli.ts");+const STALE = "opencode/big-pickle\nvenice/deepseek-v4-flash";+const FRESH = `${STALE}\nvenice/deepseek-v4-1-flash-uncensored`;++const scratches: string[] = [];+const live: Array<{ instance: ProviderInstance; recorder: EventRecorder }> = [];+afterEach(async () => {+ for (const entry of live.splice(0)) {+ entry.recorder.stop();+ await entry.instance.dispose();+ }+ for (const scratch of scratches.splice(0)) await removeTempDir(scratch);+ resetOpenCodeModelCache();+});++function home(cached: string, offered: string) {+ const scratch = mkdtempSync(join(tmpdir(), "omb-opencode-refresh-"));+ scratches.push(scratch);+ const cache = join(scratch, "models-cache");+ const upstream = join(scratch, "models-upstream");+ writeFileSync(cache, cached);+ writeFileSync(upstream, offered);+ return {+ scratch, upstream,+ env: {+ ...process.env, HOME: scratch, XDG_CONFIG_HOME: scratch, XDG_DATA_HOME: scratch, OPENCODE_API_KEY: "fixture-key",+ FAKE_ACP_MODELS_FILE: cache, FAKE_ACP_MODELS_REFRESH_FROM: upstream,+ } as Record<string, string | undefined>,+ };+}++const ids = (catalog: ModelCatalog) => catalog.options.map((option) => option.id);++async function start(name: string, environment: Record<string, string | undefined>, loader: OpenCodeCatalogLoader = discoverOpenCodeModels) {+ const instance = await createOpenCodeDriver(loader).create({+ instanceId: name, displayName: "OpenCode", enabled: true,+ config: { cli: FAKE_CLI, fullAuto: false, workspace: environment.HOME },+ environment: Object.fromEntries(Object.entries(environment).filter((entry): entry is [string, string] => entry[1] !== undefined)),+ });+ const recorder = recordEvents(instance.adapter);+ live.push({ instance, recorder });+ await instance.startupModelRefresh;+ const run = async (threadId: string, model: string) => {+ const { turnId } = await instance.adapter.sendTurn({ threadId, text: "hello", model });+ const done = await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId, 20_000);+ return { done, events: recorder.events.filter((event) => event.turnId === turnId) };+ };+ return { instance, run };+}++describe("OpenCode Refresh", () => {+ it("re-reads the provider's models past OpenCode's own models cache", async () => {+ const { env } = home(STALE, FRESH);+ expect(ids(await discoverOpenCodeModels(env, FAKE_CLI))).not.toContain("venice/deepseek-v4-1-flash-uncensored");+ expect(ids(await discoverOpenCodeModels(env, FAKE_CLI, { refresh: true }))).toContain("venice/deepseek-v4-1-flash-uncensored");+ });++ it("is what the picker's refresh runs, and only it", async () => {+ const asked: Array<boolean | undefined> = [];+ const { env } = home(STALE, STALE);+ const { instance } = await start("opencode-refresh-asks", env, async (_environment, _cli, options) => {+ asked.push(options?.refresh);+ return { default: "opencode/big-pickle", options: [{ id: "opencode/big-pickle", label: "Zen · Big Pickle" }] };+ });+ expect(asked.every((refresh) => refresh === false)).toBe(true);+ await instance.refreshModels?.();+ expect(asked.at(-1)).toBe(true);+ });++ it("starts a fresh OpenCode for the next turn only when the refresh changed the models", async () => {+ const { env, upstream } = home(STALE, STALE);+ await discoverOpenCodeModels(env, FAKE_CLI);+ const before = openCodeSpawnFingerprint(env, FAKE_CLI);+ await discoverOpenCodeModels(env, FAKE_CLI, { refresh: true });+ expect(openCodeSpawnFingerprint(env, FAKE_CLI)).toBe(before);+ writeFileSync(upstream, FRESH);+ await discoverOpenCodeModels(env, FAKE_CLI, { refresh: true });+ expect(openCodeSpawnFingerprint(env, FAKE_CLI)).not.toBe(before);+ });++ it("runs a newly offered model on the turn right after the refresh", async () => {+ const { env, upstream } = home(STALE, STALE);+ const { instance, run } = await start("opencode-refresh-turn", env);+ expect((await run("t-before", "opencode/big-pickle")).done).toMatchObject({ ok: true });+ writeFileSync(upstream, FRESH);+ await instance.refreshModels?.();+ expect(ids(instance.models)).toContain("venice/deepseek-v4-1-flash-uncensored");+ const after = await run("t-after", "venice/deepseek-v4-1-flash-uncensored");+ expect(after.done).toMatchObject({ ok: true });+ expect(after.events.find((event) => event.type === "session.started")).toMatchObject({ model: "venice/deepseek-v4-1-flash-uncensored" });+ });+});++describe("OpenCode model typed by hand", () => {+ const listed: ModelCatalog = { default: "opencode/big-pickle", options: [{ id: "opencode/big-pickle", label: "Zen · Big Pickle" }] };+ const typed = "typed::venice/deepseek-v4-1-flash-uncensored";++ it("is saved apart from listed ids, and only as a provider/model id", () => {+ expect(typedOpenCodeModelId(" venice/deepseek-v4-1-flash-uncensored ")).toBe(typed);+ expect(typedOpenCodeModel(typed)).toBe("venice/deepseek-v4-1-flash-uncensored");+ expect(typedOpenCodeModelId("openrouter/meta-llama/llama-3.3-70b:free")).toBe("typed::openrouter/meta-llama/llama-3.3-70b:free");+ for (const bad of ["deepseek", "/model", "venice/", "venice/a b", "ven ice/model", "venice/x\u0000", `venice/${"x".repeat(201)}`, "typed::venice/x"]) {+ expect(typedOpenCodeModelId(bad)).toBeNull();+ }+ for (const other of ["venice/deepseek-v4-1-flash-uncensored", "omlx::qwen", "typed::venice/a b", undefined]) expect(typedOpenCodeModel(other)).toBeNull();+ });++ it("is declared to OpenCode beside the person's own config, and no other id is", () => {+ const env: Record<string, string | undefined> = {+ OPENCODE_CONFIG_CONTENT: JSON.stringify({ theme: "dark", provider: { venice: { options: { timeout: 1 }, models: { mine: { name: "Mine" } } } } }),+ };+ expect(declareTypedOpenCodeModel(env, typed)).toBe("venice/deepseek-v4-1-flash-uncensored");+ expect(JSON.parse(env.OPENCODE_CONFIG_CONTENT!)).toEqual({+ theme: "dark",+ provider: { venice: { options: { timeout: 1 }, models: { "deepseek-v4-1-flash-uncensored": {}, mine: { name: "Mine" } } } },+ });+ for (const model of ["venice/deepseek-v4-1-flash-uncensored", "opencode/big-pickle", "not a model"]) {+ const untouched: Record<string, string | undefined> = {};+ expect(declareTypedOpenCodeModel(untouched, model)).toBeUndefined();+ expect(untouched).toEqual({});+ }+ });++ it("runs on OpenCode instead of being swapped for the default", async () => {+ const { env } = home("opencode/big-pickle", "opencode/big-pickle");+ const { run } = await start("opencode-typed", env, async () => listed);+ const turn = await run("t-typed", typed);+ expect(turn.done).toMatchObject({ ok: true });+ expect(turn.events.find((event) => event.type === "session.started")).toMatchObject({ model: "venice/deepseek-v4-1-flash-uncensored" });+ expect(turn.events.some((event) => event.type === "runtime.notice")).toBe(false);+ });+});diff --git a/server/drivers/acp/opencode-typed-model.ts b/server/drivers/acp/opencode-typed-model.tsnew file mode 100644index 0000000000..73922dda25--- /dev/null+++ b/server/drivers/acp/opencode-typed-model.ts@@ -0,0 +1,33 @@+import { typedOpenCodeModel } from "../../../shared/opencode-model-id.ts";++function record(value: unknown): Record<string, unknown> {+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};+}++/** The OpenCode id of a model typed by hand, declared to OpenCode for this process; undefined for any other id.+ * OpenCode (1.19.4) refuses `session/set_config_option` for a model its catalog lacks ("model not found"), merges+ * OPENCODE_CONFIG_CONTENT over its other config, and adds a model listed under a provider's `models` to that provider. */+export function declareTypedOpenCodeModel(env: Record<string, string | undefined>, savedId: string): string | undefined {+ const model = typedOpenCodeModel(savedId);+ if (!model) return undefined;+ let config: Record<string, unknown> = {};+ if (env.OPENCODE_CONFIG_CONTENT?.trim()) {+ try {+ const parsed = JSON.parse(env.OPENCODE_CONFIG_CONTENT) as unknown;+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return model;+ config = parsed as Record<string, unknown>;+ } catch {+ return model;+ }+ }+ const separator = model.indexOf("/");+ const providerId = model.slice(0, separator);+ const providers = record(config.provider);+ const provider = record(providers[providerId]);+ const models = record(provider.models);+ env.OPENCODE_CONFIG_CONTENT = JSON.stringify({+ ...config,+ provider: { ...providers, [providerId]: { ...provider, models: { [model.slice(separator + 1)]: {}, ...models } } },+ });+ return model;+}diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.tsindex ac41c5eaa7..01e0c68d57 100755--- a/server/testing/fake-acp-cli.ts+++ b/server/testing/fake-acp-cli.ts@@ -38,6 +38,8 @@// FAKE_ACP_MODELS model ids: opencode-shaped configOptions and set_config_option (-32602 for others);// a new session starts on AGY_ACP_DEFAULT_MODEL when set, taken unchecked as agy_acp_server 1.1.1 does// FAKE_ACP_MODELS_FILE the same list, read once at startup, as `opencode acp` never re-reads a login+// FAKE_ACP_MODELS_REFRESH_FROM `models --refresh` copies this file over FAKE_ACP_MODELS_FILE, as OpenCode 1.19.4+// refetches its models.dev cache only then; OPENCODE_CONFIG_CONTENT's provider models join any model list// FAKE_ACP_MODELS_LIST=v2 OpenCode 2: `models` answers empty with exit 0, `models --verbose` exits 1// FAKE_ACP_MODELS_LIST=auto-only Cursor CLI 2026.10.22: `models` lists only `auto`// FAKE_ACP_VERBOSE_FAIL_ONCE marker path: the first `models --verbose` fails, like a new OpenCode home's first run@@ -84,6 +86,12 @@ const modelsText = process.env.FAKE_ACP_MODELS_FILE && existsSync(process.env.FA: process.env.FAKE_ACP_MODELS ?? "";// One id per line when the list holds a newline (DeepSeek's wire values are JSON pairs with commas); else comma-separated.const models = modelsText.split(modelsText.includes("\n") ? "\n" : ",").map((id) => id.trim()).filter(Boolean);+try {+ const declared = JSON.parse(process.env.OPENCODE_CONFIG_CONTENT || "{}")?.provider ?? {};+ for (const [provider, entry] of Object.entries<any>(declared)) {+ for (const id of Object.keys(entry?.models ?? {})) if (models.length && !models.includes(`${provider}/${id}`)) models.push(`${provider}/${id}`);+ }+} catch {}const defaultModelEnv = process.env.AGY_ACP_DEFAULT_MODEL;if (models.length && defaultModelEnv && !models.includes(defaultModelEnv)) models.push(defaultModelEnv);let currentModel: string | null = models.length && defaultModelEnv ? defaultModelEnv : models[0] ?? null;@@ -283,6 +291,12 @@ if (argv[0] === "status" || argv[0] === "whoami") {console.log(JSON.stringify({ isAuthenticated: authenticated }));process.exit(0);}+if (argv[0] === "models" && argv.includes("--refresh")) {+ if (process.env.FAKE_ACP_MODELS_REFRESH_FROM && process.env.FAKE_ACP_MODELS_FILE) {+ writeFileSync(process.env.FAKE_ACP_MODELS_FILE, readFileSync(process.env.FAKE_ACP_MODELS_REFRESH_FROM));+ }+ process.exit(0);+}if (argv[0] === "models" || argv.includes("--list-models")) {const failOnce = process.env.FAKE_ACP_VERBOSE_FAIL_ONCE;if (failOnce && argv.includes("--verbose") && !existsSync(failOnce)) {diff --git a/shared/opencode-model-id.ts b/shared/opencode-model-id.tsnew file mode 100644index 0000000000..3e07c308f0--- /dev/null+++ b/shared/opencode-model-id.ts@@ -0,0 +1,22 @@+const TYPED_PREFIX = "typed::";+const OPENCODE_MODEL = /^[A-Za-z0-9][\w.-]{0,63}\/[A-Za-z0-9][\w.:@+/-]{0,199}$/u;++function openCodeModelId(value: string): string | null {+ const id = value.trim();+ return OPENCODE_MODEL.test(id) && !id.endsWith("/") ? id : null;+}++/** The saved model id of a `provider/model` id typed by hand for OpenCode, or null when `value` cannot be one. OpenCode+ * (1.19.4) runs a model its catalog lacks once the model is declared under its provider in OpenCode's config, which the+ * server does for a typed id only: a plain saved id OpenCode no longer lists still falls back to its default. */+export function typedOpenCodeModelId(value: string): string | null {+ const id = openCodeModelId(value);+ return id ? `${TYPED_PREFIX}${id}` : null;+}++/** The OpenCode `provider/model` id inside a saved id typed by hand, or null for any other id. */+export function typedOpenCodeModel(savedId: string | undefined): string | null {+ if (!savedId?.startsWith(TYPED_PREFIX)) return null;+ const id = savedId.slice(TYPED_PREFIX.length);+ return openCodeModelId(id) === id ? id : null;+}diff --git a/src/components/ModelPicker.dom.test.ts b/src/components/ModelPicker.dom.test.tsindex 1221c5d29a..9e64d6cc53 100644--- a/src/components/ModelPicker.dom.test.ts+++ b/src/components/ModelPicker.dom.test.ts@@ -254,6 +254,30 @@ describe("the full picker's search and the rows around it", () => {});});+describe("an OpenCode model typed by hand", () => {+ const typed = "venice/deepseek-v4-1-flash-uncensored";+ const opencode: InstanceInfo = {+ instanceId: "opencode", driverKind: "opencodeGo", displayName: "OpenCode", access: "subscription",+ snapshot: { state: "available", version: "1.19.4", authenticated: true },+ models: { default: "opencode/big-pickle", options: [{ id: "opencode/big-pickle", label: "Zen · Big Pickle" }] },+ };+ const onOpenCode = (model: string): Bot => ({ ...scout(), modelSelection: { instanceId: "opencode", model } });++ it.each([false, true])("is picked from the search box (advanced: %s) and then named as typed by hand", async (advanced) => {+ fixture.advanced = advanced;+ fixture.instances = [opencode];+ render(onOpenCode("opencode/big-pickle"));+ await openWith("click");+ type(document.querySelector<HTMLInputElement>("[data-menu-search]")!, typed);+ const row = [...document.querySelectorAll<HTMLElement>("[data-menu-row]")].find((candidate) => candidate.textContent?.includes("typed by hand"))!;+ flushSync(() => row.click());+ await settle();+ expect(fixture.dispatch).toHaveBeenLastCalledWith(expect.objectContaining({ type: "setModel", selection: { instanceId: "opencode", model: `typed::${typed}` } }));+ render(onOpenCode(`typed::${typed}`));+ expect(chip().textContent).toContain(`${typed} · typed by hand`);+ });+});+describe("the floating menu and the pointer", () => {it("stays open for a click inside its portal and closes for one outside, without taking focus", async () => {await openWith("click");diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsxindex c654e8fb51..09d7cf59e1 100644--- a/src/components/ModelPicker.tsx+++ b/src/components/ModelPicker.tsx@@ -7,7 +7,7 @@ import type { ModelVariantOption } from "../../shared/runtime-events";import { filterCustomModels, partitionCustomModels, suggestedModels } from "@/lib/custom-models";import { configuredModelInstances, isClaudeAccount, isCustomOnly, SIGN_IN_FAMILY_LABEL, signInFamily } from "@/lib/engine-rail";import { modelName, simpleModelMenu } from "@/lib/simple-model-menu";-import { choiceIsSelected, modelChoices, modelSelectionForPick, type ModelChoice } from "@/lib/model-choices";+import { choiceIsSelected, modelChoices, modelSelectionForPick, takesTypedModels, withTypedModels, type ModelChoice } from "@/lib/model-choices";export { modelSelectionForPick } from "@/lib/model-choices";import { pickerPlacement, type PickerPlacement } from "@/lib/picker-placement";import type { Typeahead } from "@/lib/menu-keys";@@ -247,8 +247,7 @@ export function ModelPicker({const [scope, setScope] = useState<"bot" | "thread">("thread");const advanced = useAdvancedMode();const ownerOrAdmin = useOwnerOrAdmin();- // A guest changes only their own conversation's model, never the shared bot's default; thread-only until- // authority loads.+ // A guest changes only their own conversation's model, never the shared bot's default; thread-only until authority loads.const simpleUpdatesBotDefault = ownerOrAdmin === true;const [fullView, setFullView] = useState(false);const [pendingSwitch, setPendingSwitch] = useState<{ botId: string; threadId: string;@@ -307,8 +306,9 @@ export function ModelPicker({}, [open, placement]);const selection = bot.modelSelection;- const active = state.instances.find((instance) => instance.instanceId === selection.instanceId);- const pickerInstances = configuredModelInstances(state.instances, selection.instanceId);+ const instances = withTypedModels(state.instances, selection, query);+ const active = instances.find((instance) => instance.instanceId === selection.instanceId);+ const pickerInstances = configuredModelInstances(instances, selection.instanceId);const selectedVariantLabel = selection.variant === undefined ? undefined : variantLabel(active?.models.options.find((option) => option.id === selection.model)?.variants?.find((option) => option.id === selection.variant)?? { id: selection.variant, label: selection.variant },@@ -680,7 +680,7 @@ export function ModelPicker({);const simpleMenu = simpleView ? simpleModelMenu({- instances: state.instances,+ instances,listed: pickerInstances,selection,bot: { name: profile.name, selection: profile.modelSelection, follows },@@ -820,7 +820,7 @@ export function ModelPicker({</div>) : (<>- {((pane === "main" && official.length > COMPACT_MODEL_COUNT) ||+ {((pane === "main" && (official.length > COMPACT_MODEL_COUNT || takesTypedModels(railInstance))) ||(pane === "custom" && custom.length > COMPACT_MODEL_COUNT)) && (<ModelSearchvalue={query}diff --git a/src/lib/model-choices.test.ts b/src/lib/model-choices.test.tsindex 0518f41f91..78a2878468 100644--- a/src/lib/model-choices.test.ts+++ b/src/lib/model-choices.test.ts@@ -1,7 +1,13 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";-import type { InstanceInfo } from "@/state/store";-import { choiceIsSelected, modelChoices } from "./model-choices";+import type { InstanceInfo, ModelSelection } from "@/state/store";+import { choiceIsSelected, modelChoices, withTypedModels } from "./model-choices";+import { simpleModelMenu } from "./simple-model-menu";++vi.hoisted(() => {+ vi.stubGlobal("window", {});+ vi.stubGlobal("localStorage", { getItem: () => null, setItem: () => {} });+});const antigravity = {instanceId: "google",@@ -23,3 +29,35 @@ describe("Antigravity model choices", () => {expect(choiceIsSelected(choices[1]!, { instanceId: "google", model: "gemini-3.8-flash", variant: "medium" })).toBe(true);});});++describe("OpenCode models typed by hand", () => {+ const opencode = {+ instanceId: "opencode", driverKind: "opencodeGo", displayName: "OpenCode", access: "subscription",+ snapshot: { state: "available", version: "1.19.4", authenticated: true },+ models: { default: "opencode/big-pickle", options: [+ { id: "opencode/big-pickle", label: "Zen · Big Pickle" }, { id: "venice/deepseek-v4-flash", label: "Venice · DeepSeek V4 Flash" },+ ] },+ } as InstanceInfo;+ const typed = "venice/deepseek-v4-1-flash-uncensored";+ const onPickle: ModelSelection = { instanceId: "opencode", model: "opencode/big-pickle" };+ const added = (instances: InstanceInfo[]) => instances[0]!.models.options.slice(opencode.models.options.length);++ it("offers a provider/model id typed in the search box, saved as typed and labelled typed by hand", () => {+ expect(added(withTypedModels([opencode], onPickle, ` ${typed} `))).toEqual([{ id: `typed::${typed}`, label: `${typed} · typed by hand` }]);+ const menu = simpleModelMenu({ instances: [opencode], listed: withTypedModels([opencode], onPickle, typed), selection: onPickle,+ bot: { name: "Pepper", selection: onPickle }, query: typed, expanded: new Set(), probing: new Set(), loading: false });+ expect(menu.search).toBe(true);+ expect(menu.groups[0]!.body).toMatchObject({ kind: "models", rows: [{ option: { id: `typed::${typed}` }, label: `${typed} · typed by hand` }] });+ });++ it("keeps a typed selection listed and named, and adds nothing the catalog has or that is not an id", () => {+ expect(added(withTypedModels([opencode], { instanceId: "opencode", model: `typed::${typed}` }, ""))).toEqual([+ { id: `typed::${typed}`, label: `${typed} · typed by hand` },+ ]);+ for (const query of ["venice/deepseek-v4-flash", "deepseek", "venice/ x"]) {+ expect(withTypedModels([opencode], onPickle, query)[0]).toBe(opencode);+ }+ expect(withTypedModels([opencode], { instanceId: "opencode", model: "venice/retired" }, "")[0]).toBe(opencode);+ expect(withTypedModels([antigravity], { instanceId: "google", model: `typed::${typed}` }, typed)[0]).toBe(antigravity);+ });+});diff --git a/src/lib/model-choices.ts b/src/lib/model-choices.tsindex 23303bfbfe..daf683b01f 100644--- a/src/lib/model-choices.ts+++ b/src/lib/model-choices.ts@@ -1,4 +1,6 @@import type { InstanceInfo, ModelSelection } from "@/state/store";+import { typedOpenCodeModel, typedOpenCodeModelId } from "../../shared/opencode-model-id";+import { t } from "./i18n";type ModelOption = InstanceInfo["models"]["options"][number];@@ -30,3 +32,21 @@ export function modelSelectionForPick(selection: ModelSelection, instance: Insta}return next;}++export function takesTypedModels(instance: InstanceInfo | undefined): boolean {+ return instance?.driverKind === "opencodeGo";+}++/** OpenCode runs a `provider/model` id its catalog lacks: offer the one in the search box, and keep the selected one listed. */+export function withTypedModels(instances: readonly InstanceInfo[], selection: ModelSelection, query: string): InstanceInfo[] {+ return instances.map((instance) => {+ if (!takesTypedModels(instance)) return instance;+ const listed = (id: string) => instance.models.options.some((option) => option.id === id);+ const selected = instance.instanceId === selection.instanceId && typedOpenCodeModel(selection.model) ? selection.model : null;+ const searched = typedOpenCodeModelId(query);+ const typed = [selected, searched && !listed(typedOpenCodeModel(searched)!) ? searched : null]+ .filter((id, index, all): id is string => id !== null && !listed(id) && all.indexOf(id) === index);+ return typed.length ? { ...instance, models: { ...instance.models,+ options: [...instance.models.options, ...typed.map((id) => ({ id, label: t("model.typedByHand", { id: typedOpenCodeModel(id)! }) }))] } } : instance;+ });+}diff --git a/src/lib/simple-model-menu.ts b/src/lib/simple-model-menu.tsindex 367110aaab..c57c6393fe 100644--- a/src/lib/simple-model-menu.ts+++ b/src/lib/simple-model-menu.ts@@ -4,7 +4,7 @@ import { t } from "./i18n";import { filterCustomModels, partitionCustomModels, suggestedModels } from "./custom-models";import { isCustomOnly, SIGN_IN_FAMILY_LABEL, signInFamily, splitEngineRail } from "./engine-rail";import { displayModelLabel, shortModelLabel } from "./model-friendly";-import { choiceIsSelected, modelChoices, type ModelChoice } from "./model-choices";+import { choiceIsSelected, modelChoices, takesTypedModels, type ModelChoice } from "./model-choices";export type ModelOption = InstanceInfo["models"]["options"][number];@@ -141,7 +141,7 @@ export function simpleModelMenu(input: SimpleMenuInput): SimpleMenu {const models = new Map(listed.map((instance) => [instance.instanceId, listedModels(instance)]));const total = listed.filter((instance) => !instance.policy && !needsCli(instance)).reduce((sum, instance) => sum + models.get(instance.instanceId)!.all.length, 0);- const search = total > SIMPLE_SEARCH_AFTER;+ const search = total > SIMPLE_SEARCH_AFTER || listed.some((instance) => takesTypedModels(instance) && !instance.policy && !needsCli(instance));const query = search ? input.query.trim() : "";const { subscription, api, custom } = splitEngineRail(listed);const ordered = [...subscription, ...api, ...custom];diff --git a/src/locales/en.json b/src/locales/en.jsonindex 4c4330aa86..2b08deb33c 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2922,6 +2922,7 @@"model.available": "{count} available","model.noProviders": "No model providers are available.","model.noMatch": "Nothing matches “{query}”",+ "model.typedByHand": "{id} · typed by hand","model.section.default": "Default model","model.section.starting": "Starting model for the new bot and its threads.","model.section.threads": "For groups and every thread that uses the bot's model. A thread keeps its own model only when you pick one in it.",