Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Let a local Ollama on the built-in OpenAI-compatible server set its reply wait (#4316)

Aditya Umale3c165f55d0da
diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.ts
index f31b9cc6d4..ce8707fb07 100644
--- a/server/routes/instances.test.ts
+++ b/server/routes/instances.test.ts
@@ -3,7 +3,7 @@ import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { afterEach, describe, expect, it } from "vitest";
-import type { AppConfig } from "../config.ts";
+import { instanceConfigs, type AppConfig } from "../config.ts";
import type { ProviderAuthenticationStart, ProviderAuthenticationStatus } from "../contracts.ts";
import { ENGINE_LIST_REUSE_MS, ProviderRegistry } from "../harness/registry.ts";
import { json, readBody } from "../harness/http.ts";
@@ -203,6 +203,21 @@ describe("a server's reply wait", () => {
for (const bad of [0, 61, 2.5, "10"]) expect(await status("openai-compat-1", { replyWaitMinutes: bad })).toBe(400);
expect(persisted).toHaveLength(2);
});
+
+ it("saves minutes for the built-in OpenAI-compatible server, such as a local Ollama set by its base URL", async () => {
+ const persisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];
+ const cfg = { openaiCompat: { url: "http://127.0.0.1:11434/v1" } };
+ const { call } = await serve({
+ cfg: cfg as unknown as AppConfig,
+ persistProviderInstance: async (_id: string, instances: typeof persisted[number]) => {
+ persisted.push(structuredClone(instances));
+ (cfg as { instances?: unknown }).instances = instances;
+ },
+ });
+ await call("PATCH", "/api/instances/openaiCompat", { replyWaitMinutes: 30 });
+ expect(persisted.at(-1)!.openaiCompat).toEqual({ driver: "openai-compat", config: { replyWaitMinutes: 30 } });
+ expect(instanceConfigs(cfg as unknown as AppConfig).openaiCompat!.config).toMatchObject({ url: "http://127.0.0.1:11434/v1", replyWaitMinutes: 30 });
+ });
});
describe("hiding a provider", () => {
diff --git a/server/routes/instances.ts b/server/routes/instances.ts
index 8dc54c2038..d1292f2f85 100644
--- a/server/routes/instances.ts
+++ b/server/routes/instances.ts
@@ -347,7 +347,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {
}
if (body.replyWaitMinutes !== undefined) {
if (entry.driver !== "openai-compat") return json(res, 400, { error: "The reply wait is available for OpenAI-compatible servers only." });
- const { replyWaitMinutes: _previous, ...rest } = entry.config as Record<string, unknown>;
+ const { replyWaitMinutes: _previous, ...rest } = (entry.config ?? {}) as Record<string, unknown>;
entry.config = body.replyWaitMinutes === null ? rest : { ...rest, replyWaitMinutes: body.replyWaitMinutes };
}
if (body.displayName !== undefined) entry.displayName = body.displayName;
diff --git a/src/components/OpenAiCompatServers.test.ts b/src/components/OpenAiCompatServers.test.ts
index ac3196d204..7a1ea89820 100644
--- a/src/components/OpenAiCompatServers.test.ts
+++ b/src/components/OpenAiCompatServers.test.ts
@@ -2,7 +2,7 @@ import { Children, createElement, isValidElement, type ReactElement, type ReactN
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import * as store from "@/state/store";
-import { modelIds, OtherOpenAiCompatServers, LmStudioServer, lmStudioBaseUrl } from "./OpenAiCompatServers";
+import { BuiltInReplyWait, modelIds, OtherOpenAiCompatServers, LmStudioServer, lmStudioBaseUrl } from "./OpenAiCompatServers";
const fixture = vi.hoisted(() => ({ counting: false, values: [] as unknown[], index: 0, api: vi.fn(), track: vi.fn() }));
vi.mock("react", async (original) => {
@@ -123,9 +123,13 @@ describe("adding another OpenAI-compatible server", () => {
});
describe("how long a server may take to reply", () => {
- type Props = { children?: ReactNode; servers?: unknown; value?: unknown; onChange?: (event: { target: { value: string } }) => void; "aria-label"?: string };
+ type Props = { children?: ReactNode; servers?: unknown; value?: unknown; onChange?: (event: { target: { value: string } }) => void; onPick?: unknown; "aria-label"?: string };
const nodes = (tree: ReactNode): Array<ReactElement<Props>> =>
Children.toArray(tree).flatMap((child) => isValidElement<Props>(child) ? [child, ...nodes(child.props.children)] : []);
+ const waitPicker = (tree: ReactNode) => {
+ const picker = nodes(tree).find((node) => node.props.onPick !== undefined)!;
+ return (picker.type as (props: Props) => ReactElement<Props>)(picker.props);
+ };
function waitSelect(replyWaitMinutes?: number) {
vi.stubGlobal("window", {});
const servers = [instance("openai-compat-1", "Ollama", { url: "http://127.0.0.1:11434/v1", ...(replyWaitMinutes ? { replyWaitMinutes } : {}) })];
@@ -136,7 +140,23 @@ describe("how long a server may take to reply", () => {
fixture.counting = true;
fixture.index = 0;
try {
- return nodes((added.type as (props: Props) => ReactNode)(added.props)).find((node) => node.props["aria-label"] === "How long to wait for Ollama to reply")!;
+ return waitPicker((added.type as (props: Props) => ReactNode)(added.props));
+ } finally {
+ fixture.counting = false;
+ }
+ }
+
+ function builtInSelect(url: string) {
+ vi.stubGlobal("window", {});
+ vi.spyOn(store, "useStore").mockReturnValue({
+ state: { ...store.initialState, config: { openaiCompat: { url } } as unknown as store.ConfigStatus, instances: [instance("openaiCompat", "Other (OpenAI-compatible)")] },
+ dispatch: vi.fn(), flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),
+ });
+ fixture.counting = true;
+ fixture.index = 0;
+ try {
+ const tree = BuiltInReplyWait();
+ return tree && waitPicker(tree);
} finally {
fixture.counting = false;
}
@@ -157,6 +177,20 @@ describe("how long a server may take to reply", () => {
expect(fixture.api).toHaveBeenLastCalledWith("/api/instances/openai-compat-1", { method: "PATCH", body: JSON.stringify({ replyWaitMinutes: null }) });
});
+ it("offers the same wait for the built-in server once its base URL is set, such as a local Ollama", async () => {
+ fixture.values = [];
+ fixture.api.mockReset();
+ fixture.api.mockResolvedValue({ instances: [] });
+ const select = builtInSelect("http://localhost:11434/v1")!;
+ expect(select.props["aria-label"]).toBe("How long to wait for Other (OpenAI-compatible) to reply");
+ expect(JSON.stringify(select.props.children)).toContain("Wait 30 min");
+ select.props.onChange!({ target: { value: "30" } });
+ await Promise.resolve();
+ expect(fixture.api).toHaveBeenLastCalledWith("/api/instances/openaiCompat", { method: "PATCH", body: JSON.stringify({ replyWaitMinutes: 30 }) });
+ fixture.values = [];
+ expect(builtInSelect("")).toBeNull();
+ });
+
it("shows a saved wait that is not one of the usual choices", () => {
fixture.values = [];
const html = JSON.stringify(waitSelect(45).props.children);
diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsx
index 4ad396859b..1c48225146 100644
--- a/src/components/OpenAiCompatServers.tsx
+++ b/src/components/OpenAiCompatServers.tsx
@@ -19,6 +19,56 @@ 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;
+const saveReplyWait = (instanceId: string, minutes: number | null): Promise<{ instances?: unknown }> =>
+ api(`/api/instances/${encodeURIComponent(instanceId)}`, { method: "PATCH", body: JSON.stringify({ replyWaitMinutes: minutes }) });
+
+function ReplyWaitSelect({ server, disabled, onPick }: { server: InstanceInfo; disabled: boolean; onPick: (minutes: number | null) => void }) {
+ return (
+ <Select
+ size="sm"
+ className="shrink-0"
+ value={server.replyWaitMinutes ?? ""}
+ onChange={(event) => onPick(event.target.value ? Number(event.target.value) : null)}
+ disabled={disabled}
+ aria-label={t("apiInstances.replyWaitFor", { name: server.displayName })}
+ title={t("apiInstances.replyWaitHint")}
+ >
+ <option value="">{t("apiInstances.replyWaitDefault")}</option>
+ {[...new Set([...REPLY_WAIT_CHOICES, ...(server.replyWaitMinutes ? [server.replyWaitMinutes] : [])])].sort((a, b) => a - b).map((minutes) => (
+ <option key={minutes} value={minutes}>{t("apiInstances.replyWaitMinutes", { minutes: String(minutes) })}</option>
+ ))}
+ </Select>
+ );
+}
+
+/** The built-in server whose base URL is set above, often a local Ollama: the same wait as an added server. */
+export function BuiltInReplyWait() {
+ const { state, dispatch, refreshInstances } = useStore();
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const server = state.instances.find((instance) => instance.instanceId === "openaiCompat" && instance.driverKind === "openai-compat");
+ if (!server || !state.config?.openaiCompat?.url) return null;
+ const pick = (minutes: number | null) => {
+ if (busy) return;
+ setBusy(true);
+ setError(null);
+ void saveReplyWait(server.instanceId, minutes)
+ .then(async ({ instances }) => {
+ if (Array.isArray(instances)) dispatch({ type: "instances", instances: instances as InstanceInfo[] });
+ else await refreshInstances({ reportErrors: true });
+ })
+ .catch((e: Error) => setError(e.message || t("apiInstances.failed")))
+ .finally(() => setBusy(false));
+ };
+ return (
+ <div className="flex flex-col gap-1">
+ <ReplyWaitSelect server={server} disabled={busy} onPick={pick} />
+ <p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.replyWaitHint")}</p>
+ {error && <div role="alert" className="text-[12px] leading-4 text-danger">{error}</div>}
+ </div>
+ );
+}
+
export function OtherOpenAiCompatServers() {
const { state } = useStore();
return <AddedServers servers={addedServers(state.instances)} />;
@@ -71,23 +121,11 @@ function AddedServers({ servers }: { servers: Array<InstanceInfo & { url?: strin
<div className="truncate text-[12px] text-ink">{server.displayName}</div>
{server.url && <div className="truncate font-mono text-[11px] text-ink-secondary">{server.url}</div>}
</div>
- <Select
- size="sm"
- className="shrink-0"
- value={server.replyWaitMinutes ?? ""}
- onChange={(event) => {
- const minutes = event.target.value ? Number(event.target.value) : null;
- run("other", () => api(`/api/instances/${encodeURIComponent(server.instanceId)}`, { method: "PATCH", body: JSON.stringify({ replyWaitMinutes: minutes }) }));
- }}
+ <ReplyWaitSelect
+ server={server}
disabled={busy !== null}
- aria-label={t("apiInstances.replyWaitFor", { name: server.displayName })}
- title={t("apiInstances.replyWaitHint")}
- >
- <option value="">{t("apiInstances.replyWaitDefault")}</option>
- {[...new Set([...REPLY_WAIT_CHOICES, ...(server.replyWaitMinutes ? [server.replyWaitMinutes] : [])])].sort((a, b) => a - b).map((minutes) => (
- <option key={minutes} value={minutes}>{t("apiInstances.replyWaitMinutes", { minutes: String(minutes) })}</option>
- ))}
- </Select>
+ onPick={(minutes) => run("other", () => saveReplyWait(server.instanceId, minutes))}
+ />
<button
type="button"
onClick={() => run("other", () => api(`/api/instances/${encodeURIComponent(server.instanceId)}/refresh-models`, { method: "POST" }))}
diff --git a/src/components/keys/KeysPage.dom.test.ts b/src/components/keys/KeysPage.dom.test.ts
index cbbd051b2d..97cc4c0d94 100644
--- a/src/components/keys/KeysPage.dom.test.ts
+++ b/src/components/keys/KeysPage.dom.test.ts
@@ -7,6 +7,7 @@ import { setLocale } from "@/lib/i18n";
const fx = vi.hoisted(() => ({
config: {} as Record<string, unknown>,
+ instances: [] as unknown[],
listeners: new Set<() => void>(),
api: vi.fn(),
dispatch: vi.fn(),
@@ -20,7 +21,7 @@ vi.mock("@/state/store", async (original) => {
api: (...args: unknown[]) => fx.api(...args),
useStore: () => {
const config = useSyncExternalStore(subscribe, () => fx.config);
- return { state: { ...actual.initialState, config, instances: [] }, dispatch: fx.dispatch };
+ return { state: { ...actual.initialState, config, instances: fx.instances as never }, dispatch: fx.dispatch };
},
};
});
@@ -72,6 +73,7 @@ beforeEach(() => {
if (action.type === "configStatus") setConfig(action.config!);
});
fx.config = { composio: { configured: false }, box: { configured: false }, vps: { configured: false, sshAlias: "" } };
+ fx.instances = [];
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
@@ -174,6 +176,20 @@ describe("the keys page", () => {
});
});
+describe("the OpenAI-compatible server row", () => {
+ it("offers the reply wait for the built-in server once its base URL is set, such as a local Ollama", () => {
+ const waitFor = () => host.querySelector('select[aria-label="How long to wait for Other (OpenAI-compatible) to reply"]');
+ fx.instances = [{ instanceId: "openaiCompat", driverKind: "openai-compat", displayName: "Other (OpenAI-compatible)", snapshot: { state: "available" } }];
+ page();
+ expect(waitFor()).toBeNull();
+ flushSync(() => setConfig({ ...fx.config, openaiCompat: { url: "http://localhost:11434/v1" } }));
+ expect(row("openaiCompat")).not.toBeNull();
+ expect(waitFor()).not.toBeNull();
+ flushSync(() => setConfig({ ...fx.config, openaiCompat: { url: "" } }));
+ expect(waitFor()).toBeNull();
+ });
+});
+
describe("Boat's credit offer on the Boat card", () => {
const offer = () => row("box")!.querySelector<HTMLElement>("[data-boat-offer]");
const buttons = () => [...offer()!.querySelectorAll<HTMLButtonElement>("button")];
diff --git a/src/components/keys/KeysPage.tsx b/src/components/keys/KeysPage.tsx
index 30d89e7a31..af84218da1 100644
--- a/src/components/keys/KeysPage.tsx
+++ b/src/components/keys/KeysPage.tsx
@@ -5,7 +5,7 @@ import { cn } from "@/lib/cn";
import { scrollParent, scrollWithin } from "@/lib/scroll-within";
import { t } from "@/lib/i18n";
import { BoatOfferPanel } from "../BoatOffer";
-import { LmStudioServer, OtherOpenAiCompatServers } from "../OpenAiCompatServers";
+import { BuiltInReplyWait, LmStudioServer, OtherOpenAiCompatServers } from "../OpenAiCompatServers";
import { KEY_CATALOG, KEY_SECTIONS, keyMatches, savedState, type KeyEntry, type KeyId, type KeySectionId } from "./key-catalog";
import { finishKeyFocus, useKeyFocus, type KeyFocusRequest } from "./key-focus";
import { AnthropicEveryClaudeBot, OpenAiCompatUrl, OpenCodeProviderKeys, VpsConnection } from "./KeyPanels";
@@ -22,7 +22,7 @@ const PANELS: Partial<Record<KeyId, () => ReactNode>> = {
const EXTRAS: Partial<Record<KeyId, () => ReactNode>> = {
anthropic: () => <AnthropicEveryClaudeBot />,
- openaiCompat: () => <><OpenAiCompatUrl /><OtherOpenAiCompatServers /></>,
+ openaiCompat: () => <><OpenAiCompatUrl /><BuiltInReplyWait /><OtherOpenAiCompatServers /></>,
box: () => <BoatOfferPanel />,
};