Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(settings): filter and sort the LLM provider picker (OHE-3653) (#18710)

Hiep Leb7ee2876317f
diff --git a/__tests__/components/modals/settings/model-selector-openhands.test.tsx b/__tests__/components/modals/settings/model-selector-openhands.test.tsx
index 1c7e7927ea..d05650b187 100644
--- a/__tests__/components/modals/settings/model-selector-openhands.test.tsx
+++ b/__tests__/components/modals/settings/model-selector-openhands.test.tsx
@@ -131,4 +131,57 @@ describe("ModelSelector β€” OpenHands provider display", () => {
"Free",
);
});
+
+ it("lists each section's providers by their shown name, OpenHands first", async () => {
+ // Arrange: neither the backend order nor the provider ids follow the
+ // names the picker shows (e.g. "bedrock" is shown as "AWS Bedrock").
+ server.use(
+ http.get("*/api/llm/providers", () =>
+ HttpResponse.json({ providers: ["mistral", "azure", "bedrock"] }),
+ ),
+ http.get("*/api/llm/models/verified", () =>
+ HttpResponse.json({
+ models: { openai: [], openhands: [], deepseek: [], anthropic: [] },
+ }),
+ ),
+ );
+ const user = userEvent.setup();
+ renderWithQuery(<ModelSelector />);
+
+ // Act
+ await user.click(screen.getByLabelText("LLM$PROVIDER"));
+
+ // Assert
+ await waitFor(() => {
+ expect(
+ screen.getAllByRole("option").map((option) => option.textContent),
+ ).toEqual([
+ "OpenHands",
+ "Anthropic",
+ "deepseek",
+ "OpenAI",
+ "AWS Bedrock",
+ "Azure",
+ "Mistral AI",
+ ]);
+ });
+ });
+
+ it("filters providers by what the user types over the selected one", async () => {
+ // Arrange
+ const user = userEvent.setup();
+ renderWithQuery(<ModelSelector currentModel="openai/gpt-4o" />);
+ const providerInput = screen.getByLabelText("LLM$PROVIDER");
+ await waitFor(() => expect(providerInput).toHaveValue("OpenAI"));
+
+ // Act
+ await user.click(providerInput);
+ await user.keyboard("anth");
+
+ // Assert
+ expect(providerInput).toHaveValue("anth");
+ expect(
+ screen.getAllByRole("option").map((option) => option.textContent),
+ ).toEqual(["Anthropic"]);
+ });
});
diff --git a/__tests__/components/shared/modals/modal-backdrop.test.tsx b/__tests__/components/shared/modals/modal-backdrop.test.tsx
index 4569489d72..fe7c764ce2 100644
--- a/__tests__/components/shared/modals/modal-backdrop.test.tsx
+++ b/__tests__/components/shared/modals/modal-backdrop.test.tsx
@@ -261,6 +261,67 @@ describe("ModalBackdrop focus management", () => {
expect(popoverInput).toHaveFocus();
});
+ // A combobox that opens on focus moves virtual focus to its selected option
+ // (portaled outside the dialog) while its own focus event is still on the
+ // way to window: browsers flush React's update between the event's
+ // listeners. A document listener gives jsdom the same order.
+ function ComboboxOpeningOnFocus() {
+ const optionRef = React.useRef<HTMLLIElement>(null);
+ React.useEffect(() => {
+ const moveVirtualFocus = (event: FocusEvent) => {
+ if ((event.target as Element).getAttribute("role") !== "combobox") {
+ return;
+ }
+ optionRef.current?.dispatchEvent(
+ new FocusEvent("focusin", { bubbles: true }),
+ );
+ };
+ document.addEventListener("focusin", moveVirtualFocus);
+ return () => document.removeEventListener("focusin", moveVirtualFocus);
+ }, []);
+ return (
+ <>
+ <input
+ role="combobox"
+ aria-label="provider"
+ aria-controls="providers"
+ aria-expanded="true"
+ />
+ {createPortal(
+ <ul id="providers" role="listbox" aria-label="providers">
+ <li ref={optionRef} role="option" aria-selected="true">
+ OpenAI
+ </li>
+ </ul>,
+ document.body,
+ )}
+ </>
+ );
+ }
+
+ it("keeps focus on a combobox that moves virtual focus to its option as it opens", async () => {
+ // Arrange
+ const user = userEvent.setup();
+ render(
+ <PageWithModal
+ renderModalContent={() => (
+ <>
+ <button type="button">first</button>
+ <ComboboxOpeningOnFocus />
+ </>
+ )}
+ />,
+ );
+ await user.click(screen.getByRole("button", { name: "open" }));
+ const combobox = screen.getByRole("combobox", { name: "provider" });
+
+ // Act
+ combobox.focus();
+
+ // Assert
+ expect(combobox).toHaveFocus();
+ });
+
it("restores focus to the opener when the dialog closes", async () => {
const user = userEvent.setup();
render(<PageWithModal renderModalContent={threeButtons} />);
diff --git a/src/components/shared/modals/settings/model-selector.tsx b/src/components/shared/modals/settings/model-selector.tsx
index f721bc2449..417c149b8b 100644
--- a/src/components/shared/modals/settings/model-selector.tsx
+++ b/src/components/shared/modals/settings/model-selector.tsx
@@ -17,6 +17,15 @@ import { useSearchProviders } from "#/hooks/query/use-search-providers";
import { useProviderModels } from "#/hooks/query/use-provider-models";
import { FREE_MODEL_BADGE_LABEL } from "#/utils/format-model-name";
import { FreeOpenHandsModelsNote } from "#/components/shared/free-models-note";
+import type { LLMProvider } from "#/api/config-service/config-service.types";
+
+// Sorts by the label the picker shows, keeping the managed OpenHands provider
+// first as the backend does.
+const compareProviderLabels = (a: LLMProvider, b: LLMProvider) =>
+ Number(b.name === "openhands") - Number(a.name === "openhands") ||
+ mapProvider(a.name).localeCompare(mapProvider(b.name), undefined, {
+ sensitivity: "base",
+ });
const freeModelBadgeClassName =
"shrink-0 rounded-full border border-warning/40 bg-warning/10 px-1.5 py-0.5 text-[10px] leading-none text-warning";
@@ -55,11 +64,11 @@ export function ModelSelector({
} = useProviderModels(selectedProvider);
const verifiedProviders = React.useMemo(
- () => providers.filter((p) => p.verified),
+ () => providers.filter((p) => p.verified).sort(compareProviderLabels),
[providers],
);
const unverifiedProviders = React.useMemo(
- () => providers.filter((p) => !p.verified),
+ () => providers.filter((p) => !p.verified).sort(compareProviderLabels),
[providers],
);
@@ -171,6 +180,9 @@ export function ModelSelector({
if (e?.toString()) handleChangeProvider(e.toString());
}}
onInputChange={(value) => !value && clear()}
+ // Select the current provider's label so typing replaces it and
+ // filters the list instead of appending to it.
+ onFocus={(e) => e.target.select()}
defaultSelectedKey={selectedProvider ?? undefined}
selectedKey={selectedProvider}
classNames={{
diff --git a/src/components/shared/modals/use-modal-focus.ts b/src/components/shared/modals/use-modal-focus.ts
index 414b48aa47..33112d73a1 100644
--- a/src/components/shared/modals/use-modal-focus.ts
+++ b/src/components/shared/modals/use-modal-focus.ts
@@ -90,7 +90,10 @@ export function useModalFocus({ elevated }: { elevated: boolean }) {
const [opener] = React.useState(() =>
typeof document === "undefined" ? null : document.activeElement,
);
- const focusEventFromDialogTree = React.useRef<Event | null>(null);
+ // Focus events that went through the dialog's onFocus. A set, not just the
+ // last one: a focusin can trigger a nested one (a combobox opening moves
+ // virtual focus to its option), and marking that must not unmark the outer.
+ const focusEventsFromDialogTree = React.useRef(new WeakSet<Event>());
React.useEffect(() => {
const root = rootRef.current;
@@ -107,7 +110,7 @@ export function useModalFocus({ elevated }: { elevated: boolean }) {
const handleFocusIn = (event: FocusEvent) => {
// A closing dialog is already detached here; let the new focus stand.
if (!root.isConnected || topmostModalRoot() !== root) return;
- if (event === focusEventFromDialogTree.current) return;
+ if (focusEventsFromDialogTree.current.has(event)) return;
focusFirstTabbable(root);
};
window.addEventListener("focusin", handleFocusIn);
@@ -140,7 +143,7 @@ export function useModalFocus({ elevated }: { elevated: boolean }) {
}, []);
const onFocus = React.useCallback((event: React.FocusEvent) => {
- focusEventFromDialogTree.current = event.nativeEvent;
+ focusEventsFromDialogTree.current.add(event.nativeEvent);
}, []);
const onKeyDown = React.useCallback((event: React.KeyboardEvent) => {