Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

fix(frontend): keep IME input and the caret working in text fields that rewrite what the user types (#15649)

Krzysztof Czerwinskia3fbaeae6e1a
diff --git a/AGENTS.md b/AGENTS.md
index 94106977db..6a5dba7c45 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -40,6 +40,7 @@ See `/frontend/CONTRIBUTING.md` for complete patterns. Quick reference:
5. **Testing**: Integration tests (Vitest + RTL + MSW) are the default (~90%, page-level). Playwright for E2E critical flows. Storybook for design system components. See `autogpt_platform/frontend/TESTING.md`
6. **Code conventions**: Function declarations (not arrow functions) for components/handlers
7. **Keyboard handling**: Use `isKey(e, "Enter")` (or `isKey(e, "Enter", " ")`) from `@/lib/keyboard` instead of comparing `e.key`. It returns false while an IME is composing (Japanese, Chinese, Korean input), when Enter/Space/arrows belong to the input method, not the app. The `Input` atom drops composing keydowns before calling `onKeyDown` as a safety net; every handler on a raw `<input>`/`<textarea>`, a container, or `document` must use `isKey` itself. That atom-level guard is deliberately unconditional, so a modifier chord wired through `<Input onKeyDown>` is dropped mid-composition too — handle chords outside the atom. For focus traps and other containment handlers, which must keep holding a key even while composing, use `isKeyIgnoringComposition`. ESLint (`no-restricted-syntax`) flags direct `.key` comparisons and switches against the IME key names only; `// eslint-disable-next-line no-restricted-syntax` is the escape hatch for a domain object that merely has a `.key` field (e.g. `column.key === "Delete"`). Modifier chords like Cmd+K, `.key.toLowerCase()` and `[...].includes(e.key)` are not checked and are out of scope, since an IME never owns them. Passing `e.key` on as a function argument (e.g. into a roving-focus helper) is also invisible to the rule — guard those handlers with `isComposingEvent(e)` at the top.
+8. **Text field values**: a controlled `<input>`/`<textarea>` must show exactly what was typed, in the same render as the keystroke. If React writes any other value back (the old one, because the new one arrives a render later through a `useEffect`, a context `register` or a store; a reformatted one, such as pretty-printed JSON; or a rebuilt one, after an edit that didn't parse was dropped), the caret jumps to the end and every IME composition is cancelled (Japanese `nihongo` comes out as `nいhおnngお`). Lint can't see this, so: keep the user's text in state the field reads directly, send it up from the change handler, and replace it from outside only when the stored value really differs (`isJsonTextFor` in `@/lib/json-text` does that check for JSON). Test any field that transforms or round-trips its value with `expectTypingKept` from `@/tests/integrations/typing`.
- Component props should be `interface Props { ... }` (not exported) unless the interface needs to be used outside the component
- Separate render logic from business logic (component.tsx + useComponent.ts + helpers.ts)
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx
index 25703f6321..4b249eab7c 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/QuestionDock.tsx
@@ -13,6 +13,7 @@ import { CopilotChatActionsContext } from "../CopilotChatActionsProvider/useCopi
import { ChainActionsContext } from "../ToolChain/chainActions";
import {
buildAnswersMessage,
+ buildQuestionsEntry,
getPendingQuestions,
type PendingQuestions,
} from "./helpers";
@@ -41,26 +42,18 @@ export function QuestionsForm({ dockId, questions }: FormProps) {
// Proceed step — register readiness + message instead.
useEffect(() => {
if (!chainActions || dismissed) return;
- chainActions.register({
- id: dockId,
- ready: allAnswered,
- // Answers are ready on the first character of the last one; the user
- // reviews them through the dock's own action, not an automatic send.
- manualProceed: true,
- buildMessage: () =>
- allAnswered ? buildAnswersMessage(questions, answers) : null,
- onSent: () => setDismissedId(dockId),
- questions: {
- id: dockId,
+ chainActions.register(
+ buildQuestionsEntry({
+ dockId,
questions,
answers,
- onAnswer: (keyword, value) =>
- setAnswers((prev) => ({ ...prev, [keyword]: value })),
- onSkip: () => setDismissedId(dockId),
- },
- });
+ register: chainActions.register,
+ setAnswers,
+ dismiss: () => setDismissedId(dockId),
+ }),
+ );
return () => chainActions.unregister(dockId);
- }, [chainActions, dismissed, dockId, allAnswered, answers, questions]);
+ }, [chainActions, dismissed, dockId, answers, questions]);
if (renderedDockId !== dockId) {
setRenderedDockId(dockId);
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/helpers.ts
index 7b23e8a80e..f674ca946a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/QuestionDock/helpers.ts
@@ -1,11 +1,14 @@
import type { ToolUIPart, UIDataTypes, UIMessage, UITools } from "ai";
+import type { Dispatch, SetStateAction } from "react";
import {
type ClarifyingQuestion,
type QuestionAnswer,
extractClarifyingQuestions,
formatAnswer,
+ isAnswered,
normalizeClarifyingQuestions,
} from "../../tools/clarifying-questions";
+import type { ChainActionEntry } from "../ToolChain/chainActions";
export interface PendingQuestions {
dockId: string;
@@ -73,3 +76,54 @@ export function buildAnswersMessage(
.join("\n\n");
return `**Here are my answers:**\n\n${body}\n\nPlease proceed.`;
}
+
+type Answers = Record<string, QuestionAnswer>;
+
+interface QuestionsEntryArgs {
+ dockId: string;
+ questions: ClarifyingQuestion[];
+ answers: Answers;
+ register: (entry: ChainActionEntry) => void;
+ setAnswers: Dispatch<SetStateAction<Answers>>;
+ dismiss: () => void;
+}
+
+/** The questions card's entry in the tool chain. An answer re-registers the
+ * entry in the same event as the keystroke: left to the asking component's
+ * effect, the field would get its value one render late, and React writing
+ * the old value back in between moves the caret to the end and cancels an
+ * IME composition (Japanese "nihongo" came out as "nいhおnngお"). */
+export function buildQuestionsEntry(
+ args: QuestionsEntryArgs,
+): ChainActionEntry {
+ const { dockId, questions, answers, register, setAnswers, dismiss } = args;
+ const ready = questions.every((q) => isAnswered(answers[q.keyword]));
+ return {
+ id: dockId,
+ ready,
+ // Answers are ready on the first character of the last one; the user
+ // reviews them through the dock's own action, not an automatic send.
+ manualProceed: true,
+ buildMessage: () =>
+ ready ? buildAnswersMessage(questions, answers) : null,
+ onSent: dismiss,
+ questions: {
+ id: dockId,
+ questions,
+ answers,
+ onAnswer: (keyword, value) => {
+ // State takes the functional update so a second answer in the same
+ // event can't drop the first; the entry registered here is what the
+ // field shows this render, and the effect re-registers from state.
+ setAnswers((prev) => ({ ...prev, [keyword]: value }));
+ register(
+ buildQuestionsEntry({
+ ...args,
+ answers: { ...answers, [keyword]: value },
+ }),
+ );
+ },
+ onSkip: dismiss,
+ },
+ };
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx
index f221135a62..3ad5c3b507 100644
--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/ToolChain/__tests__/ToolChain.test.tsx
@@ -12,6 +12,7 @@ import type { MessagePart } from "../../ChatMessagesContainer/helpers";
import type { PendingQuestions } from "../../QuestionDock/helpers";
import { PendingQuestionsContext } from "../../QuestionDock/PendingQuestionsContext";
import { ToolChain } from "../ToolChain";
+import { expectTypingKept } from "@/tests/integrations/typing";
vi.mock("@/components/molecules/Toast/use-toast", () => ({
toast: vi.fn(),
@@ -399,6 +400,45 @@ describe("ToolChain", () => {
expect(screen.queryByText("Answer a few questions")).toBeNull();
});
+ it("keeps the caret where the user is editing an answer", async () => {
+ // The answer used to reach the field one render late, and React writing
+ // the old value back in between threw the caret to the end and broke
+ // IME input (Japanese "nihongo" came out as "nいhおnngお").
+ const user = userEvent.setup();
+ const pending: PendingQuestions = {
+ dockId: "m1:call-ask_question",
+ callIds: ["call-ask_question"],
+ questions: [
+ { question: "Which region?", keyword: "region", example: "Europe" },
+ ],
+ };
+
+ render(
+ <CopilotChatActionsProvider onSend={onSend}>
+ <PendingQuestionsContext.Provider value={pending}>
+ <ToolChain
+ parts={[
+ toolPart("ask_question", "output-available", {
+ output: {
+ type: "agent_builder_clarification_needed",
+ questions: pending.questions,
+ },
+ }),
+ ]}
+ isStreaming={false}
+ />
+ </PendingQuestionsContext.Provider>
+ </CopilotChatActionsProvider>,
+ );
+
+ const field = screen.getByPlaceholderText(
+ "e.g. Europe",
+ ) as HTMLTextAreaElement;
+ await user.type(field, "Wstern");
+ await expectTypingKept(field, "e", 1);
+ await expectTypingKept(field, " 日本語");
+ });
+
it("reports a rejected send without bringing the card back", async () => {
const user = userEvent.setup();
onSend.mockRejectedValueOnce(new Error("boom"));
diff --git a/autogpt_platform/frontend/src/components/atoms/Input/Input.test.tsx b/autogpt_platform/frontend/src/components/atoms/Input/Input.test.tsx
index ffe500036f..3dc509faaf 100644
--- a/autogpt_platform/frontend/src/components/atoms/Input/Input.test.tsx
+++ b/autogpt_platform/frontend/src/components/atoms/Input/Input.test.tsx
@@ -1,5 +1,7 @@
import { fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
import { describe, expect, it, vi } from "vitest";
+import { expectTypingKept } from "@/tests/integrations/typing";
import { Input } from "./Input";
describe("Input keyboard handling", () => {
@@ -52,3 +54,32 @@ describe("Input keyboard handling", () => {
expect(onKeyDown).toHaveBeenCalledTimes(1);
});
});
+
+// Every text field built on the atom inherits this: if the atom ever rewrote
+// its value (a formatter, a late sync), IME input and the caret would break
+// everywhere at once.
+describe("Input typing", () => {
+ function ControlledInput({ type }: { type: "text" | "textarea" }) {
+ const [value, setValue] = useState("Wstern");
+ return (
+ <Input
+ id="field"
+ label="Field"
+ type={type}
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ />
+ );
+ }
+
+ it.each(["text", "textarea"] as const)(
+ "keeps the text and caret as typed in the %s variant",
+ async (type) => {
+ render(<ControlledInput type={type} />);
+ const field = screen.getByLabelText("Field") as HTMLInputElement;
+
+ await expectTypingKept(field, "e", 1);
+ await expectTypingKept(field, " 日本語");
+ },
+ );
+});
diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/PendingReviewCard.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/PendingReviewCard.tsx
index 7a45b68615..0c39435db2 100644
--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/PendingReviewCard.tsx
+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/PendingReviewCard.tsx
@@ -3,6 +3,7 @@ import { Text } from "@/components/atoms/Text/Text";
import { Input } from "@/components/atoms/Input/Input";
import { Switch } from "@/components/atoms/Switch/Switch";
import { useEffect, useState } from "react";
+import { JsonDataInput } from "./components/JsonDataInput/JsonDataInput";
import { ReviewInputFields } from "./components/ReviewInputFields/ReviewInputFields";
import { reviewFields } from "./components/ReviewInputFields/helpers";
import { useReviewBlockSchema } from "./components/ReviewInputFields/useReviewBlockSchema";
@@ -113,22 +114,13 @@ export function PendingReviewCard({
);
} else {
return (
- <Input
- id="data-json"
- label="Value"
- hideLabel
- size="small"
- type="textarea"
- rows={6}
- value={JSON.stringify(data, null, 2)}
- onChange={(e) => {
- try {
- const parsed = JSON.parse(e.target.value);
- handleDataChange(parsed);
- } catch {}
- }}
- placeholder="Edit JSON data"
- className="font-mono text-sm"
+ <JsonDataInput
+ value={data}
+ initialText={externalDataValue}
+ onChange={(value) => handleDataChange(value as ReviewPayload)}
+ onInvalidDraft={(text) =>
+ onReviewDataChange(review.node_exec_id, text)
+ }
/>
);
}
diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/__tests__/PendingReviewCard.test.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/__tests__/PendingReviewCard.test.tsx
index b407c3c40f..000ce7ffe3 100644
--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/__tests__/PendingReviewCard.test.tsx
+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/__tests__/PendingReviewCard.test.tsx
@@ -4,8 +4,11 @@ import { expect, test, vi } from "vitest";
import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";
import { server } from "@/mocks/mock-server";
import { render, screen } from "@/tests/integrations/test-utils";
+import { expectTypingKept } from "@/tests/integrations/typing";
import { PendingReviewCard } from "../PendingReviewCard";
+type ReviewPayload = PendingHumanReviewModel["payload"];
+
function makeReview(
overrides: Partial<PendingHumanReviewModel> = {},
): PendingHumanReviewModel {
@@ -267,3 +270,65 @@ test("uses the block's input schema and never shows the credential id", async ()
expect(screen.queryByDisplayValue("s3cr3t")).toBeNull();
expect(screen.queryByText("SendEmailBlock")).toBeNull();
});
+
+// A list payload is edited as raw JSON. Every half-typed edit is invalid JSON,
+// and the field used to drop it and put the old text back, which also broke
+// IME input and threw the caret to the end.
+test("keeps half-typed JSON in a list payload and reports it once it parses", async () => {
+ const onReviewDataChange = vi.fn();
+ render(
+ <PendingReviewCard
+ review={makeReview({ payload: [1, 2] as unknown as ReviewPayload })}
+ onReviewDataChange={onReviewDataChange}
+ />,
+ );
+
+ const field = screen.getByPlaceholderText(
+ "Edit JSON data",
+ ) as HTMLTextAreaElement;
+ await expectTypingKept(field, ", 3", field.value.indexOf("2") + 1);
+
+ expect(onReviewDataChange).toHaveBeenLastCalledWith(
+ "ne-1",
+ JSON.stringify([1, 2, 3], null, 2),
+ );
+});
+
+test("an emptied JSON draft shows a value that then arrives from outside", () => {
+ const review = makeReview({ payload: [1, 2] as unknown as ReviewPayload });
+ const { rerender } = render(
+ <PendingReviewCard review={review} onReviewDataChange={() => {}} />,
+ );
+ const field = screen.getByPlaceholderText(
+ "Edit JSON data",
+ ) as HTMLTextAreaElement;
+
+ fireEvent.change(field, { target: { value: "" } });
+ rerender(
+ <PendingReviewCard
+ review={review}
+ onReviewDataChange={() => {}}
+ externalDataValue="null"
+ />,
+ );
+
+ expect(field.value).toBe("null");
+});
+
+// A card mounted again (its group collapsed and expanded) must show the draft
+// the list still holds, or Approve fails over text the reviewer can't see.
+test("a JSON draft that doesn't parse is shown again when the card remounts", () => {
+ const draft = "[\n 1,\n]";
+ render(
+ <PendingReviewCard
+ review={makeReview({ payload: [1, 2] as unknown as ReviewPayload })}
+ onReviewDataChange={() => {}}
+ externalDataValue={draft}
+ />,
+ );
+
+ expect(
+ (screen.getByPlaceholderText("Edit JSON data") as HTMLTextAreaElement)
+ .value,
+ ).toBe(draft);
+});
diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/JsonDataInput/JsonDataInput.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/JsonDataInput/JsonDataInput.tsx
new file mode 100644
index 0000000000..bf2485eb25
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewCard/components/JsonDataInput/JsonDataInput.tsx
@@ -0,0 +1,67 @@
+import { Input } from "@/components/atoms/Input/Input";
+import { isJsonTextFor } from "@/lib/json-text";
+import { useId, useState } from "react";
+
+interface Props {
+ /** Compared by reference to spot an outside change, so keep it stable
+ * while it is unchanged; an equal copy on every render would replace a
+ * draft that doesn't parse yet. */
+ value: unknown;
+ /** Text to start from instead of `value`: a draft kept from before the
+ * card remounted, which may not parse. */
+ initialText?: string;
+ onChange: (value: unknown) => void;
+ /** The draft no longer parses. Its text goes up as is so approval can be
+ * blocked: the last valid value must not be sent while the screen shows
+ * something else. */
+ onInvalidDraft: (text: string) => void;
+}
+
+/** The payload as editable JSON. The text is the user's draft: an edit that
+ * doesn't parse yet (every half-typed one) stays on screen and is reported
+ * once it does. Rebuilding the text from the value would drop those edits,
+ * and rewriting it under the user throws the caret to the end and cancels
+ * an IME composition. */
+export function JsonDataInput({
+ value,
+ initialText,
+ onChange,
+ onInvalidDraft,
+}: Props) {
+ const id = useId();
+ const [text, setText] = useState(() => initialText ?? toJsonText(value));
+ const [shownValue, setShownValue] = useState(value);
+
+ if (value !== shownValue) {
+ setShownValue(value);
+ if (!text.trim() || !isJsonTextFor(text, value)) setText(toJsonText(value));
+ }
+
+ function handleChange(next: string) {
+ setText(next);
+ try {
+ onChange(JSON.parse(next));
+ } catch {
+ onInvalidDraft(next);
+ }
+ }
+
+ return (
+ <Input
+ id={id}
+ label="Value"
+ hideLabel
+ size="small"
+ type="textarea"
+ rows={6}
+ value={text}
+ onChange={(e) => handleChange(e.target.value)}
+ placeholder="Edit JSON data"
+ className="font-mono text-sm"
+ />
+ );
+}
+
+function toJsonText(value: unknown) {
+ return JSON.stringify(value, null, 2);
+}
diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx
index b8deff7b80..c6d1fb80d0 100644
--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx
+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx
@@ -132,17 +132,24 @@ export function PendingReviewsList({
let parsedData: any = undefined;
if (!autoApproveThisNode) {
- if (review.editable && reviewData) {
+ // An emptied draft is "" here and must fail the parse below, not
+ // fall back to the original payload the reviewer just cleared.
+ if (review.editable && reviewData !== undefined) {
try {
parsedData = JSON.parse(reviewData);
} catch (error) {
- toast({
- title: "Invalid JSON",
- description: `Please fix the JSON format in review for node ${review.node_exec_id}: ${error instanceof Error ? error.message : "Invalid syntax"}`,
- variant: "destructive",
- });
- setPendingAction(null);
- return;
+ // A rejection sends nothing the reviewer edited, so a broken
+ // draft only has to block an approval.
+ if (approved) {
+ toast({
+ title: "Invalid JSON",
+ description: `Please fix the JSON format in review for node ${review.node_exec_id}: ${error instanceof Error ? error.message : "Invalid syntax"}`,
+ variant: "destructive",
+ });
+ setPendingAction(null);
+ return;
+ }
+ parsedData = review.payload;
}
} else {
parsedData = review.payload;
diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/__tests__/PendingReviewsList.test.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/__tests__/PendingReviewsList.test.tsx
index 833008cff3..4aad7171cb 100644
--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/__tests__/PendingReviewsList.test.tsx
+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/__tests__/PendingReviewsList.test.tsx
@@ -1,5 +1,6 @@
+import { fireEvent } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
-import { expect, test } from "vitest";
+import { expect, test, vi } from "vitest";
import { getPostV2ProcessReviewActionMockHandler200 } from "@/app/api/__generated__/endpoints/executions/executions.msw";
import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";
import type { ReviewRequest } from "@/app/api/__generated__/models/reviewRequest";
@@ -7,6 +8,12 @@ import { server } from "@/mocks/mock-server";
import { render, screen, waitFor } from "@/tests/integrations/test-utils";
import { PendingReviewsList } from "../PendingReviewsList";
+const { toastSpy } = vi.hoisted(() => ({ toastSpy: vi.fn() }));
+vi.mock("@/components/molecules/Toast/use-toast", () => ({
+ toast: toastSpy,
+ useToast: () => ({ toast: toastSpy, dismiss: vi.fn() }),
+}));
+
function makeReview(
overrides: Partial<PendingHumanReviewModel> = {},
): PendingHumanReviewModel {
@@ -188,3 +195,65 @@ test("an AutoPilot action's card neither calls it a workflow nor offers an edit"
expect(screen.queryByText(/edit it if needed/)).toBeNull();
expect(screen.queryByText(/Node #/)).toBeNull();
});
+
+// The JSON editor keeps a half-typed draft on screen. Approving must not send
+// the last valid JSON in its place: with a trailing comma left behind,
+// "[email protected]" would still go out while the reviewer sees it deleted.
+test.each([
+ ["a draft that doesn't parse", '[\n "[email protected]",\n]'],
+ ["an emptied draft", ""],
+])(
+ "approving %s is blocked instead of sending stale data",
+ async (_, draft) => {
+ const captured = captureReviewAction();
+ render(
+ <PendingReviewsList
+ reviews={[
+ makeReview({
+ payload: [
+ ] as unknown as PendingHumanReviewModel["payload"],
+ }),
+ ]}
+ />,
+ );
+
+ fireEvent.change(screen.getByPlaceholderText("Edit JSON data"), {
+ target: { value: draft },
+ });
+ await userEvent.click(screen.getByRole("button", { name: "Approve" }));
+
+ await waitFor(() =>
+ expect(toastSpy).toHaveBeenCalledWith(
+ expect.objectContaining({ title: "Invalid JSON" }),
+ ),
+ );
+ expect(captured.body).toBeUndefined();
+ },
+);
+
+test("rejecting goes through while the JSON draft doesn't parse", async () => {
+ const captured = captureReviewAction();
+ const payload = ["[email protected]", "[email protected]"];
+ render(
+ <PendingReviewsList
+ reviews={[
+ makeReview({
+ payload: payload as unknown as PendingHumanReviewModel["payload"],
+ }),
+ ]}
+ />,
+ );
+
+ fireEvent.change(screen.getByPlaceholderText("Edit JSON data"), {
+ target: { value: '[\n "[email protected]",\n]' },
+ });
+ await userEvent.click(screen.getByRole("button", { name: "Reject" }));
+
+ await waitFor(() => expect(captured.body).toBeDefined());
+ expect(captured.body?.reviews[0]).toMatchObject({
+ approved: false,
+ reviewed_data: payload,
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/JsonTextField.test.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/JsonTextField.test.tsx
new file mode 100644
index 0000000000..dc590a9d3b
--- /dev/null
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/JsonTextField.test.tsx
@@ -0,0 +1,92 @@
+import type { IChangeEvent } from "@rjsf/core";
+import type { RJSFSchema } from "@rjsf/utils";
+import { fireEvent, screen, waitFor } from "@testing-library/react";
+import { useState } from "react";
+import { describe, expect, it } from "vitest";
+
+import { BlockUIType } from "@/app/(platform)/build/components/types";
+import { render } from "@/tests/integrations/test-utils";
+import { expectTypingKept } from "@/tests/integrations/typing";
+
+import { FormRenderer } from "../FormRenderer";
+
+interface RowsData {
+ rows: Record<string, unknown>[];
+}
+
+// Free-form dicts inside an array are edited as raw JSON.
+const schema: RJSFSchema = {
+ type: "object",
+ properties: {
+ rows: {
+ title: "Rows",
+ type: "array",
+ items: { type: "object", additionalProperties: true },
+ },
+ },
+};
+
+function RowsForm({ rows }: { rows: Record<string, unknown>[] }) {
+ const [data, setData] = useState<RowsData>({ rows });
+
+ function handleChange(event: IChangeEvent<RowsData>) {
+ if (event.formData) setData(event.formData);
+ }
+
+ return (
+ <>
+ <FormRenderer
+ jsonSchema={schema}
+ handleChange={handleChange}
+ uiSchema={{}}
+ initialValues={data}
+ formContext={{
+ nodeId: "json-node",
+ uiType: BlockUIType.STANDARD,
+ showHandles: false,
+ size: "small",
+ }}
+ />
+ <output aria-label="Stored rows">{JSON.stringify(data.rows)}</output>
+ <button type="button" onClick={() => setData({ rows: [{ b: 2 }] })}>
+ Load other rows
+ </button>
+ </>
+ );
+}
+
+function getJsonField() {
+ return screen.getByPlaceholderText('{"key": "value"}') as HTMLTextAreaElement;
+}
+
+describe("JsonTextField", () => {
+ it("keeps the JSON as typed instead of reformatting it", async () => {
+ render(<RowsForm rows={[{}]} />);
+
+ await expectTypingKept(getJsonField(), '"a":1', 1);
+
+ expect(screen.getByLabelText("Stored rows").textContent).toBe('[{"a":1}]');
+ });
+
+ it("shows data that changes from outside the field", async () => {
+ render(<RowsForm rows={[{ a: 1 }]} />);
+ expect(getJsonField().value).toBe('{\n "a": 1\n}');
+
+ fireEvent.click(screen.getByRole("button", { name: "Load other rows" }));
+
+ await waitFor(() => expect(getJsonField().value).toBe('{\n "b": 2\n}'));
+ });
+
+ it("keeps typing next to a number stored as a rounded big integer", async () => {
+ render(<RowsForm rows={[{ id: 12345678901234567000 }]} />);
+ const field = getJsonField();
+
+ await expectTypingKept(field, ', "a": 1', field.value.indexOf("\n}"));
+ });
+
+ it("keeps a negative decimal while it is typed", async () => {
+ render(<RowsForm rows={[{}]} />);
+
+ await expectTypingKept(getJsonField(), '"a":-0.5', 1);
+ });
+});
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/JsonTextField/useJsonTextField.ts b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/JsonTextField/useJsonTextField.ts
index 85dc69cfd3..3c8d451ce0 100644
--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/JsonTextField/useJsonTextField.ts
+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/custom/JsonTextField/useJsonTextField.ts
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from "react";
import { FieldProps } from "@rjsf/utils";
+import { isJsonTextFor } from "@/lib/json-text";
import { stringifyFormData, parseJsonValue, isValidJson } from "./helpers";
type FieldOnChange = FieldProps["onChange"];
@@ -35,10 +36,13 @@ export function useJsonTextField({
const [isModalOpen, setIsModalOpen] = useState(false);
const [hasError, setHasError] = useState(false);
- // Update text value when formData changes externally
+ // Update text value when formData changes externally. The user's own edits
+ // come back here as formData too; their text stays as typed rather than
+ // being swapped for the reformatted copy.
useEffect(() => {
- const newValue = stringifyFormData(formData);
- setTextValue(newValue);
+ setTextValue((current) =>
+ isJsonTextFor(current, formData) ? current : stringifyFormData(formData),
+ );
setHasError(false);
}, [formData]);
diff --git a/autogpt_platform/frontend/src/lib/json-text.test.ts b/autogpt_platform/frontend/src/lib/json-text.test.ts
new file mode 100644
index 0000000000..af79b2dddc
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/json-text.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+import { isJsonTextFor } from "./json-text";
+
+describe("isJsonTextFor", () => {
+ it("matches the same value however it is formatted", () => {
+ expect(isJsonTextFor('{"a":1}', { a: 1 })).toBe(true);
+ expect(isJsonTextFor('{\n "a": 1\n}', { a: 1 })).toBe(true);
+ expect(isJsonTextFor("[1, 2]", [1, 2])).toBe(true);
+ });
+
+ it("does not match a different value", () => {
+ expect(isJsonTextFor('{"a":1}', { a: 2 })).toBe(false);
+ expect(isJsonTextFor("[1, 2]", [2, 1])).toBe(false);
+ });
+
+ it("does not match text that is not JSON yet", () => {
+ expect(isJsonTextFor('{"a":', { a: 1 })).toBe(false);
+ });
+
+ it("matches empty text only to no value", () => {
+ expect(isJsonTextFor(" ", undefined)).toBe(true);
+ expect(isJsonTextFor("", null)).toBe(true);
+ expect(isJsonTextFor("", {})).toBe(false);
+ });
+
+ // The stored value would be a rounded copy, so the field must show it
+ // rather than keep digits that will not be saved.
+ it("does not match numbers JSON parsing can't hold exactly", () => {
+ const id = "1234567890123456789";
+ expect(
+ isJsonTextFor(
+ `{"channel_id": ${id}}`,
+ JSON.parse(`{"channel_id": ${id}}`),
+ ),
+ ).toBe(false);
+ expect(isJsonTextFor("[1e400]", [Infinity])).toBe(false);
+ });
+
+ it("still matches safe numbers and digits inside strings", () => {
+ expect(
+ isJsonTextFor("[9007199254740991, -2.5e3]", [9007199254740991, -2500]),
+ ).toBe(true);
+ expect(
+ isJsonTextFor('{"id": "1234567890123456789"}', {
+ id: "1234567890123456789",
+ }),
+ ).toBe(true);
+ });
+
+ // Once the field shows the stored (rounded) number, later edits must not be
+ // flagged again, or every keystroke would rewrite the field.
+ it("matches a big number written as it is stored", () => {
+ expect(
+ isJsonTextFor("[12345678901234567000]", [12345678901234567000]),
+ ).toBe(true);
+ expect(isJsonTextFor("[9007199254740992]", [9007199254740992])).toBe(true);
+ });
+
+ // "-0" is on the way to "-0.5" and is stored exactly; it reads back as "0".
+ it("matches negative zero", () => {
+ expect(isJsonTextFor("[-0]", [-0])).toBe(true);
+ });
+});
diff --git a/autogpt_platform/frontend/src/lib/json-text.ts b/autogpt_platform/frontend/src/lib/json-text.ts
new file mode 100644
index 0000000000..8a331ba6bf
--- /dev/null
+++ b/autogpt_platform/frontend/src/lib/json-text.ts
@@ -0,0 +1,37 @@
+/**
+ * True when `text` is JSON for `value`, however it is spaced or indented.
+ * A field that edits JSON as text keeps the user's own text while it still
+ * says the same thing as the stored value. Replacing it with a reformatted
+ * copy rewrites the field under the user, which throws the caret to the end
+ * and cancels an IME composition.
+ *
+ * Key order counts, which is fine for a value parsed from the user's own
+ * text; a value with its keys in another order only costs one reformat.
+ */
+export function isJsonTextFor(text: string, value: unknown): boolean {
+ if (text.trim() === "") return value === undefined || value === null;
+ if (hasInexactNumber(text)) return false;
+ try {
+ return JSON.stringify(JSON.parse(text)) === JSON.stringify(value);
+ } catch {
+ return false;
+ }
+}
+
+const STRING_LITERAL = /"(?:[^"\\]|\\.)*"/g;
+const NUMBER_LITERAL = /-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g;
+
+// A number JSON.parse can only round (an integer that doesn't read back as
+// the same digits, or one too large to hold at all) would be saved as
+// something other than what is on screen. An integer written as it is stored
+// reads back unchanged, so the field stops being rewritten once it shows it.
+function hasInexactNumber(text: string): boolean {
+ const numbers = text.replace(STRING_LITERAL, '""').match(NUMBER_LITERAL);
+ return (numbers ?? []).some((literal) => {
+ const parsed = Number(literal);
+ if (!Number.isFinite(parsed)) return true;
+ // -0 is exact too (it is on the way to "-0.5"), but reads back as "0".
+ if (!/^-?\d+$/.test(literal) || Object.is(parsed, -0)) return false;
+ return String(parsed) !== literal;
+ });
+}
diff --git a/autogpt_platform/frontend/src/tests/integrations/typing.ts b/autogpt_platform/frontend/src/tests/integrations/typing.ts
new file mode 100644
index 0000000000..f0e9e88c3d
--- /dev/null
+++ b/autogpt_platform/frontend/src/tests/integrations/typing.ts
@@ -0,0 +1,42 @@
+import { fireEvent } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { expect } from "vitest";
+
+type TextField = HTMLInputElement | HTMLTextAreaElement;
+
+/**
+ * Types `text` into `field` at offset `at` (the end by default) and fails if
+ * the field's text or caret was rewritten on the way. The keystrokes are
+ * wrapped in composition events for fields that listen for them, but the
+ * test environment can't run a real IME: what catches a broken field is the
+ * text and caret check, since React writing its own value back moves the
+ * caret to the end.
+ *
+ * A field that writes its own value over what was typed (reformatting it,
+ * dropping an edit it can't parse yet, or getting it back one render late)
+ * cancels every Japanese, Chinese or Korean composition and throws the caret
+ * to the end. Use this in the test of any field that transforms or round-trips
+ * its value.
+ */
+export async function expectTypingKept(
+ field: TextField,
+ text: string,
+ at = field.value.length,
+) {
+ const user = userEvent.setup();
+ const expected = field.value.slice(0, at) + text + field.value.slice(at);
+ fireEvent.compositionStart(field);
+ await user.type(field, escapeKeyDescriptors(text), {
+ initialSelectionStart: at,
+ initialSelectionEnd: at,
+ });
+ fireEvent.compositionEnd(field);
+ expect(field.value).toBe(expected);
+ expect(field.selectionStart).toBe(at + text.length);
+}
+
+// user-event reads `{Enter}` and `[KeyA]` as key names; doubled, they type
+// the bracket itself.
+function escapeKeyDescriptors(text: string) {
+ return text.replace(/[{[]/g, "$&$&");
+}