Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Model menu: stay open after picking a model that has reasoning levels (#4218)
Aditya Umale5df8b46c18cb
diff --git a/scripts/testing/control-omb-ui.e2e.test.ts b/scripts/testing/control-omb-ui.e2e.test.tsindex d397a513ae..2ff4950d1c 100644--- a/scripts/testing/control-omb-ui.e2e.test.ts+++ b/scripts/testing/control-omb-ui.e2e.test.ts@@ -271,7 +271,9 @@ describe("control-omb ui drives the real renderer", () => {await ui("click", info.ui, "--name", nextModel.label);await expect.poll(async () => (await savedBot()).modelSelection.model, { timeout: 10_000 }).toBe(nextModel.id);expect((await savedBot()).tasks.find((task: any) => task.threadId === originalBot.threadId).modelSelection.model).toBe(nextModel.id);- await ui("click", info.ui, "--name", nextModel.label);+ // A model with reasoning levels keeps the menu open after the pick, so its level can be set next.+ expect(await ui("eval", info.ui, "--js", "String(Boolean(document.querySelector('[data-model-picker-content]')))"))+ .toMatchObject({ result: "true" });await ui("click", info.ui, "--name", "Only this thread");const modelSnapshot = await ui("snapshot", info.ui, "--interactive");const originalRow = Object.entries(modelSnapshot.refs as Record<string, { name: string; role: string }>)@@ -282,6 +284,10 @@ describe("control-omb ui drives the real renderer", () => {{ timeout: 10_000 }).toBe(originalModel);expect((await savedBot()).modelSelection.model).toBe(nextModel.id);expect((await savedBot()).approvalMode).toBe(originalBot.approvalMode);+ // The menu is still open after that pick; close it before using the composer.+ await ui("press", info.ui, "--keys", "Escape");+ await expect.poll(async () => (await ui("eval", info.ui, "--js", "String(Boolean(document.querySelector('[data-model-picker-content]')))")).result,+ { timeout: 10_000 }).toBe("false");const before = await ui("snapshot", info.ui, "--interactive");expect(before.ok).toBe(true);diff --git a/src/components/CustomAcpModelPicker.test.ts b/src/components/CustomAcpModelPicker.test.tsindex df991b4dd2..09c5f23c2b 100644--- a/src/components/CustomAcpModelPicker.test.ts+++ b/src/components/CustomAcpModelPicker.test.ts@@ -101,14 +101,15 @@ it.each(["zcode", "codebuddy", "qoder", "qodercn"])("offers discovered models inexpect(fixture.dispatch).toHaveBeenLastCalledWith({ type: "setModel", botId: selected.id, threadId: selected.threadId,updateBotDefault: true, selection: { instanceId, model: "glm-5.3-flash" } });const saved = { ...selected, modelSelection: { instanceId, model: "glm-5.3-flash" } };- const reopened = openPicker(saved);- const savedPane = reopened.nodes.find((entry) => entry.type === SimpleModelMenu) as unknown as ReactElement<ComponentProps<typeof SimpleModelMenu>>;+ // A model with thinking choices keeps the menu open, so its thinking row is offered right away.+ const stillOpen = renderPicker(saved);+ const savedPane = stillOpen.nodes.find((entry) => entry.type === SimpleModelMenu) as unknown as ReactElement<ComponentProps<typeof SimpleModelMenu>>;const variants = (savedPane.props.thinking as { variants: ReactElement<ComponentProps<typeof ModelVariantRow>> }).variants;expect(variants.type).toBe(ModelVariantRow);const nativeRow = ModelVariantRow(variants.props);const thinking = elements(nativeRow).find((entry) => entry.type === Select)!;- expect(reopened.html).toContain(">high</option>");- expect(reopened.html).not.toContain(">Max</option>");+ expect(stillOpen.html).toContain(">high</option>");+ expect(stillOpen.html).not.toContain(">Max</option>");thinking.props.onChange!({ target: { value: "1" } } as ChangeEvent<HTMLSelectElement>);expect(fixture.dispatch).toHaveBeenLastCalledWith({ type: "setModel", botId: selected.id, threadId: selected.threadId,updateBotDefault: true, selection: { instanceId, model: "glm-5.3-flash", variant: "high" } });diff --git a/src/components/ModelPicker.dom.test.ts b/src/components/ModelPicker.dom.test.tsindex 7a06f135e7..ce26766b86 100644--- a/src/components/ModelPicker.dom.test.ts+++ b/src/components/ModelPicker.dom.test.ts@@ -100,6 +100,8 @@ afterEach(() => {describe("choosing a model with the keyboard", () => {it("opens from the chip, starts on the current model, moves with the arrows and picks with Enter", async () => {+ fixture.instances = [{ ...claude(three), capabilities: {} }];+ render();await openWith("ArrowDown");expect(menu()).not.toBeNull();expect(host.contains(menu())).toBe(false);@@ -172,7 +174,7 @@ describe("choosing a model with the keyboard", () => {});it("clears a search with Escape before closing, keeps every Escape from the panel around it, and returns focus to the chip", async () => {- fixture.instances = [claude(numbered(14))];+ fixture.instances = [{ ...claude(numbered(14)), capabilities: {} }];render(scout("model-0"));await openWith("click");const search = document.querySelector<HTMLInputElement>("[data-menu-search]")!;@@ -278,6 +280,64 @@ describe("an OpenCode model typed by hand", () => {});});+describe("picking a model that has reasoning levels", () => {+ for (const advanced of [false, true]) {+ it(`keeps the ${advanced ? "full" : "Simple"} menu open on the new model so its level can be set next, and Escape still closes it`, async () => {+ fixture.advanced = advanced;+ render();+ await openWith("ArrowDown");+ press("ArrowDown");+ expect(focused()?.textContent).toContain("Sonnet 5.5");+ press("Enter");+ await settle();++ expect(fixture.dispatch).toHaveBeenLastCalledWith(expect.objectContaining({+ type: "setModel", selection: expect.objectContaining({ model: "claude-sonnet-5-5" }),+ }));+ expect(menu()).not.toBeNull();+ expect(chip().getAttribute("aria-expanded")).toBe("true");+ expect(menu()!.querySelector(advanced ? 'select[aria-label="Reasoning effort"]' : "[data-effort-pill]")).not.toBeNull();++ // The store applies the pick; the picked row may be redrawn elsewhere, but focus stays in the menu.+ render(scout("claude-sonnet-5-5"));+ await settle();+ expect(menu()).not.toBeNull();+ expect(menu()!.contains(focused())).toBe(true);++ press("Escape");+ await settle();+ expect(menu()).toBeNull();+ });+ }+});++describe("clearing a search after a pick that keeps the menu open", () => {+ it("keeps focus in the Simple menu when Escape removes the picked row, so the next Escape still closes it", async () => {+ fixture.instances = [claude(numbered(14))];+ render(scout("model-0"));+ await openWith("click");+ const search = document.querySelector<HTMLInputElement>("[data-menu-search]")!;+ type(search, "model 13");+ press("ArrowDown", search);+ expect(focused()?.textContent).toContain("Model 13");+ press("Enter");+ await settle();+ render(scout("model-13"));+ await settle();+ expect(menu()!.contains(focused())).toBe(true);++ press("Escape");+ await settle();+ expect(document.querySelector<HTMLInputElement>("[data-menu-search]")!.value).toBe("");+ expect(menu()).not.toBeNull();+ expect(menu()!.contains(focused())).toBe(true);++ press("Escape");+ await settle();+ expect(menu()).toBeNull();+ });+});+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.simple.test.ts b/src/components/ModelPicker.simple.test.tsindex b8cb780b01..8e9847e9c7 100644--- a/src/components/ModelPicker.simple.test.ts+++ b/src/components/ModelPicker.simple.test.ts@@ -898,12 +898,14 @@ describe("a thread's picker and its bot's model", () => {expect(closed).not.toContain("data-thread-models-notice");});- it("right after a pick changes the bot's model, says how many threads keep their own, until it opens again", () => {+ it("once the menu closes after a pick changes the bot's model, says how many threads keep their own, until it opens again", () => {const forBot = scout(null, [{ threadId: "kept", model: haiku }, { threadId: "follows", model: null }]);const opened = open(forBot);pane(opened)!.props.onPick(instance("claude"), "claude-sonnet-5-5");expect(fixture.dispatch).toHaveBeenLastCalledWith(expect.objectContaining({ type: "setModel", updateBotDefault: true }));- const closed = render(forBot);+ // Sonnet 5.5 has effort levels, so the menu stays open for them; the chip closes it.+ expect(render(forBot).html).not.toContain("data-thread-models-notice");+ const closed = open(forBot);expect(closed.html).toContain("data-thread-models-notice");expect(closed.html).toContain("menu-surface");expect(closed.html).toContain("1 thread uses its own model.");diff --git a/src/components/ModelPicker.tsx b/src/components/ModelPicker.tsxindex d078e92412..bb322d1236 100644--- a/src/components/ModelPicker.tsx+++ b/src/components/ModelPicker.tsx@@ -1,7 +1,7 @@import { useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from "react";import { createPortal } from "react-dom";import { ChevronDown, ChevronLeft, ChevronRight, ChevronUp, KeyRound, Loader2, RefreshCw, X } from "lucide-react";-import { useStore, currentTaskBot, type AppState, type Bot, type InstanceInfo, type ModelSelection } from "@/state/store";+import { useStore, currentTaskBot, type Bot, type InstanceInfo, type ModelSelection } from "@/state/store";import type { EffortLevel } from "../../shared/wire";import type { ModelVariantOption } from "../../shared/runtime-events";import { filterCustomModels, partitionCustomModels, suggestedModels } from "@/lib/custom-models";@@ -25,6 +25,7 @@ import { SimpleModelMenu, type SimpleThinking } from "./SimpleModelMenu";import { apiKeysLabel, ClaudeAccountSelect, engineStatus, FollowBotModelRow, ModelEngineRail, ModelRow, ModelSearch } from "./ModelPickerFull";import { MENU_LABEL, MENU_LINE, MENU_ROW, MENU_SEPARATOR, MENU_STROKE, MENU_TRAILING } from "./menu-recipe";import { modelMenuKey, modelMenuPointerMove } from "./model-menu-keys";+import { offersReasoning, useRefocusAfterPick, variantChoices } from "./model-picker-reasoning";import { useAdvancedMode } from "@/lib/interface-mode";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";@@ -123,17 +124,6 @@ export function EffortRow({const variantLabel = (option: ModelVariantOption, driverKind?: string): string =>option.id === "default" && driverKind === "opencodeGo" ? t("model.variant.openCodeDefault") : option.label;-/** ACP variant ids are opaque; their model/session declares the available choices. */-function variantChoices(state: Pick<AppState, "instances" | "modelVariantSessions">, selection: ModelSelection, threadId: string | undefined) {- const instance = state.instances.find((candidate) => candidate.instanceId === selection.instanceId);- if (!instance?.capabilities?.modelVariants) return null;- const session = threadId === undefined ? undefined : state.modelVariantSessions[threadId];- const reported = session?.instanceId === selection.instanceId && session.model === selection.model ? session.variants : undefined;- const options = reported?.options ?? instance.models.options.find((option) => option.id === selection.model)?.variants ?? [];- if (!options.length && selection.variant === undefined) return null;- return { instance, reported, options };-}-export function ModelVariantRow({ bot, threadId, updateBotDefault, className, label, compact = false, wide = false, quiet = false }: {bot: Bot;threadId?: string;@@ -306,6 +296,7 @@ export function ModelPicker({}, [open, placement]);const selection = bot.modelSelection;+ const refocusAfterPick = useRefocusAfterPick(menuRef, open, selection, query);const instances = withTypedModels(state.instances, selection, query);const active = instances.find((instance) => instance.instanceId === selection.instanceId);const pickerInstances = configuredModelInstances(instances, selection.instanceId);@@ -500,7 +491,10 @@ export function ModelPicker({selection: nextSelection,});if (updateBotDefault && threadId) setChangedBotModel(true);- close(true);+ // A model with reasoning levels keeps the menu open, so its level can be set next without opening it again;+ // picking a variant row already sets that level.+ if (variant !== undefined || contained || !offersReasoning(state, instance, nextSelection, threadId ?? bot.threadId)) close(true);+ else refocusAfterPick();};const resetVariant = contained && selection.variant !== undefined ? () => {@@ -570,8 +564,10 @@ export function ModelPicker({if (event.key !== "Escape") return modelMenuKey(event, { query, typed, close: () => close(true) });event.preventDefault();event.stopPropagation();- if (query) setQuery("");- else if (!simpleView && pane === "custom" && canReturnToOfficial) setPane("main");+ if (query) {+ setQuery("");+ refocusAfterPick();+ } else if (!simpleView && pane === "custom" && canReturnToOfficial) setPane("main");else if (fullView && !advanced) backToList(true);else close(true);};diff --git a/src/components/model-picker-reasoning.ts b/src/components/model-picker-reasoning.tsnew file mode 100644index 0000000000..a3847f3cea--- /dev/null+++ b/src/components/model-picker-reasoning.ts@@ -0,0 +1,37 @@+import { useEffect, useRef, type RefObject } from "react";+import type { AppState, InstanceInfo, ModelSelection } from "@/state/store";++/** ACP variant ids are opaque; their model/session declares the available choices. */+export function variantChoices(state: Pick<AppState, "instances" | "modelVariantSessions">, selection: ModelSelection, threadId: string | undefined) {+ const instance = state.instances.find((candidate) => candidate.instanceId === selection.instanceId);+ if (!instance?.capabilities?.modelVariants) return null;+ const session = threadId === undefined ? undefined : state.modelVariantSessions[threadId];+ const reported = session?.instanceId === selection.instanceId && session.model === selection.model ? session.variants : undefined;+ const options = reported?.options ?? instance.models.options.find((option) => option.id === selection.model)?.variants ?? [];+ if (!options.length && selection.variant === undefined) return null;+ return { instance, reported, options };+}++/** Whether the full menu shows a reasoning row (effort levels or model variants) for `next` on `instance`. */+export function offersReasoning(state: Pick<AppState, "instances" | "modelVariantSessions">, instance: InstanceInfo, next: ModelSelection, threadId: string | undefined): boolean {+ return instance.capabilities?.modelVariants+ ? Boolean(variantChoices(state, next, threadId))+ : Boolean(instance.capabilities?.effortLevels?.length);+}++/**+ * Applying a pick, or clearing the search after one, can redraw or remove the focused row and drop focus out of+ * the open menu. Call the returned function after either: focus comes back (to the thinking level when there is+ * one) so Escape and the arrow keys keep working.+ */+export function useRefocusAfterPick(menuRef: RefObject<HTMLElement | null>, open: boolean, selection: ModelSelection, query: string): () => void {+ const pending = useRef(false);+ useEffect(() => {+ if (!pending.current) return;+ pending.current = false;+ const menu = menuRef.current;+ if (!open || !menu || menu.contains(document.activeElement)) return;+ (menu.querySelector<HTMLElement>('[data-simple-effort] [tabindex="0"]') ?? menu).focus({ preventScroll: true });+ }, [selection, query, open, menuRef]);+ return () => { pending.current = true; };+}