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): preserve numeric enum selections (#13147)
Abhimanyu Yadav2e3750b22761
diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/FormRenderer.test.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/FormRenderer.test.tsxnew file mode 100644index 0000000000..1e280124e4--- /dev/null+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/__tests__/FormRenderer.test.tsx@@ -0,0 +1,187 @@+import { fireEvent, screen, waitFor } from "@testing-library/react";+import { RJSFSchema, WidgetProps } from "@rjsf/utils";+import React from "react";+import { describe, expect, it, vi } from "vitest";++import { BlockUIType } from "@/app/(platform)/build/components/types";+import { render } from "@/tests/integrations/test-utils";++import { FormRenderer } from "../FormRenderer";+import { SelectWidget } from "../base/standard/widgets/SelectInput/SelectWidget";++vi.mock("@/components/atoms/Select/Select", () => ({+ Select: ({+ id,+ value,+ onValueChange,+ options,+ }: {+ id: string;+ value?: string;+ onValueChange?: (value: string) => void;+ options: { value: string; label: string }[];+ }) => (+ <select+ aria-label={id}+ value={value ?? ""}+ onChange={(event) => onValueChange?.(event.target.value)}+ >+ {options.map((option) => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </select>+ ),+}));++let mockMultiSelectValues: string[] = [];+let mockMultiSelectOnChange: (values: string[]) => void = () => undefined;++vi.mock("@/components/__legacy__/ui/multiselect", () => ({+ MultiSelector: ({+ values,+ onValuesChange,+ children,+ }: {+ values: string[];+ onValuesChange: (values: string[]) => void;+ children: React.ReactNode;+ }) => (+ <div>+ {(() => {+ mockMultiSelectValues = values;+ mockMultiSelectOnChange = onValuesChange;+ return children;+ })()}+ </div>+ ),+ MultiSelectorTrigger: ({ children }: { children: React.ReactNode }) => {+ return (+ <div>+ <div data-testid="selected-values">+ {mockMultiSelectValues.join(",")}+ </div>+ {children}+ </div>+ );+ },+ MultiSelectorInput: () => <input aria-label="multi-select-input" />,+ MultiSelectorContent: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ MultiSelectorList: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+ MultiSelectorItem: ({+ value,+ children,+ }: {+ value: string;+ children: React.ReactNode;+ }) => {+ return (+ <button+ type="button"+ onClick={() =>+ mockMultiSelectOnChange([...mockMultiSelectValues, value])+ }+ >+ {children}+ </button>+ );+ },+}));++describe("FormRenderer", () => {+ it("round-trips numeric enum values for array item selects", async () => {+ const handleChange = vi.fn();+ const jsonSchema: RJSFSchema = {+ type: "object",+ properties: {+ reminder_minutes: {+ title: "Reminder Minutes",+ type: "array",+ items: {+ title: "ReminderPreset",+ type: "integer",+ enum: [10, 30, 60, 1440],+ },+ },+ },+ };++ render(+ <FormRenderer+ jsonSchema={jsonSchema}+ handleChange={handleChange}+ uiSchema={{}}+ initialValues={{ reminder_minutes: [] }}+ formContext={{+ nodeId: "node-1",+ uiType: BlockUIType.STANDARD,+ showHandles: false,+ size: "small",+ }}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: /add item/i }));++ const select = screen.getByRole("combobox") as HTMLSelectElement;+ expect(Array.from(select.options).map((option) => option.text)).toEqual([+ "10",+ "30",+ "60",+ "1440",+ ]);++ fireEvent.change(select, { target: { value: "2" } });++ await waitFor(() => {+ const lastCall = handleChange.mock.calls.at(-1)?.[0];+ expect(lastCall.formData.reminder_minutes).toEqual([60]);+ });+ });++ it("round-trips numeric enum values for multiselects without exposing indexes", () => {+ const onChange = vi.fn();++ render(+ <SelectWidget+ id="reminder-minutes"+ name="reminder-minutes"+ label="Reminder Minutes"+ schema={{+ type: "array",+ items: {+ type: "integer",+ enum: [10, 30, 60, 1440],+ },+ }}+ options={{+ enumOptions: [+ { value: 10, label: "10" },+ { value: 30, label: "30" },+ { value: 60, label: "60" },+ { value: 1440, label: "1440" },+ ],+ }}+ value={[10, 60]}+ onChange={onChange}+ onBlur={vi.fn()}+ onFocus={vi.fn()}+ disabled={false}+ readonly={false}+ formContext={{ size: "small" }}+ registry={{} as WidgetProps["registry"]}+ />,+ );++ expect(screen.getByTestId("selected-values").textContent).toBe("10,60");++ fireEvent.click(screen.getByRole("button", { name: "30" }));++ expect(onChange).toHaveBeenCalledWith([10, 60, 30]);+ });+});diff --git a/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/SelectWidget.tsx b/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/SelectWidget.tsxindex 894004db40..c4f04c0ed2 100644--- a/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/SelectWidget.tsx+++ b/autogpt_platform/frontend/src/components/renderers/InputRenderer/base/standard/widgets/SelectInput/SelectWidget.tsx@@ -1,4 +1,8 @@-import { WidgetProps } from "@rjsf/utils";+import {+ enumOptionsIndexForValue,+ enumOptionsValueForIndex,+ WidgetProps,+} from "@rjsf/utils";import {InputType,mapJsonSchemaTypeToInputType,@@ -13,7 +17,7 @@ import {MultiSelectorTrigger,} from "@/components/__legacy__/ui/multiselect";-export const SelectWidget = (props: WidgetProps) => {+export function SelectWidget(props: WidgetProps) {const {options,value,@@ -27,16 +31,49 @@ export const SelectWidget = (props: WidgetProps) => {const enumOptions = options.enumOptions || [];const type = mapJsonSchemaTypeToInputType(props.schema);const { size = "small" } = formContext || {};+ const selectedIndexes = enumOptionsIndexForValue(+ value,+ enumOptions,+ type === InputType.MULTI_SELECT,+ );// Determine select size based on contextconst selectSize = size === "large" ? "medium" : "small";const renderInput = () => {if (type === InputType.MULTI_SELECT) {+ const enumOptionIndexesByLabel = new Map<string, string>();+ enumOptions.forEach((option, index) => {+ if (!enumOptionIndexesByLabel.has(option.label)) {+ enumOptionIndexesByLabel.set(option.label, String(index));+ }+ });++ const selectedValues: string[] = [];+ if (Array.isArray(selectedIndexes)) {+ for (const index of selectedIndexes) {+ const label = enumOptions[Number(index)]?.label;+ if (typeof label === "string") {+ selectedValues.push(label);+ }+ }+ }+return (<MultiSelector- values={Array.isArray(value) ? value : []}- onValuesChange={onChange}+ values={selectedValues}+ onValuesChange={(newValues) => {+ const selectedOptionIndexes: string[] = [];+ for (const label of newValues) {+ const optionIndex = enumOptionIndexesByLabel.get(label);+ if (optionIndex !== undefined) {+ selectedOptionIndexes.push(optionIndex);+ }+ }+ onChange(+ enumOptionsValueForIndex(selectedOptionIndexes, enumOptions),+ );+ }}className="w-full"><MultiSelectorTrigger>@@ -44,8 +81,11 @@ export const SelectWidget = (props: WidgetProps) => {</MultiSelectorTrigger><MultiSelectorContent><MultiSelectorList>- {enumOptions?.map((option: any) => (- <MultiSelectorItem key={option.value} value={option.value}>+ {enumOptions.map((option) => (+ <MultiSelectorItem+ key={`${String(option.value)}-${option.label}`}+ value={option.label}+ >{option.label}</MultiSelectorItem>))}@@ -54,6 +94,9 @@ export const SelectWidget = (props: WidgetProps) => {</MultiSelector>);}+ const selectedValue =+ typeof selectedIndexes === "string" ? selectedIndexes : "";+return (<Selectlabel=""@@ -61,14 +104,16 @@ export const SelectWidget = (props: WidgetProps) => {hideLabel={true}disabled={disabled || readonly}size={selectSize as any}- value={value ?? ""}- onValueChange={onChange}- options={- enumOptions?.map((option: any) => ({- value: option.value,- label: option.label,- })) || []+ value={selectedValue}+ onValueChange={(newValue) =>+ onChange(+ enumOptionsValueForIndex(newValue, enumOptions, options.emptyValue),+ )}+ options={enumOptions.map((option, index) => ({+ value: String(index),+ label: option.label,+ }))}wrapperClassName="!mb-0 "className={className}/>@@ -76,4 +121,4 @@ export const SelectWidget = (props: WidgetProps) => {};return renderInput();-};+}