Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

studio: guard project submits during IME composition (#12924)

Maheswar Kumard7cac16cbe09
diff --git a/studio/frontend/src/features/chat/components/edit-project-dialog.tsx b/studio/frontend/src/features/chat/components/edit-project-dialog.tsx
index 03e4dada932..535777c464c 100644
--- a/studio/frontend/src/features/chat/components/edit-project-dialog.tsx
+++ b/studio/frontend/src/features/chat/components/edit-project-dialog.tsx
@@ -1,7 +1,7 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { useState } from "react";
+import { useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import {
@@ -23,6 +23,11 @@ import {
updateChatProjectInstructions,
} from "../hooks/use-chat-projects";
import type { ProjectRecord } from "../types";
+import {
+ imeOwnsInputKeydown,
+ inputImeHandlers,
+ newInputImeState,
+} from "../utils/composer-preferences";
/** Name, instructions and linked folders for one project. Opened from the folder row's "Edit".
* Deleting hands back to the caller, which owns the confirmation. */
@@ -39,6 +44,15 @@ export function EditProjectDialog({
const [name, setName] = useState(project?.name ?? "");
const [instructions, setInstructions] = useState(project?.instructions ?? "");
const [busy, setBusy] = useState(false);
+ const nameImeRef = useRef(newInputImeState());
+ const nameImeHandlers = {
+ onFocus: () => inputImeHandlers(nameImeRef.current).onFocus(),
+ onBlur: () => inputImeHandlers(nameImeRef.current).onBlur(),
+ onCompositionStart: () =>
+ inputImeHandlers(nameImeRef.current).onCompositionStart(),
+ onCompositionEnd: (event: { timeStamp: number }) =>
+ inputImeHandlers(nameImeRef.current).onCompositionEnd(event),
+ };
// Reseed on render, not in an effect: the fields are drafts of whichever project is open, and
// a stale one would save the last project's text over this one.
const [seededFor, setSeededFor] = useState(project?.id ?? null);
@@ -98,10 +112,17 @@ export function EditProjectDialog({
>
<DialogContent
className="corner-squircle dialog-soft-surface gap-5 sm:max-w-lg"
+ {...nameImeHandlers}
// Enter saves from the name field, which a multi-line instructions box cannot do; the
// chord saves from either. The menus and confirmations inside portal out of here, so
// their own keys never reach this.
onKeyDown={(e) => {
+ if (
+ imeOwnsInputKeydown(e, nameImeRef.current, {
+ modifiedEnterSubmits: true,
+ })
+ )
+ return;
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
void save();
@@ -131,6 +152,14 @@ export function EditProjectDialog({
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) => {
+ if (
+ imeOwnsInputKeydown(e, nameImeRef.current, {
+ modifiedEnterSubmits: true,
+ })
+ ) {
+ e.stopPropagation();
+ return;
+ }
if (e.key === "Enter") {
e.preventDefault();
// The chord would reach the dialog's handler too and save twice.
diff --git a/studio/frontend/src/features/chat/components/new-project-dialog.tsx b/studio/frontend/src/features/chat/components/new-project-dialog.tsx
index a37a36e91d2..b844ce63c0f 100644
--- a/studio/frontend/src/features/chat/components/new-project-dialog.tsx
+++ b/studio/frontend/src/features/chat/components/new-project-dialog.tsx
@@ -29,6 +29,11 @@ import { HugeiconsIcon } from "@hugeicons/react";
import { createChatProject } from "../hooks/use-chat-projects";
import { useChatRuntimeStore } from "../stores/chat-runtime-store";
import type { ProjectRecord } from "../types";
+import {
+ imeOwnsInputKeydown,
+ inputImeHandlers,
+ newInputImeState,
+} from "../utils/composer-preferences";
function currentRoute(): string {
if (typeof window === "undefined") return "";
@@ -63,6 +68,15 @@ export function NewProjectDialog({
const [stagingDrop, setStagingDrop] = useState(false);
// Same for a folder pick still resolving over IPC.
const [pickingFolder, setPickingFolder] = useState(false);
+ const nameImeRef = useRef(newInputImeState());
+ const nameImeHandlers = {
+ onFocus: () => inputImeHandlers(nameImeRef.current).onFocus(),
+ onBlur: () => inputImeHandlers(nameImeRef.current).onBlur(),
+ onCompositionStart: () =>
+ inputImeHandlers(nameImeRef.current).onCompositionStart(),
+ onCompositionEnd: (event: { timeStamp: number }) =>
+ inputImeHandlers(nameImeRef.current).onCompositionEnd(event),
+ };
// Uploads outlive this component, so a slow one must not yank the user to the new project after
// they have navigated away.
const mounted = useRef(true);
@@ -154,7 +168,14 @@ export function NewProjectDialog({
<input
value={name}
onChange={(e) => setName(e.target.value)}
+ {...nameImeHandlers}
onKeyDown={(e) => {
+ if (
+ imeOwnsInputKeydown(e, nameImeRef.current, {
+ modifiedEnterSubmits: true,
+ })
+ )
+ return;
if (e.key === "Enter") {
e.preventDefault();
void commitCreate();
diff --git a/studio/frontend/src/features/chat/utils/composer-preferences.ts b/studio/frontend/src/features/chat/utils/composer-preferences.ts
index b69a66883ca..86cf7d93acf 100644
--- a/studio/frontend/src/features/chat/utils/composer-preferences.ts
+++ b/studio/frontend/src/features/chat/utils/composer-preferences.ts
@@ -35,15 +35,20 @@ export function imeKeydownBlocksComposerSubmit(
);
}
-export type InputImeState = { open: boolean; endedAt: number };
+export type InputImeState = {
+ open: boolean;
+ endedAt: number;
+ commitKeydownSeen: boolean;
+};
export function newInputImeState(): InputImeState {
- return { open: false, endedAt: -Infinity };
+ return { open: false, endedAt: -Infinity, commitKeydownSeen: false };
}
export function resetInputIme(ime: InputImeState) {
ime.open = false;
ime.endedAt = -Infinity;
+ ime.commitKeydownSeen = false;
}
export function inputImeHandlers(ime: InputImeState) {
@@ -54,10 +59,12 @@ export function inputImeHandlers(ime: InputImeState) {
onBlur: reset,
onCompositionStart: () => {
ime.open = true;
+ ime.commitKeydownSeen = false;
},
onCompositionEnd: (event: { timeStamp: number }) => {
ime.open = false;
- ime.endedAt = event.timeStamp;
+ ime.endedAt = ime.commitKeydownSeen ? -Infinity : event.timeStamp;
+ ime.commitKeydownSeen = false;
},
};
}
@@ -69,9 +76,15 @@ export function imeOwnsInputKeydown(
nativeEvent: { isComposing?: boolean };
},
ime: InputImeState,
+ options?: { modifiedEnterSubmits?: boolean },
): boolean {
+ if (event.key === "Enter" && (event.nativeEvent.isComposing || ime.open)) {
+ ime.commitKeydownSeen = true;
+ }
const msSinceCompositionEnd = event.timeStamp - ime.endedAt;
ime.endedAt = -Infinity;
+ // A held candidate Enter repeats past compositionend: same press, never the submit.
+ if (event.key === "Enter" && event.repeat) return true;
if (event.nativeEvent.isComposing) return true;
if (event.keyCode !== 229) {
// Candidate-confirming Enter can arrive as keyCode 13 mid-composition; swallow it once.
@@ -79,7 +92,10 @@ export function imeOwnsInputKeydown(
ime.open = false;
return confirmsCandidate;
}
- return imeKeydownBlocksComposerSubmit(event, ime.open, msSinceCompositionEnd);
+ const candidate = options?.modifiedEnterSubmits
+ ? { ...event, metaKey: false, ctrlKey: false }
+ : event;
+ return imeKeydownBlocksComposerSubmit(candidate, ime.open, msSinceCompositionEnd);
}
export function composerKeyEventForImeSubmit(
diff --git a/studio/frontend/tests/chat-rename-ime.test.ts b/studio/frontend/tests/chat-rename-ime.test.ts
index 90ce6918a0b..f9d4bd17e64 100644
--- a/studio/frontend/tests/chat-rename-ime.test.ts
+++ b/studio/frontend/tests/chat-rename-ime.test.ts
@@ -170,14 +170,12 @@ for (const [name, file, inline] of [
});
}
-test("sidebar inline: an unchanged IME Enter does not close the input", () => {
+test("sidebar inline: a separate idle Pinyin Enter closes an unchanged input", () => {
const f = fixture("components/app-sidebar.tsx", true, false);
f.compose(true);
f.key("Enter", true);
f.compose(false);
f.key("Enter", false, 229);
- assert.deepEqual(f.effects, []);
- f.key("Enter");
assert.deepEqual(f.effects, ["prevent", "close"]);
});
@@ -249,9 +247,29 @@ test("focus change clears a recent compositionend so the next idle Pinyin Enter
test("a keyCode 13 candidate-confirming Enter inside an open composition is swallowed once", () => {
const state = newInputImeState();
- inputImeHandlers(state).onCompositionStart();
+ const ime = inputImeHandlers(state);
+ ime.onCompositionStart();
assert.equal(imeOwnsInputKeydown(plainEnter(13, 2000), state), true);
- assert.equal(imeOwnsInputKeydown(plainEnter(13, 5000), state), false);
+ ime.onCompositionEnd({ timeStamp: 2010 });
+ assert.equal(imeOwnsInputKeydown(plainEnter(229, 2100), state), false);
+});
+
+test("a Chrome-order composition does not swallow the next idle Pinyin Enter", () => {
+ const state = newInputImeState();
+ const ime = inputImeHandlers(state);
+ ime.onCompositionStart();
+ assert.equal(
+ imeOwnsInputKeydown(
+ {
+ ...plainEnter(229, 1000),
+ nativeEvent: { isComposing: true },
+ },
+ state,
+ ),
+ true,
+ );
+ ime.onCompositionEnd({ timeStamp: 1010 });
+ assert.equal(imeOwnsInputKeydown(plainEnter(229, 1100), state), false);
});
test("every rename input resets IME state on focus and blur", () => {
diff --git a/studio/frontend/tests/edit-project-dialog.test.ts b/studio/frontend/tests/edit-project-dialog.test.ts
index 6fb2712d78e..f958296f345 100644
--- a/studio/frontend/tests/edit-project-dialog.test.ts
+++ b/studio/frontend/tests/edit-project-dialog.test.ts
@@ -114,9 +114,13 @@ test("the dialog commits on Enter and on the chord", () => {
DIALOG,
/if \(e\.key === "Enter" && \(e\.metaKey \|\| e\.ctrlKey\)\) \{\n\s*e\.preventDefault\(\);\n\s*void save\(\);/,
);
+ const nameInput = DIALOG.slice(
+ DIALOG.indexOf("<input"),
+ DIALOG.indexOf("autoFocus={true}"),
+ );
assert.match(
- DIALOG,
- /onKeyDown=\{\(e\) => \{\n\s*if \(e\.key === "Enter"\) \{\n\s*e\.preventDefault\(\);\n(?:\s*\/\/.*\n)*\s*e\.stopPropagation\(\);\n\s*void save\(\);/,
+ nameInput,
+ /if \(e\.key === "Enter"\) \{\n\s*e\.preventDefault\(\);\n(?:\s*\/\/.*\n)*\s*e\.stopPropagation\(\);\n\s*void save\(\);/,
);
});
diff --git a/studio/frontend/tests/project-name-ime.test.ts b/studio/frontend/tests/project-name-ime.test.ts
new file mode 100644
index 00000000000..de906fec1fc
--- /dev/null
+++ b/studio/frontend/tests/project-name-ime.test.ts
@@ -0,0 +1,294 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import ts from "typescript";
+import {
+ imeOwnsInputKeydown,
+ inputImeHandlers,
+ newInputImeState,
+} from "../src/features/chat/utils/composer-preferences.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+type Target = "input" | "dialog";
+
+function assertImeHandlerSpread(file: string, target: Target) {
+ const source = ts.createSourceFile(
+ file,
+ readSrc(file),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const matches: ts.JsxSpreadAttribute[] = [];
+ function visit(node: ts.Node) {
+ if (
+ (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&
+ node.tagName.getText(source) ===
+ (target === "input" ? "input" : "DialogContent")
+ ) {
+ for (const attribute of node.attributes.properties) {
+ if (
+ ts.isJsxSpreadAttribute(attribute) &&
+ attribute.expression.getText(source) === "nameImeHandlers"
+ ) {
+ matches.push(attribute);
+ }
+ }
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ assert.equal(
+ matches.length,
+ 1,
+ `${file}: unique ${target} IME handler spread`,
+ );
+}
+
+function compositionHandlers(file: string, deps: Record<string, unknown>) {
+ const source = ts.createSourceFile(
+ file,
+ readSrc(file),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const matches: ts.ObjectLiteralExpression[] = [];
+ function visit(node: ts.Node) {
+ if (
+ ts.isVariableDeclaration(node) &&
+ node.name.getText(source) === "nameImeHandlers" &&
+ node.initializer &&
+ ts.isObjectLiteralExpression(node.initializer)
+ ) {
+ matches.push(node.initializer);
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ assert.equal(matches.length, 1, `${file}: unique IME handler object`);
+ const code = ts.transpileModule(`return (${matches[0].getText(source)});`, {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.None,
+ },
+ }).outputText;
+ return new Function(...Object.keys(deps), code)(...Object.values(deps)) as {
+ onFocus: () => void;
+ onBlur: () => void;
+ onCompositionStart: () => void;
+ onCompositionEnd: (event: { timeStamp: number }) => void;
+ };
+}
+
+function keyHandler(
+ file: string,
+ target: Target,
+ action: "commitCreate" | "save",
+ deps: Record<string, unknown>,
+) {
+ const source = ts.createSourceFile(
+ file,
+ readSrc(file),
+ ts.ScriptTarget.Latest,
+ true,
+ ts.ScriptKind.TSX,
+ );
+ const matches: ts.ArrowFunction[] = [];
+ function visit(node: ts.Node) {
+ if (
+ ts.isJsxAttribute(node) &&
+ node.name.getText(source) === "onKeyDown" &&
+ node.initializer &&
+ ts.isJsxExpression(node.initializer) &&
+ node.initializer.expression &&
+ ts.isArrowFunction(node.initializer.expression)
+ ) {
+ const opening = node.parent.parent;
+ if (
+ (ts.isJsxOpeningElement(opening) ||
+ ts.isJsxSelfClosingElement(opening)) &&
+ opening.tagName.getText(source) ===
+ (target === "input" ? "input" : "DialogContent") &&
+ node.initializer.expression.getText(source).includes(`${action}()`)
+ ) {
+ matches.push(node.initializer.expression);
+ }
+ }
+ ts.forEachChild(node, visit);
+ }
+ visit(source);
+ assert.equal(matches.length, 1, `${file}: unique ${target} handler`);
+ const code = ts.transpileModule(`return (${matches[0].getText(source)});`, {
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.None,
+ },
+ }).outputText;
+ return new Function(...Object.keys(deps), code)(...Object.values(deps)) as (
+ event: object,
+ ) => void;
+}
+
+function fixture(
+ file: string,
+ action: "commitCreate" | "save",
+ target: Target = "input",
+) {
+ const effects: string[] = [];
+ const nameImeRef = { current: newInputImeState() };
+ const ime = compositionHandlers(file, { inputImeHandlers, nameImeRef });
+ const onKey = keyHandler(file, target, action, {
+ imeOwnsInputKeydown,
+ nameImeRef,
+ commitCreate: () => effects.push("submit"),
+ save: () => effects.push("submit"),
+ });
+ let now = 1000;
+ function key({
+ isComposing = false,
+ keyCode = 13,
+ metaKey = false,
+ ctrlKey = false,
+ repeat = false,
+ advance = 1000,
+ }: {
+ isComposing?: boolean;
+ keyCode?: number;
+ metaKey?: boolean;
+ ctrlKey?: boolean;
+ repeat?: boolean;
+ advance?: number;
+ } = {}) {
+ now += advance;
+ onKey({
+ key: "Enter",
+ keyCode,
+ metaKey,
+ ctrlKey,
+ shiftKey: false,
+ altKey: false,
+ repeat,
+ timeStamp: now,
+ nativeEvent: { isComposing },
+ preventDefault: () => effects.push("prevent"),
+ stopPropagation: () => effects.push("stop"),
+ });
+ }
+ function compose(start: boolean) {
+ if (start) ime.onCompositionStart();
+ else ime.onCompositionEnd({ timeStamp: now + 999 });
+ }
+ return {
+ effects,
+ key,
+ compose,
+ focus: ime.onFocus,
+ blur: ime.onBlur,
+ };
+}
+
+for (const [name, file, action] of [
+ [
+ "new project",
+ "features/chat/components/new-project-dialog.tsx",
+ "commitCreate",
+ ],
+ ["edit project", "features/chat/components/edit-project-dialog.tsx", "save"],
+] as const) {
+ test(`${name}: composition events update the state used by its key handler`, () => {
+ assertImeHandlerSpread(file, name === "new project" ? "input" : "dialog");
+ });
+
+ test(`${name}: composition Enter waits for a separate Enter`, () => {
+ const f = fixture(file, action);
+ f.compose(true);
+ f.key({ isComposing: true });
+ assert.equal(f.effects.includes("submit"), false);
+ f.compose(false);
+ f.key({ keyCode: 229 });
+ assert.equal(f.effects.filter((effect) => effect === "submit").length, 1);
+ });
+
+ test(`${name}: WebKit compositionend-before-keydown waits for a separate Enter`, () => {
+ const f = fixture(file, action);
+ f.compose(true);
+ f.compose(false);
+ f.key({ keyCode: 229 });
+ assert.equal(f.effects.includes("submit"), false);
+ f.key({ keyCode: 229, advance: 100 });
+ assert.equal(f.effects.filter((effect) => effect === "submit").length, 1);
+ });
+
+ test(`${name}: a held candidate Enter cannot auto-repeat into submit`, () => {
+ const f = fixture(file, action);
+ f.compose(true);
+ f.key({ isComposing: true });
+ f.compose(false);
+ f.key({ keyCode: 229, repeat: true, advance: 50 });
+ assert.equal(f.effects.includes("submit"), false);
+ f.key({ keyCode: 229, advance: 50 });
+ assert.equal(f.effects.filter((effect) => effect === "submit").length, 1);
+ });
+
+ test(`${name}: idle macOS Pinyin Enter still submits`, () => {
+ const f = fixture(file, action);
+ f.key({ keyCode: 229 });
+ assert.equal(f.effects.filter((effect) => effect === "submit").length, 1);
+ });
+
+ for (const modifier of ["metaKey", "ctrlKey"] as const) {
+ test(`${name}: idle macOS Pinyin ${modifier} Enter still submits`, () => {
+ const f = fixture(file, action);
+ f.key({ keyCode: 229, [modifier]: true });
+ assert.equal(f.effects.filter((effect) => effect === "submit").length, 1);
+ });
+ }
+
+ for (const reset of ["focus", "blur"] as const) {
+ test(`${name}: ${reset} clears a missing compositionend`, () => {
+ const f = fixture(file, action);
+ f.compose(true);
+ f[reset]();
+ f.key({ keyCode: 229 });
+ assert.equal(f.effects.filter((effect) => effect === "submit").length, 1);
+ });
+ }
+}
+
+test("edit project: composition blocks the save chord from the instructions field", () => {
+ const f = fixture(
+ "features/chat/components/edit-project-dialog.tsx",
+ "save",
+ "dialog",
+ );
+ f.compose(true);
+ f.key({ isComposing: true, metaKey: true });
+ assert.equal(f.effects.includes("submit"), false);
+ f.compose(false);
+ f.key({ metaKey: true });
+ assert.equal(f.effects.filter((effect) => effect === "submit").length, 1);
+});
+
+for (const modifier of ["metaKey", "ctrlKey"] as const) {
+ test(`edit project: idle macOS Pinyin ${modifier} save chord from instructions submits`, () => {
+ const f = fixture(
+ "features/chat/components/edit-project-dialog.tsx",
+ "save",
+ "dialog",
+ );
+ f.key({ keyCode: 229, [modifier]: true });
+ assert.equal(f.effects.filter((effect) => effect === "submit").length, 1);
+ });
+}
+
+test("edit project: blocked name candidate cannot bubble into the save chord", () => {
+ const f = fixture("features/chat/components/edit-project-dialog.tsx", "save");
+ f.compose(true);
+ f.compose(false);
+ f.key({ keyCode: 229, metaKey: true });
+ assert.equal(f.effects.includes("submit"), false);
+ assert.equal(f.effects.includes("stop"), true);
+});