Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(settings): Google Gemini preset for OpenAI-compatible servers (#4264)
Aditya Umale1de227e3edcc
diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.tsindex fa377c6455..af64a1bcc0 100644--- a/server/drivers/openai-compat.test.ts+++ b/server/drivers/openai-compat.test.ts@@ -3,6 +3,7 @@ import { recordEvents } from "../testing/events.ts";import { buildTurnContext, replaysNatively } from "../turn-context.ts";import { instanceConfigs } from "../config.ts";import { OpenAICompatDriver } from "./openai-compat.ts";+import { flushNativeLogs } from "./native.ts";describe("OpenAICompatDriver", () => {const savedUrl = process.env.OPENAI_COMPAT_URL;@@ -135,6 +136,38 @@ describe("OpenAICompatDriver", () => {await inst.dispose();});+ it("lists Gemini's chat models by their plain IDs", async () => {+ const fetchMock = vi.fn(async () => Response.json({ object: "list", data: [+ { id: "models/gemini-2.5-pro", object: "model", owned_by: "google" },+ { id: "models/gemini-embedding-001", object: "model", owned_by: "google" },+ { id: "models/gemini-2.5-flash", object: "model", owned_by: "google" },+ { id: "models/gemini-2.5-flash-preview-tts", object: "model", owned_by: "google" },+ { id: "models/imagen-4.0-generate-001", object: "model", owned_by: "google" },+ { id: "models/gemini-2.5-flash-image", object: "model", owned_by: "google" },+ { id: "models/gemini-live-2.5-flash-preview", object: "model", owned_by: "google" },+ ] }));+ vi.stubGlobal("fetch", fetchMock);+ const inst = await OpenAICompatDriver.create({+ instanceId: "openai-compat-1", displayName: "Google Gemini", enabled: true,+ config: OpenAICompatDriver.decodeConfig({ url: "https://generativelanguage.googleapis.com/v1beta/openai", key: "gemini-fixture" }),+ environment: {},+ });+ await vi.waitFor(() => expect(inst.models.options.map((option) => option.id)).toEqual(["gemini-2.5-pro", "gemini-2.5-flash"]));+ expect(fetchMock).toHaveBeenCalledWith("https://generativelanguage.googleapis.com/v1beta/openai/models", expect.anything());+ await inst.dispose();+ });++ it("keeps other servers' model IDs as they list them", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ data: [{ id: "models/gemini-2.5-pro" }, { id: "text-embedding-3-small" }] })));+ const inst = await OpenAICompatDriver.create({+ instanceId: "openai-compat-2", displayName: "Proxy", enabled: true,+ config: OpenAICompatDriver.decodeConfig({ url: "https://llm.example.com/v1", key: "sk-fixture" }),+ environment: {},+ });+ await vi.waitFor(() => expect(inst.models.options.map((option) => option.id)).toEqual(["models/gemini-2.5-pro", "text-embedding-3-small"]));+ await inst.dispose();+ });+it("reports unavailable without an API key", async () => {const inst = await OpenAICompatDriver.create({instanceId: "test-1",@@ -1131,6 +1164,8 @@ describe("OpenAICompatDriver", () => {const item = recorder.events.find((e) => e.type === "item.completed");expect(item).toMatchObject({ text: "start middle end" });+ // The native log's flush timer is shared across tests and pending only sometimes; it is not the idle timer.+ flushNativeLogs();expect(vi.getTimerCount()).toBe(0);recorder.stop();diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex fe6deaede4..af78e49f24 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -50,6 +50,21 @@ const OPENAI_MODELS: ModelCatalog = {],};+/** Google's Gemini API, added as an OpenAI-compatible server (Settings → API keys → Other). */+function isGeminiOrigin(url: string): boolean {+ try {+ return new URL(url).origin === "https://generativelanguage.googleapis.com";+ } catch {+ return false;+ }+}++/** Gemini's /models names each model "models/<id>" and also lists embedding, speech, image and live-audio models. */+function geminiChatModelId(id: string): string | null {+ const bare = id.replace(/^models\//, "");+ return bare.startsWith("gemini-") && !/embedding|tts|image|live|native-audio/.test(bare) ? bare : null;+}+/** OpenAI's /models also lists embeddings, speech, images, moderation and Responses-only models. */export function isOpenAIChatModel(id: string): boolean {if (!/^(gpt-|chatgpt-|o\d)/i.test(id)) return false;@@ -179,6 +194,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {}: seeded;const openRouter = Boolean(apiKey) && !config.managedModels && isOpenRouterOrigin(config.url);+ const gemini = isGeminiOrigin(config.url);const freeTier = () => openRouter ? openRouterFreeTier(apiKey, config.url) : Promise.resolve(null);const fetchModels = async () => {@@ -233,7 +249,8 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {const seen = new Set<string>();const options: ModelCatalog["options"] = [];for (const row of rows) {- const id = typeof row.id === "string" ? row.id : "";+ const rawId = typeof row.id === "string" ? row.id : "";+ const id = gemini ? geminiChatModelId(rawId) ?? "" : rawId;if (!id || seen.has(id) || isContextName(id)) continue;seen.add(id);const label = typeof row.name === "string" && row.name.trim() ? row.name : id;diff --git a/src/components/OpenAiCompatServers.test.ts b/src/components/OpenAiCompatServers.test.tsindex 157acb6ee0..ac3196d204 100644--- a/src/components/OpenAiCompatServers.test.ts+++ b/src/components/OpenAiCompatServers.test.ts@@ -105,6 +105,21 @@ describe("adding another OpenAI-compatible server", () => {expect(fixture.track.mock.calls).toEqual([["api_key_saved", { provider: "custom_endpoint", via: "settings", result }]]);expect(JSON.stringify(fixture.track.mock.calls)).not.toMatch(/ada|example|ZZtest|SECRET/);});++ it("fills in Google Gemini, so only the AI Studio key is left to paste", async () => {+ fixture.values = [];+ fixture.api.mockReset();+ fixture.api.mockResolvedValueOnce({ instances: [] });+ const button = (text: string) => form().find((node) => node.type === "button" && JSON.stringify(node.props.children ?? "").includes(text))!;+ expect(JSON.stringify(form().map((node) => node.props.children ?? ""))).not.toContain("aistudio.google.com");+ button("Fill in Google Gemini").props.onClick!();+ expect(JSON.stringify(form().map((node) => node.props.children ?? ""))).toContain("aistudio.google.com/apikey");+ form().find((node) => node.props["aria-label"] === "API key")!.props.onChange!({ target: { value: "gemini-fixture" } });+ button("Add server").props.onClick!();+ await flush();+ expect(fixture.api).toHaveBeenCalledExactlyOnceWith("/api/instances/openai-compat", expect.objectContaining({ method: "POST" }));+ expect(JSON.parse(fixture.api.mock.calls[0][1].body)).toEqual({ displayName: "Google Gemini", url: "https://generativelanguage.googleapis.com/v1beta/openai", key: "gemini-fixture" });+ });});describe("how long a server may take to reply", () => {diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsxindex af3ee01765..4ad396859b 100644--- a/src/components/OpenAiCompatServers.tsx+++ b/src/components/OpenAiCompatServers.tsx@@ -16,6 +16,8 @@ const INPUT = cn(KEY_FIELD, "font-sans");/** A slow computer can take minutes before a local model's first words, so the wait is the person's call. */export const REPLY_WAIT_CHOICES = [5, 10, 20, 30, 60] as const;const ICON_BUTTON = "ui-icon-button shrink-0 hover:text-ink";+/** Google's Gemini API speaks the OpenAI protocol here; the key comes from Google AI Studio. */+export const GEMINI_PRESET = { name: "Google Gemini", url: "https://generativelanguage.googleapis.com/v1beta/openai" } as const;export function OtherOpenAiCompatServers() {const { state } = useStore();@@ -109,6 +111,15 @@ function AddedServers({ servers }: { servers: Array<InstanceInfo & { url?: strin</div>))}<div className="mt-2 flex flex-col gap-1.5">+ <button+ type="button"+ onClick={() => { setName(GEMINI_PRESET.name); setUrl(GEMINI_PRESET.url); }}+ disabled={busy !== null}+ className="ui-button self-start"+ >+ {t("apiInstances.geminiPreset")}+ </button>+ {url.trim() === GEMINI_PRESET.url && <p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.geminiKeyHint")}</p>}<input value={name} onChange={(e) => setName(e.target.value)} placeholder={t("apiInstances.name")} aria-label={t("apiInstances.name")}spellCheck={false} disabled={busy !== null} className={INPUT} /><input type="url" value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://api.example.com/v1" aria-label={t("apiInstances.url")}diff --git a/src/components/keys/key-catalog.test.ts b/src/components/keys/key-catalog.test.tsindex 75ce311c9c..ac188c206a 100644--- a/src/components/keys/key-catalog.test.ts+++ b/src/components/keys/key-catalog.test.ts@@ -107,6 +107,7 @@ describe("searching the keys", () => {expect(found("voice")).toEqual(expect.arrayContaining(["liveCalls", "liveKey", "elevenlabs", "fishAudio"]));expect(found("openai")).toEqual(expect.arrayContaining(["openai", "liveCalls", "liveKey", "imageOpenai"]));expect(found("gmail")).toEqual(["composio"]);+ expect(found("gemini")).toEqual(["openaiCompat"]);expect(found("no such key anywhere")).toEqual([]);});});diff --git a/src/components/keys/key-catalog.ts b/src/components/keys/key-catalog.tsindex f30d8ff150..2477c222d8 100644--- a/src/components/keys/key-catalog.ts+++ b/src/components/keys/key-catalog.ts@@ -117,7 +117,7 @@ export const KEY_CATALOG: readonly KeyEntry[] = [{ id: "lmStudio", section: "servers", labelKey: "lmStudio.title", purposeKey: "keys.purpose.lmStudio", name: "LM Studio", env: [],words: ["lm studio", "lmstudio", "llm studio", "local", "bionic"], mark: { icon: Server }, kind: "panel" },{ id: "openaiCompat", section: "servers", labelKey: "keys.openaiCompat.label", purposeKey: "keys.purpose.openaiCompat", name: "OpenAI-compatible", env: ["OPENAI_COMPAT_API_KEY", "OPENAI_COMPAT_URL"],- words: ["openai-compatible", "openai compatible", "ollama", "together", "base url", "server", "endpoint"], mark: { icon: Server }, kind: "key",+ words: ["openai-compatible", "openai compatible", "ollama", "together", "gemini", "google ai studio", "base url", "server", "endpoint"], mark: { icon: Server }, kind: "key",target: { patch: (value) => ({ openaiCompat: { key: value } }), saved: (config) => flag(config.openaiCompat), placeholder: "…", placeholderKey: "keys.openaiCompat.placeholder",href: "https://platform.openai.com/docs/api-reference", test: "openaiCompat", analytics: "openai_compat" } },{ id: "liveCalls", section: "voice", labelKey: "call.live.key", purposeKey: "keys.purpose.liveCalls", name: "OpenAI", env: [],diff --git a/src/locales/en.json b/src/locales/en.jsonindex a65d420857..f5d08c4ac7 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6633,6 +6633,8 @@"apiInstances.key": "API key","apiInstances.models": "Model IDs, separated by commas (optional)","apiInstances.modelsHint": "Leave the model IDs empty to detect them. If the model picker then shows only sample models, this server does not list its models: enter them here.",+ "apiInstances.geminiPreset": "Fill in Google Gemini",+ "apiInstances.geminiKeyHint": "Paste a Gemini API key from Google AI Studio (aistudio.google.com/apikey). Models are detected after you add it.","apiInstances.add": "Add server","apiInstances.adding": "Adding…","apiInstances.remove": "Remove {name}",