πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(editor): magic paste for JSON editors (LFE-10488) (#14526)
Nikita Kabardinac4a8cb9cf7e
diff --git a/web/src/components/editor/CodeMirrorEditor.tsx b/web/src/components/editor/CodeMirrorEditor.tsxindex 60ae090e06..9bc8066e1b 100644--- a/web/src/components/editor/CodeMirrorEditor.tsx+++ b/web/src/components/editor/CodeMirrorEditor.tsx@@ -32,6 +32,7 @@ import {import { lightTheme } from "@/src/components/editor/light-theme";import { darkTheme } from "@/src/components/editor/dark-theme";import { autoScrollOnSelectionDrag } from "@/src/components/editor/autoScrollOnSelectionDrag";+import { createJsonMagicPasteExtension } from "@/src/components/editor/jsonMagicPaste";// Custom language mode for prompts that highlights mustache variables and prompt dependency tagsconst promptLanguage = StreamLanguage.define({@@ -509,6 +510,10 @@ export function CodeMirrorEditor({: []),...(mode === "json" ? [json()] : []),...(mode === "json" && linterEnabled ? [linter(jsonParseLinter())] : []),+ // Magic paste: when editing JSON, escape pasted text inside a string (or+ // wrap a blob pasted into a blank field) so the JSON stays valid, with a+ // "Paste raw" escape hatch. Conservative β defers to normal paste otherwise.+ ...(editable && mode === "json" ? [createJsonMagicPasteExtension()] : []),...(mode === "prompt" ? [promptSupport, promptLinter] : []),...(lineWrapping ? [EditorView.lineWrapping] : []),...(additionalExtensions ?? []),diff --git a/web/src/components/editor/fileDropPaste.ts b/web/src/components/editor/fileDropPaste.tsindex fac47b61df..92e7dece9a 100644--- a/web/src/components/editor/fileDropPaste.ts+++ b/web/src/components/editor/fileDropPaste.ts@@ -3,9 +3,13 @@ import { type Extension } from "@codemirror/state";/*** Collects files from a drop/paste transfer, falling back to `items` for- * sources (e.g. clipboard images) that don't populate `files`.+ * sources (e.g. clipboard images) that don't populate `files`. Exported so other+ * paste handlers (e.g. magic paste) can detect a file paste with the exact same+ * definition, avoiding a gap where both handlers defer and the default fires.*/-function extractTransferFiles(data: DataTransfer | null | undefined): File[] {+export function extractTransferFiles(+ data: DataTransfer | null | undefined,+): File[] {if (!data) return [];if (data.files.length > 0) return Array.from(data.files);const files: File[] = [];diff --git a/web/src/components/editor/index.ts b/web/src/components/editor/index.tsindex d7c1421fbc..3ef451a7c8 100644--- a/web/src/components/editor/index.ts+++ b/web/src/components/editor/index.ts@@ -1,2 +1,3 @@export * from "./CodeMirrorEditor";export * from "./fileDropPaste";+export * from "./jsonMagicPaste";diff --git a/web/src/components/editor/jsonMagicPaste.clienttest.ts b/web/src/components/editor/jsonMagicPaste.clienttest.tsnew file mode 100644index 0000000000..a455900b7a--- /dev/null+++ b/web/src/components/editor/jsonMagicPaste.clienttest.ts@@ -0,0 +1,183 @@+import { EditorSelection, EditorState } from "@codemirror/state";++import {+ escapeForJsonStringBody,+ isInsideJsonString,+ isValidJson,+ planMagicPaste,+} from "./jsonMagicPaste";++function jsonState(doc: string, anchor = 0, head = anchor): EditorState {+ return EditorState.create({ doc, selection: { anchor, head } });+}++describe("escapeForJsonStringBody", () => {+ it("escapes quotes, backslashes, and newlines", () => {+ expect(escapeForJsonStringBody('say "hi"\nbye')).toBe('say \\"hi\\"\\nbye');+ expect(escapeForJsonStringBody("a\\b")).toBe("a\\\\b");+ expect(escapeForJsonStringBody("tab\there")).toBe("tab\\there");+ });++ it("is a no-op for text with no JSON-special characters", () => {+ expect(escapeForJsonStringBody("plain text 123")).toBe("plain text 123");+ });++ it("round-trips: wrapping the body in quotes parses back to the input", () => {+ const text = 'multi\nline "quoted" \\ slash';+ expect(JSON.parse(`"${escapeForJsonStringBody(text)}"`)).toBe(text);+ });+});++describe("isValidJson", () => {+ it.each([+ ['{"a":1}', true],+ ['"x"', true],+ ["42", true],+ ["true", true],+ ["hello", false],+ ["", false],+ [" ", false],+ ['{"a":}', false],+ ] as const)("isValidJson(%j) === %s", (input, expected) => {+ expect(isValidJson(input)).toBe(expected);+ });+});++describe("isInsideJsonString", () => {+ const doc = '{"key": "value"}';++ it("is true inside a string value body", () => {+ const pos = doc.indexOf("value") + 2; // between v-a-l...+ expect(isInsideJsonString(jsonState(doc, pos), pos)).toBe(true);+ });++ it("is true inside a property name", () => {+ const pos = doc.indexOf("key") + 1;+ expect(isInsideJsonString(jsonState(doc, pos), pos)).toBe(true);+ });++ it("is false at a structural position (after the colon)", () => {+ const pos = doc.indexOf(":") + 1;+ expect(isInsideJsonString(jsonState(doc, pos), pos)).toBe(false);+ });++ it("is false on the opening quote boundary", () => {+ const pos = doc.indexOf('"value"'); // on the quote itself+ expect(isInsideJsonString(jsonState(doc, pos), pos)).toBe(false);+ });++ it("is false in an empty document", () => {+ expect(isInsideJsonString(jsonState("", 0), 0)).toBe(false);+ });++ it("treats an unterminated string as open", () => {+ const open = '{"a": "ab';+ const pos = open.length; // caret at EOF, inside the unterminated string+ expect(isInsideJsonString(jsonState(open, pos), pos)).toBe(true);+ });+});++describe("planMagicPaste", () => {+ it("escapes a fragment pasted inside a string value", () => {+ const doc = '{"text": ""}';+ const pos = doc.indexOf('""') + 1; // between the empty string's quotes+ const plan = planMagicPaste(jsonState(doc, pos), 'a "quote"\nline');+ expect(plan).toMatchObject({+ kind: "escape",+ from: pos,+ to: pos,+ insert: 'a \\"quote\\"\\nline',+ });+ });++ it("returns null inside a string when nothing needs escaping", () => {+ const doc = '{"text": ""}';+ const pos = doc.indexOf('""') + 1;+ expect(planMagicPaste(jsonState(doc, pos), "plain words")).toBeNull();+ });++ it("wraps a non-JSON blob pasted into an empty field", () => {+ const text = 'Chapter 1.\nHe said "stop".';+ const plan = planMagicPaste(jsonState("", 0), text);+ expect(plan).toMatchObject({+ kind: "wrap",+ from: 0,+ to: 0,+ insert: JSON.stringify(text),+ raw: text,+ });+ // The wrapped result is valid JSON.+ expect(isValidJson(plan!.insert)).toBe(true);+ });++ it("does not wrap when the pasted blob is already valid JSON", () => {+ expect(planMagicPaste(jsonState("", 0), '{"x": 1}')).toBeNull();+ });++ it("still wraps a blank (whitespace-only) field", () => {+ const plan = planMagicPaste(jsonState(" \n ", 0), "hi there");+ expect(plan).toMatchObject({ kind: "wrap", insert: '"hi there"' });+ });++ it("does NOT wrap select-all-then-paste over existing content", () => {+ // Wrapping a whole-doc replacement would silently stringify the user's+ // existing structure; leave it to normal paste instead.+ const doc = '{"old": 1}';+ expect(+ planMagicPaste(jsonState(doc, 0, doc.length), "just text"),+ ).toBeNull();+ });++ it("defers multi-cursor pastes to native per-cursor paste", () => {+ const doc = '{"a":"","b":""}';+ const a = doc.indexOf('""') + 1;+ const b = doc.lastIndexOf('""') + 1;+ const state = EditorState.create({+ doc,+ selection: EditorSelection.create([+ EditorSelection.cursor(a),+ EditorSelection.cursor(b),+ ]),+ // basicSetup enables this in the real editor; needed for >1 range to stick.+ extensions: [EditorState.allowMultipleSelections.of(true)],+ });+ expect(state.selection.ranges.length).toBe(2);+ expect(planMagicPaste(state, 'x"y')).toBeNull();+ });++ it("leaves a mid-document structural paste alone", () => {+ const doc = '{"a": 1, "b": 2}';+ const pos = doc.indexOf(", ") + 1; // structural position between properties+ expect(planMagicPaste(jsonState(doc, pos), "garbage")).toBeNull();+ });++ it("escapes a selection wholly inside one string value", () => {+ const doc = '{"a": "hello"}';+ const from = doc.indexOf("hello"); // start of the value text+ const to = from + "hello".length; // end, still inside the same string+ const plan = planMagicPaste(jsonState(doc, from, to), 'x"y');+ expect(plan).toMatchObject({ kind: "escape", from, to, insert: 'x\\"y' });+ });++ it("does NOT escape a selection that spans two different strings", () => {+ // Selecting from inside the first value, across `","b":"`, into the second+ // would collapse the two keys if escaped. Must be left to normal paste. Use a+ // paste that needs escaping so the no-op short-circuit doesn't mask the gate.+ const doc = '{"a":"1","b":"2"}';+ const from = doc.indexOf("1"); // inside the first value+ const to = doc.indexOf("2"); // inside the second value+ expect(planMagicPaste(jsonState(doc, from, to), 'x"y')).toBeNull();+ });++ it("does NOT escape when the caret sits mid-escape (after a lone backslash)", () => {+ // doc `"a\nb"` is valid JSON (string a + newline + b); caret between `\` and+ // `n`. Escaping there would split the `\n` and corrupt the JSON.+ const doc = '"a\\nb"';+ const pos = doc.indexOf("\\") + 1; // right after the backslash+ expect(planMagicPaste(jsonState(doc, pos), '"')).toBeNull();+ });++ it("returns null for an empty paste", () => {+ expect(planMagicPaste(jsonState("", 0), "")).toBeNull();+ });+});diff --git a/web/src/components/editor/jsonMagicPaste.ts b/web/src/components/editor/jsonMagicPaste.tsnew file mode 100644index 0000000000..899f89cee9--- /dev/null+++ b/web/src/components/editor/jsonMagicPaste.ts@@ -0,0 +1,395 @@+import {+ EditorView,+ keymap,+ showTooltip,+ type Tooltip,+} from "@uiw/react-codemirror";+import {+ type EditorState,+ StateEffect,+ StateField,+ type Extension,+} from "@codemirror/state";+import { extractTransferFiles } from "@/src/components/editor/fileDropPaste";++/**+ * "Magic paste" for JSON editors.+ *+ * Non-technical users routinely paste raw text (a log, a chapter, a blob) into a+ * JSON field. Unescaped quotes / backslashes / newlines / control chars inside a+ * string value, or a bare blob in an empty field, produce invalid JSON β and the+ * data is private, so an external escape tool isn't an option. This extension+ * transforms the paste client-side so the JSON stays valid, and shows a passive,+ * dismissible "Paste raw" affordance at the paste site (the transform is a single+ * transaction, so Cmd/Ctrl+Z also reverts it in one step).+ *+ * Two high-confidence, lossless transforms β both fully reversible, so they apply+ * automatically rather than behind a chooser:+ * - Caret inside a JSON string value β escape the pasted fragment.+ * - Empty / fully-selected field whose paste isn't already valid JSON β wrap the+ * paste as a quoted JSON string.+ * Anything else (files, no-op escapes, structural mid-document pastes) is left to+ * the editor's normal paste handling.+ */++// --- pure helpers (exported for unit tests) -------------------------------++/**+ * Escapes arbitrary text so it can be inserted between existing JSON quotes.+ * `JSON.stringify` yields a fully quoted, escaped JSON string literal; stripping+ * the wrapping quotes leaves just the escaped body. Covers `"`, `\`, and all+ * control chars (`\n` `\r` `\t` `\b` `\f` and `\uXXXX`). U+2028/U+2029 are valid+ * unescaped inside a JSON string, so they're intentionally left as-is.+ */+export function escapeForJsonStringBody(text: string): string {+ return JSON.stringify(text).slice(1, -1);+}++/** Whether `text` is, on its own, syntactically valid JSON. */+export function isValidJson(text: string): boolean {+ const trimmed = text.trim();+ if (trimmed === "") return false;+ try {+ JSON.parse(trimmed);+ return true;+ } catch {+ return false;+ }+}++/**+ * Whether `pos` sits inside the body of a JSON string (a value string or a+ * property name β escaping is wanted inside both). Scans the document prefix with+ * the canonical JSON string state machine: an unescaped `"` toggles string mode,+ * and a `\` inside a string escapes the next char. This deliberately avoids the+ * syntax tree because an unterminated string (the user typed an opening quote+ * then pasted) isn't a `String` node in the Lezer grammar β the scanner treats+ * it as "still open", which is exactly what we want.+ */+export function isInsideJsonString(state: EditorState, pos: number): boolean {+ return isInsideJsonStringPrefix(state.doc.sliceString(0, pos));+}++/** Core string-state scan over the text preceding the caret. Module-private; the+ * `isInsideJsonString` wrapper above is the intended entry point. */+function isInsideJsonStringPrefix(prefix: string): boolean {+ let inString = false;+ for (let i = 0; i < prefix.length; i++) {+ const ch = prefix[i];+ if (inString) {+ if (ch === "\\") {+ // A backslash at the very end escapes the caret position: the caret sits+ // mid-escape-sequence (e.g. between `\` and `n` of `\n`). Inserting there+ // would split the escape, so treat it as not a safe in-string point.+ if (i === prefix.length - 1) return false;+ i++; // skip the escaped character+ } else if (ch === '"') {+ inString = false;+ }+ } else if (ch === '"') {+ inString = true;+ }+ }+ return inString;+}++/**+ * Whether a selection that starts inside a JSON string stays within that *same*+ * string β i.e. the selected text contains no unescaped `"`. Without this, a+ * selection spanning from one string, across structural JSON, into another+ * string would pass both endpoint checks (each is just quote parity) and the+ * escape branch would silently rewrite the structure between them.+ */+function selectionStaysInJsonString(+ state: EditorState,+ from: number,+ to: number,+): boolean {+ const selected = state.doc.sliceString(from, to);+ for (let i = 0; i < selected.length; i++) {+ const ch = selected[i];+ if (ch === "\\") {+ // A trailing backslash escapes a char outside the selection; replacing the+ // selection would orphan that escape, so treat it as leaving the string.+ if (i === selected.length - 1) return false;+ i++; // skip the escaped character+ } else if (ch === '"') {+ return false; // an unescaped quote closes the string mid-selection+ }+ }+ return true;+}++export type MagicPastePlan = {+ kind: "escape" | "wrap";+ from: number;+ to: number;+ /** The transformed text to insert in place of [from, to]. */+ insert: string;+ /** The original pasted text, kept for the "Paste raw" affordance. */+ raw: string;+};++/**+ * Decides how a pasted text should be transformed at the current selection, or+ * returns null when the paste should be handled normally by the editor.+ */+export function planMagicPaste(+ state: EditorState,+ pastedText: string,+): MagicPastePlan | null {+ if (pastedText === "") return null;+ // Multi-cursor: a single transform would only fill the main range and drop the+ // others, so defer to CodeMirror's native per-cursor paste.+ if (state.selection.ranges.length > 1) return null;+ const sel = state.selection.main;++ // 1) Inside a JSON string β escape the fragment. The selection must start in a+ // string and stay within that same string, so we never escape across a+ // structural boundary (which would silently rewrite the JSON shape).+ if (+ isInsideJsonString(state, sel.from) &&+ (sel.empty || selectionStaysInJsonString(state, sel.from, sel.to))+ ) {+ const insert = escapeForJsonStringBody(pastedText);+ // Nothing needed escaping: let CodeMirror paste normally (no surprise).+ if (insert === pastedText) return null;+ return {+ kind: "escape",+ from: sel.from,+ to: sel.to,+ insert,+ raw: pastedText,+ };+ }++ // 2) Blank field whose paste isn't already valid JSON β wrap it as a quoted+ // JSON string. Covers "paste a blob into the empty input field". Limited to+ // a blank document so select-all-then-paste over existing content isn't+ // silently stringified (its structure would be lost behind valid-looking+ // JSON); that case falls through to normal paste.+ const docIsBlank = state.doc.toString().trim() === "";+ if (docIsBlank && !isValidJson(pastedText)) {+ return {+ kind: "wrap",+ from: 0,+ to: state.doc.length,+ insert: JSON.stringify(pastedText),+ raw: pastedText,+ };+ }++ return null;+}++// --- the "Paste raw" affordance -------------------------------------------++type ActiveTip = {+ /** Range of the just-inserted transformed text. */+ from: number;+ to: number;+ /** Original text, re-inserted when the user chooses "Paste raw". */+ raw: string;+ message: string;+};++const setMagicPasteTip = StateEffect.define<ActiveTip | null>();++const magicPasteTipField = StateField.define<ActiveTip | null>({+ create() {+ return null;+ },+ update(value, tr) {+ // A magic paste sets the tip in the same transaction it edits the doc, so+ // the effect always wins over the dismiss rule below.+ for (const effect of tr.effects) {+ if (effect.is(setMagicPasteTip)) return effect.value;+ }+ // Dismiss on the next real edit (not a bare cursor move) so the control+ // survives navigation/reading; a blur handler clears it on focus-out.+ if (value && tr.docChanged) return null;+ return value;+ },+ provide: (field) =>+ showTooltip.from(field, (tip) => (tip ? buildTooltip(tip) : null)),+});++const PASTE_RAW_KEY = "Mod-Shift-v";+// `Mod` is Cmd on macOS, Ctrl elsewhere; mirror that in the hint and the+// aria-keyshortcuts. `navigator.userAgent` (not the deprecated `.platform`)+// matches repo convention.+const IS_MAC =+ typeof navigator !== "undefined" && navigator.userAgent.includes("Mac");+const PASTE_RAW_KEY_LABEL = IS_MAC ? "β§βV" : "Ctrl+Shift+V";+// WAI-ARIA spells the macOS Cmd key as "Meta".+const PASTE_RAW_ARIA_KEYS = IS_MAC ? "Meta+Shift+V" : "Control+Shift+V";++/** Replace the transformed insert with the original raw text (the escape hatch). */+function revertToRaw(view: EditorView, tip: ActiveTip): void {+ const docLength = view.state.doc.length;+ const from = Math.min(tip.from, docLength);+ const to = Math.min(tip.to, docLength);+ view.dispatch({+ changes: { from, to, insert: tip.raw },+ selection: { anchor: from + tip.raw.length },+ effects: setMagicPasteTip.of(null),+ userEvent: "input.paste",+ });+ view.focus();+}++function buildTooltip(tip: ActiveTip): Tooltip {+ return {+ // Anchor at the caret (end of the insert), where `scrollIntoView` brought the+ // viewport β anchoring at the start would land off-screen when a long paste+ // scrolls the start out of view.+ pos: tip.to,+ // Render below the paste so the editor's own top edge / overflow can't clip+ // it; `strictSide: false` still lets it flip up near the bottom of the view.+ above: false,+ strictSide: false,+ arrow: false,+ create(view) {+ const dom = document.createElement("div");+ dom.className = "cm-json-magic-paste";++ // Announce only the status (not the button) to assistive tech.+ const label = document.createElement("span");+ label.className = "cm-json-magic-paste-label";+ label.setAttribute("role", "status");+ label.setAttribute("aria-live", "polite");+ label.textContent = tip.message;++ // "Paste raw" is also reachable from the keyboard via PASTE_RAW_KEY (the+ // tooltip itself isn't in the editor's tab order), advertised here.+ const button = document.createElement("button");+ button.type = "button";+ button.className = "cm-json-magic-paste-action";+ button.textContent = "Paste raw";+ button.title = `Insert the original text, unescaped (${PASTE_RAW_KEY_LABEL})`;+ button.setAttribute(+ "aria-label",+ `Paste raw β insert the original text, unescaped`,+ );+ button.setAttribute("aria-keyshortcuts", PASTE_RAW_ARIA_KEYS);+ // Keep editor focus so the replace doesn't blur the editor first.+ button.addEventListener("mousedown", (event) => event.preventDefault());+ button.addEventListener("click", () => revertToRaw(view, tip));++ const hint = document.createElement("span");+ hint.className = "cm-json-magic-paste-hint";+ hint.setAttribute("aria-hidden", "true");+ hint.textContent = PASTE_RAW_KEY_LABEL;++ dom.append(label, button, hint);+ return { dom };+ },+ };+}++const magicPasteTheme = EditorView.baseTheme({+ // Paint our own surface from app tokens (instead of inheriting CodeMirror's+ // default tooltip background) so the foreground tokens keep their audited+ // contrast in both themes.+ ".cm-tooltip:has(.cm-json-magic-paste)": {+ backgroundColor: "hsl(var(--popover))",+ color: "hsl(var(--popover-foreground))",+ border: "1px solid hsl(var(--border))",+ borderRadius: "6px",+ boxShadow: "0 2px 8px rgb(0 0 0 / 0.12)",+ },+ ".cm-json-magic-paste": {+ display: "flex",+ alignItems: "center",+ gap: "8px",+ padding: "3px 8px",+ fontSize: "12px",+ lineHeight: "1.4",+ whiteSpace: "nowrap",+ },+ ".cm-json-magic-paste-label": {+ color: "hsl(var(--muted-foreground))",+ },+ ".cm-json-magic-paste-action": {+ padding: "0",+ margin: "0",+ border: "none",+ background: "none",+ font: "inherit",+ color: "hsl(var(--primary))",+ cursor: "pointer",+ textDecoration: "underline",+ },+ ".cm-json-magic-paste-hint": {+ color: "hsl(var(--muted-foreground))",+ opacity: "0.7",+ },+});++/**+ * CodeMirror extension that escapes/wraps pasted text so a JSON field stays valid+ * (see module docs). Files are left to a sibling drop/paste handler. Add it to a+ * `mode="json"` editor's `extensions` (memoize at the call site).+ */+export function createJsonMagicPasteExtension(): Extension {+ return [+ magicPasteTipField,+ magicPasteTheme,+ // Keyboard path for "Paste raw" (the tooltip button isn't in the tab order).+ keymap.of([+ {+ key: PASTE_RAW_KEY,+ run: (view) => {+ const tip = view.state.field(magicPasteTipField, false);+ if (!tip) return false; // no active transform β let the key fall through+ revertToRaw(view, tip);+ return true;+ },+ },+ ]),+ EditorView.domEventHandlers({+ // Clear the affordance when focus leaves so a stale tip can't linger behind+ // the user (and two editors can't show one at once).+ blur(_event, view) {+ if (view.state.field(magicPasteTipField, false)) {+ view.dispatch({ effects: setMagicPasteTip.of(null) });+ }+ return false;+ },+ paste(event, view) {+ // Let the editor's composition-aware paste handle IME composition.+ if (view.composing) return false;+ const clipboard = event.clipboardData;+ if (!clipboard) return false;+ // Files belong to the media drop/paste handler. Use the same extractor it+ // does so we never both defer and leave the default handler to insert+ // unescaped text.+ if (extractTransferFiles(clipboard).length > 0) return false;+ const text = clipboard.getData("text/plain");+ if (!text) return false;++ const plan = planMagicPaste(view.state, text);+ if (!plan) return false;++ event.preventDefault();+ const insertEnd = plan.from + plan.insert.length;+ view.dispatch({+ changes: { from: plan.from, to: plan.to, insert: plan.insert },+ selection: { anchor: insertEnd },+ effects: setMagicPasteTip.of({+ from: plan.from,+ to: insertEnd,+ raw: plan.raw,+ message:+ plan.kind === "wrap"+ ? "Wrapped as a JSON string"+ : "Escaped to keep JSON valid",+ }),+ userEvent: "input.paste",+ scrollIntoView: true,+ });+ return true;+ },+ }),+ ];+}