Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(providers): choose how long to wait for a local model's reply (#3805)
Azad Jagtapa62301002515
diff --git a/server/claude-accounts.ts b/server/claude-accounts.tsindex 1667316444..57edb5c5b0 100644--- a/server/claude-accounts.ts+++ b/server/claude-accounts.ts@@ -17,6 +17,8 @@ export const instanceSettingsSchema = z.object({displayName: displayName.optional(),configDir: configDir.optional(),tools: z.boolean().optional(),+ /** null goes back to the server's default wait. */+ replyWaitMinutes: z.number().int().min(1).max(60).nullable().optional(),}).strict().refine((value) => Object.keys(value).length > 0, "No settings supplied");function rawConfig(entry: InstanceConfig): Record<string, unknown> {diff --git a/server/drivers/openai-compat-reply-wait.test.ts b/server/drivers/openai-compat-reply-wait.test.tsnew file mode 100644index 0000000000..c39c2e8249--- /dev/null+++ b/server/drivers/openai-compat-reply-wait.test.ts@@ -0,0 +1,28 @@+import { afterEach, expect, it, vi } from "vitest";++const runtime = vi.hoisted(() => ({ timeouts: [] as number[] }));+vi.mock("./openai-chat.ts", () => ({+ createOpenAIChatRuntime: (options: { timeoutMs: number }) => {+ runtime.timeouts.push(options.timeoutMs);+ return { adapter: {}, dispose: async () => {} };+ },+}));++const { OpenAICompatDriver } = await import("./openai-compat.ts");++afterEach(() => { vi.unstubAllEnvs(); runtime.timeouts = []; });++const create = (config: Record<string, unknown>) => OpenAICompatDriver.create({+ instanceId: "openai-compat-1", displayName: "Ollama", enabled: true,+ config: { url: "http://127.0.0.1:11434/v1", apiKeyEnv: "FIXTURE_KEY", ...config },+ environment: { FIXTURE_KEY: "synthetic-not-a-secret" },+});++it("waits as long as the server's own setting says, over the server-wide default", async () => {+ vi.stubEnv("OPENMAUS_OPENAI_COMPAT_IDLE_TIMEOUT_MS", "5000");+ await create({ replyWaitMinutes: 20 });+ await create({});+ vi.unstubAllEnvs();+ await create({});+ expect(runtime.timeouts).toEqual([20 * 60_000, 5_000, 180_000]);+});diff --git a/server/drivers/openai-compat.test.ts b/server/drivers/openai-compat.test.tsindex 13930f1cd6..fa377c6455 100644--- a/server/drivers/openai-compat.test.ts+++ b/server/drivers/openai-compat.test.ts@@ -1170,3 +1170,14 @@ it("openai-compat preserves an explicit tools-off connection and rejects ambiguoexpect(OpenAICompatDriver.decodeConfig({ tools: true })).toMatchObject({ tools: true });expect(() => OpenAICompatDriver.decodeConfig({ tools: "false" })).toThrow("tools must be a boolean");});++describe("how long a turn waits for a reply", () => {+ it("accepts 1 to 60 whole minutes and refuses anything else", () => {+ expect(OpenAICompatDriver.decodeConfig({ url: "http://127.0.0.1:11434/v1", replyWaitMinutes: 20 })).toMatchObject({ replyWaitMinutes: 20 });+ expect(OpenAICompatDriver.decodeConfig({ url: "http://127.0.0.1:11434/v1" })).not.toHaveProperty("replyWaitMinutes");+ for (const bad of [0, 61, 2.5, "10", null]) {+ expect(() => OpenAICompatDriver.decodeConfig({ url: "http://127.0.0.1:11434/v1", replyWaitMinutes: bad })).toThrow(/replyWaitMinutes/);+ }+ });+});+diff --git a/server/drivers/openai-compat.ts b/server/drivers/openai-compat.tsindex c340a91fef..c4f3bf983d 100644--- a/server/drivers/openai-compat.ts+++ b/server/drivers/openai-compat.ts@@ -53,8 +53,13 @@ export interface OpenAICompatConfig {model?: string;provider?: string;managedModels?: string[];+ /** How long a turn waits for the next piece of a reply before giving up; unset follows the server's default. */+ replyWaitMinutes?: number;}+export const MAX_REPLY_WAIT_MINUTES = 60;+const isReplyWait = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) >= 1 && (value as number) <= MAX_REPLY_WAIT_MINUTES;+function positiveTokens(value: unknown): number | undefined {return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : undefined;}@@ -96,10 +101,12 @@ function decodeConfig(raw: unknown): OpenAICompatConfig {if (config.managedModels !== undefined && (!Array.isArray(config.managedModels) || !config.managedModels.length || config.managedModels.some(model => typeof model !== "string" || !model.trim()))) throw new Error("Invalid managed models.");const ownKey = typeof config.apiKeyEnv === "string" && OWN_KEY_ENVS.has(config.apiKeyEnv);if (config.catalog !== undefined && config.catalog !== "openai" && config.catalog !== "lmstudio") throw new Error("catalog must be \"openai\" or \"lmstudio\"");+ if (config.replyWaitMinutes !== undefined && !isReplyWait(config.replyWaitMinutes)) throw new Error(`replyWaitMinutes must be a whole number from 1 to ${MAX_REPLY_WAIT_MINUTES}`);const envUrl = ownKey ? undefined : process.env.OPENAI_COMPAT_URL;return {...(config.tools !== undefined ? { tools: config.tools as boolean } : {}),...(config.managedModels ? { managedModels: config.managedModels as string[] } : {}),+ ...(isReplyWait(config.replyWaitMinutes) ? { replyWaitMinutes: config.replyWaitMinutes } : {}),url: (typeof config.url === "string" && config.url ? config.url : envUrl || "https://openrouter.ai/api/v1").replace(/\/+$/, ""),apiKeyEnv: typeof config.apiKeyEnv === "string" && config.apiKeyEnv@@ -278,7 +285,7 @@ export const OpenAICompatDriver: ProviderDriver<OpenAICompatConfig> = {httpErrorLabel: "upstream",missingKeyError: missingKey,unavailableReason: missingKey,- timeoutMs: idleTimeoutMs(),+ timeoutMs: config.replyWaitMinutes ? config.replyWaitMinutes * 60_000 : idleTimeoutMs(),reasoning: true,billing: "metered",includeUsageInCompleted: true,diff --git a/server/index.ts b/server/index.tsindex 4737732052..e5feaecff6 100644--- a/server/index.ts+++ b/server/index.ts@@ -12045,7 +12045,7 @@ async function describeInstances() {const described = {...instance, ...testedAi.info(instance),...(entry?.icon ? { icon: entry.icon } : {}),- ...(entry?.access ? { access: entry.access } : {}), ...(heldKeys?.refusal(instance.instanceId) ? { snapshot: { state: "unavailable" as const, reason: TRIAL_KEY_HELD } } : {}),+ ...(entry?.access ? { access: entry.access } : {}), ...(entry?.driver === "openai-compat" && typeof (entry.config as { replyWaitMinutes?: unknown } | undefined)?.replyWaitMinutes === "number" ? { replyWaitMinutes: (entry.config as { replyWaitMinutes: number }).replyWaitMinutes } : {}), ...(heldKeys?.refusal(instance.instanceId) ? { snapshot: { state: "unavailable" as const, reason: TRIAL_KEY_HELD } } : {}),};if (hostedModels) return { ...described, readOnly: true,install: undefined, authentication: undefined, cli: undefined, cliCandidates: [],diff --git a/server/routes/instances.test.ts b/server/routes/instances.test.tsindex 874fe46990..6fc9a52f27 100644--- a/server/routes/instances.test.ts+++ b/server/routes/instances.test.ts@@ -70,7 +70,7 @@ async function serve(extra: Partial<InstanceRouteDeps> = {}) {await call("GET", "/api/instances");return fake.probes.length;};- return { sign, call, probesAfterList };+ return { sign, call, probesAfterList, base };}describe("engine sign-in routes", () => {@@ -169,3 +169,28 @@ describe("installing an engine's own build from Settings", () => {expect(persisted).toEqual([]);});});++describe("a server's reply wait", () => {+ it("saves minutes for an OpenAI-compatible server, clears them with null, and refuses other engines or bad values", async () => {+ const persisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];+ const cfg = { instances: { a: { driver: "fake" }, "openai-compat-1": { driver: "openai-compat", config: { url: "http://127.0.0.1:11434/v1", key: "k" } } } };+ const { call, base } = 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/openai-compat-1", { replyWaitMinutes: 20 });+ expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "http://127.0.0.1:11434/v1", key: "k", replyWaitMinutes: 20 });+ await call("PATCH", "/api/instances/openai-compat-1", { replyWaitMinutes: null });+ expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "http://127.0.0.1:11434/v1", key: "k" });+ const status = async (id: string, body: unknown) => (await fetch(`${base}/api/instances/${id}`, {+ method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body),+ })).status;+ expect(await status("a", { replyWaitMinutes: 20 })).toBe(400);+ for (const bad of [0, 61, 2.5, "10"]) expect(await status("openai-compat-1", { replyWaitMinutes: bad })).toBe(400);+ expect(persisted).toHaveLength(2);+ });+});+diff --git a/server/routes/instances.ts b/server/routes/instances.tsindex b589c30600..52493d4c6d 100644--- a/server/routes/instances.ts+++ b/server/routes/instances.ts@@ -306,7 +306,7 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {return json(res, 415, { error: "content-type must be application/json" });}const parsed = instanceSettingsSchema.safeParse(await readBody(req, 16384));- if (!parsed.success) return json(res, 400, { error: "Supply a valid CLI path, account name, configuration directory or boolean tools setting." });+ if (!parsed.success) return json(res, 400, { error: "Supply a valid CLI path, account name, configuration directory, boolean tools setting or a reply wait of 1 to 60 minutes." });const body = parsed.data;const instanceId = instancePatch[1];if (providerConfigBusy.get()) return json(res, 409, { error: "provider settings are already being updated" });@@ -329,6 +329,11 @@ export function createInstanceRoutes(deps: InstanceRouteDeps): RouteHandler {}entry.config = { ...entry.config as Record<string, unknown>, tools: body.tools };}+ 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>;+ entry.config = body.replyWaitMinutes === null ? rest : { ...rest, replyWaitMinutes: body.replyWaitMinutes };+ }if (body.displayName !== undefined) entry.displayName = body.displayName;if (body.configDir !== undefined) {let previousDir: string | undefined;diff --git a/src/components/OpenAiCompatServers.test.ts b/src/components/OpenAiCompatServers.test.tsindex 92bf8c2615..157acb6ee0 100644--- a/src/components/OpenAiCompatServers.test.ts+++ b/src/components/OpenAiCompatServers.test.ts@@ -107,6 +107,48 @@ 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 };+ const nodes = (tree: ReactNode): Array<ReactElement<Props>> =>+ Children.toArray(tree).flatMap((child) => isValidElement<Props>(child) ? [child, ...nodes(child.props.children)] : []);+ function waitSelect(replyWaitMinutes?: number) {+ vi.stubGlobal("window", {});+ const servers = [instance("openai-compat-1", "Ollama", { url: "http://127.0.0.1:11434/v1", ...(replyWaitMinutes ? { replyWaitMinutes } : {}) })];+ vi.spyOn(store, "useStore").mockReturnValue({+ state: { ...store.initialState, instances: servers }, dispatch: vi.fn(), flushBotPatches: vi.fn(), refreshInstances: vi.fn(), refreshModels: vi.fn(),+ });+ const added = nodes(OtherOpenAiCompatServers()).find((node) => node.props.servers !== undefined)!;+ 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")!;+ } finally {+ fixture.counting = false;+ }+ }++ it("saves the chosen minutes for that server, and Default clears them", async () => {+ fixture.values = [];+ fixture.api.mockReset();+ fixture.api.mockResolvedValue({ instances: [] });+ const select = waitSelect();+ expect(select.props.value).toBe("");+ select.props.onChange!({ target: { value: "20" } });+ await Promise.resolve();+ expect(fixture.api).toHaveBeenLastCalledWith("/api/instances/openai-compat-1", { method: "PATCH", body: JSON.stringify({ replyWaitMinutes: 20 }) });+ fixture.values = [];+ waitSelect(20).props.onChange!({ target: { value: "" } });+ await Promise.resolve();+ expect(fixture.api).toHaveBeenLastCalledWith("/api/instances/openai-compat-1", { method: "PATCH", body: JSON.stringify({ replyWaitMinutes: null }) });+ });++ it("shows a saved wait that is not one of the usual choices", () => {+ fixture.values = [];+ const html = JSON.stringify(waitSelect(45).props.children);+ expect(html).toContain("Wait 45 min");+ });+});+describe("LM Studio and Bionic setup", () => {type Props = { children?: ReactNode; onChange?: (event: { target: { value: string } }) => void; onClick?: () => void; "aria-label"?: string };const elementNodes = (tree: ReactNode): Array<ReactElement<Props>> =>diff --git a/src/components/OpenAiCompatServers.tsx b/src/components/OpenAiCompatServers.tsxindex 53f9f64f7e..6ea612dfd8 100644--- a/src/components/OpenAiCompatServers.tsx+++ b/src/components/OpenAiCompatServers.tsx@@ -12,6 +12,8 @@ export function modelIds(text: string): string[] {}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";export function OtherOpenAiCompatServers() {@@ -62,10 +64,26 @@ function AddedServers({ servers }: { servers: Array<InstanceInfo & { url?: strin{servers.length === 0 && <p className="text-[12px] leading-4 text-ink-secondary">{t("apiInstances.empty")}</p>}{servers.map((server) => (<div key={server.instanceId} className="mb-1.5 flex items-center justify-between gap-2 rounded-lg border border-hairline/60 bg-inset px-3 py-1.5">- <div className="min-w-0">+ <div className="min-w-0 flex-1"><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+ 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 }) }));+ }}+ disabled={busy !== null}+ aria-label={t("apiInstances.replyWaitFor", { name: server.displayName })}+ title={t("apiInstances.replyWaitHint")}+ className="shrink-0 rounded-md border border-hairline/60 bg-inset px-1.5 py-1 text-[11.5px] text-ink focus:border-accent focus:outline-none disabled:opacity-50"+ >+ <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><buttontype="button"onClick={() => run("other", () => api(`/api/instances/${encodeURIComponent(server.instanceId)}/refresh-models`, { method: "POST" }))}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 8428c7b913..31ed5ae557 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -6183,6 +6183,10 @@"apiInstances.refreshModels": "Detect models for {name} again","apiInstances.empty": "No other servers yet.","apiInstances.failed": "Couldn't save the server. Check the fields and try again.",+ "apiInstances.replyWaitFor": "How long to wait for {name} to reply",+ "apiInstances.replyWaitHint": "How long to wait for the next words of a reply before giving up. Local models can take a while to answer on a slow computer.",+ "apiInstances.replyWaitDefault": "Wait: default",+ "apiInstances.replyWaitMinutes": "Wait {minutes} min","botOverview.loading": "Loading…","botOverview.refreshError": "Couldn’t refresh — showing the last loaded overview.","botOverview.readAll": "Read all",diff --git a/src/state/store.tsx b/src/state/store.tsxindex c348a3d3b7..a986cbbc0e 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -511,7 +511,7 @@ export interface InstanceInfo {cliDefault?: string;cliCandidates?: string[];claudeAccount?: { configDir: string; signInCommand: string; signInShell: "powershell" | "sh"; isDefault: boolean };- freeUpSpace?: boolean;+ freeUpSpace?: boolean; replyWaitMinutes?: number;}export type AppSettingsSection =