Skip to content

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

fix(keys): an IME's confirming Enter no longer saves a half-typed API key

hadan8977bc9f52b2f2c6
diff --git a/src/components/keys/KeyRow.ime.test.ts b/src/components/keys/KeyRow.ime.test.ts
new file mode 100644
index 0000000000..a1b9262a96
--- /dev/null
+++ b/src/components/keys/KeyRow.ime.test.ts
@@ -0,0 +1,96 @@
+// @vitest-environment happy-dom
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { setLocale } from "@/lib/i18n";
+import type { ConfigStatus } from "@/state/store";
+
+const fx = vi.hoisted(() => ({
+ saveKey: vi.fn(),
+ dispatch: vi.fn(),
+}));
+
+vi.mock("@/state/store", async (original) => {
+ const actual = await original<typeof import("@/state/store")>();
+ return {
+ ...actual,
+ useStore: () => ({
+ state: { ...actual.initialState, config: {} },
+ dispatch: fx.dispatch,
+ refreshInstances: vi.fn(),
+ }),
+ };
+});
+
+vi.mock("./key-save", async (original) => {
+ const actual = await original<typeof import("./key-save")>();
+ return { ...actual, saveKey: fx.saveKey };
+});
+
+vi.mock("@/lib/analytics", () => ({ track: vi.fn() }));
+
+const { KeyRow } = await import("./KeyRow");
+
+let host: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ setLocale("en");
+ fx.saveKey.mockReset();
+ fx.dispatch.mockReset();
+ fx.saveKey.mockResolvedValue({ anthropic: { configured: true, last4: "alf1" } } as ConfigStatus);
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+ vi.clearAllMocks();
+});
+
+function mount() {
+ flushSync(() => root.render(createElement(KeyRow, { id: "anthropic" })));
+ const input = host.querySelector<HTMLInputElement>("[data-key-input]")!;
+ flushSync(() => input.focus());
+ return input;
+}
+
+function type(input: HTMLInputElement, value: string) {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
+ flushSync(() => {
+ setter.call(input, value);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+function press(input: HTMLInputElement, init: KeyboardEventInit) {
+ flushSync(() => input.dispatchEvent(new KeyboardEvent("keydown", { bubbles: true, cancelable: true, ...init })));
+}
+
+const IME = [
+ { name: "composition", init: { isComposing: true } },
+ { name: "IME key code", init: { keyCode: 229 } },
+];
+
+describe("saving a key with an input method", () => {
+ it.each(IME)("does not save on the Enter that belongs to the $name", async ({ init }) => {
+ const input = mount();
+ type(input, "sk-ant-half");
+ press(input, { key: "Enter", ...init });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(fx.saveKey).not.toHaveBeenCalled();
+ expect(input.value).toBe("sk-ant-half");
+ });
+
+ it("still saves on a plain Enter", async () => {
+ const input = mount();
+ type(input, "sk-ant-half");
+ press(input, { key: "Enter" });
+ await vi.waitFor(() => expect(fx.saveKey).toHaveBeenCalledOnce());
+ expect(fx.saveKey).toHaveBeenCalledWith(expect.anything(), "sk-ant-half", true);
+ });
+});
diff --git a/src/components/keys/KeyRow.tsx b/src/components/keys/KeyRow.tsx
index c68e9a204b..38ec67f5a8 100644
--- a/src/components/keys/KeyRow.tsx
+++ b/src/components/keys/KeyRow.tsx
@@ -1,9 +1,10 @@
-import { useContext, useEffect, useId, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { useContext, useEffect, useId, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { Check, CircleAlert, ExternalLink, Eye, EyeOff, Loader2, TriangleAlert } from "lucide-react";
import { useStore } from "@/state/store";
import { installCommandFor } from "@/state/engine-install";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
+import { imeComposing } from "@/lib/send-key";
import type { KeyResult, KeyVia } from "@/lib/analytics-allowlist";
import { keyRemoved, keySaved, keySaveFailure, savedKeyResult } from "@/lib/product-events";
import { InstanceProviderMark } from "../ProviderIcons";
@@ -306,6 +307,21 @@ export function KeyRow({
focusAfter.current = "replace";
};
+ const onKeyField = (event: KeyboardEvent<HTMLInputElement>) => {
+ if (event.nativeEvent && imeComposing(event.nativeEvent)) {
+ event.stopPropagation();
+ return;
+ }
+ if (event.key === "Enter") {
+ event.preventDefault();
+ void save(draft);
+ } else if (event.key === "Escape" && replacing) {
+ event.preventDefault();
+ event.stopPropagation();
+ cancelReplace();
+ }
+ };
+
const input = (
<input
ref={inputRef}
@@ -322,16 +338,7 @@ export function KeyRow({
setProblem(null);
if (looksLikeKey(pasted) && !looksLikeOtherKey(row, pasted)) void save(pasted);
}}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- event.preventDefault();
- void save(draft);
- } else if (event.key === "Escape" && replacing) {
- event.preventDefault();
- event.stopPropagation();
- cancelReplace();
- }
- }}
+ onKeyDown={onKeyField}
disabled={busy === "saving"}
placeholder={replacing ? t("keys.row.newKey") : t("keys.row.pasteKey")}
aria-label={label}
@@ -377,16 +384,7 @@ export function KeyRow({
setProblem(null);
if (looksLikeKey(pasted) && !looksLikeOtherKey(row, pasted)) void save(pasted);
}}
- onKeyDown={(event) => {
- if (event.key === "Enter") {
- event.preventDefault();
- void save(draft);
- } else if (event.key === "Escape" && replacing) {
- event.preventDefault();
- event.stopPropagation();
- cancelReplace();
- }
- }}
+ onKeyDown={onKeyField}
disabled={busy === "saving"}
placeholder={replacing ? t("keys.row.newKey") : target.placeholderKey ? t(target.placeholderKey) : target.placeholder}
aria-label={label}