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): stop optional select inputs crashing review cards and run forms (#15434)

Nicholas Tindle5c7f2483d330
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/optional-inputs.test.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/optional-inputs.test.tsx
new file mode 100644
index 0000000000..7a935cb8c7
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/__tests__/optional-inputs.test.tsx
@@ -0,0 +1,150 @@
+import {
+ getGetV1ListGraphExecutionsMockHandler,
+ getPostV1ExecuteGraphAgentMockHandler,
+ getPostV1ExecuteGraphAgentResponseMock,
+} from "@/app/api/__generated__/endpoints/graphs/graphs.msw";
+import {
+ getGetV2GetLibraryAgentMockHandler,
+ getGetV2GetLibraryAgentResponseMock,
+} from "@/app/api/__generated__/endpoints/library/library.msw";
+import { getGetV2ListPresetsMockHandler } from "@/app/api/__generated__/endpoints/presets/presets.msw";
+import { getGetV1ListExecutionSchedulesForAGraphMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";
+import { server } from "@/mocks/mock-server";
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@/tests/integrations/test-utils";
+import { NuqsTestingAdapter } from "nuqs/adapters/testing";
+import { expect, test, vi } from "vitest";
+import { NewAgentLibraryView } from "../components/NewAgentLibraryView/NewAgentLibraryView";
+
+vi.mock("next/navigation", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("next/navigation")>()),
+ useParams: () => ({ id: "library-agent" }),
+ usePathname: () => "/library/agents/library-agent",
+ useRouter: () => ({ push: vi.fn(), replace: vi.fn(), refresh: vi.fn() }),
+ useSearchParams: () => new URLSearchParams(),
+}));
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({
+ user: { id: "user-1", email: "[email protected]" },
+ isLoggedIn: true,
+ isUserLoading: false,
+ }),
+}));
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importOriginal) => ({
+ ...(await importOriginal<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >()),
+ useGetFlag: () => false,
+ useFlagStatus: () => ({ enabled: false, ready: true }),
+}));
+
+const EMPTY_PAGE = {
+ total_items: 0,
+ total_pages: 0,
+ current_page: 1,
+ page_size: 20,
+};
+
+// Pydantic writes an Optional[...] input as anyOf [the type, null], and the
+// options and item type live on that anyOf member, not on the input itself.
+const OPTIONAL_INPUTS = {
+ topic: {
+ title: "Topic",
+ anyOf: [{ type: "string", enum: ["news", "sports"] }, { type: "null" }],
+ },
+ // AgentTableInputBlock.Input.generate_schema() for column_headers
+ // ["player", "points"]: the columns are on the field, beside an anyOf member
+ // that has none.
+ scores: {
+ title: "Scores",
+ anyOf: [
+ { type: "array", items: { type: "object", additionalProperties: true } },
+ { type: "null" },
+ ],
+ default: null,
+ type: "array",
+ format: "table",
+ items: {
+ type: "object",
+ properties: { player: { type: "string" }, points: { type: "string" } },
+ },
+ },
+ tags: {
+ title: "Tags",
+ anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }],
+ },
+ limit: { title: "Limit", anyOf: [{ type: "integer" }, { type: "null" }] },
+};
+
+test("the run form offers each optional input and sends what the user picked", async () => {
+ const runInputs = vi.fn();
+ server.use(
+ getGetV2GetLibraryAgentMockHandler(
+ getGetV2GetLibraryAgentResponseMock({
+ id: "library-agent",
+ graph_id: "graph-1",
+ graph_version: 1,
+ name: "Digest agent",
+ input_schema: { type: "object", properties: OPTIONAL_INPUTS },
+ credentials_input_schema: { type: "object", properties: {} },
+ has_external_trigger: false,
+ trigger_setup_info: null,
+ has_sensitive_action: false,
+ has_human_in_the_loop: false,
+ recommended_schedule_cron: null,
+ }),
+ ),
+ getGetV1ListGraphExecutionsMockHandler({
+ executions: [],
+ pagination: EMPTY_PAGE,
+ }),
+ getGetV1ListExecutionSchedulesForAGraphMockHandler([]),
+ getGetV2ListPresetsMockHandler({
+ presets: [],
+ pagination: { ...EMPTY_PAGE, page_size: 100 },
+ }),
+ getPostV1ExecuteGraphAgentMockHandler(async ({ request }) => {
+ runInputs(((await request.json()) as { inputs: unknown }).inputs);
+ return getPostV1ExecuteGraphAgentResponseMock({ id: "new-run" });
+ }),
+ );
+
+ render(
+ <NuqsTestingAdapter hasMemory>
+ <NewAgentLibraryView />
+ </NuqsTestingAdapter>,
+ );
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Setup your task" }),
+ );
+
+ fireEvent.click(await screen.findByRole("combobox", { name: "Topic" }));
+ fireEvent.click(await screen.findByRole("option", { name: "sports" }));
+ // The table offers the agent's own columns, not the "Column 1" placeholders,
+ // so the rows reach the agent keyed the way it reads them.
+ expect(screen.getByRole("columnheader", { name: "player" })).toBeDefined();
+ expect(screen.getByRole("columnheader", { name: "points" })).toBeDefined();
+ fireEvent.click(screen.getByRole("button", { name: "Add Row" }));
+ fireEvent.change(screen.getByPlaceholderText("Enter player"), {
+ target: { value: "Ada" },
+ });
+ expect(screen.getByText("Tags")).toBeDefined();
+ expect(screen.getByText("Limit")).toBeDefined();
+
+ fireEvent.click(screen.getByRole("button", { name: "Start Task" }));
+
+ await waitFor(() =>
+ expect(runInputs).toHaveBeenCalledWith(
+ expect.objectContaining({
+ topic: "sports",
+ scores: [{ player: "Ada", points: "" }],
+ }),
+ ),
+ );
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/RunAgentInputs.tsx b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/RunAgentInputs.tsx
index 46f79eea39..aa72d987ca 100644
--- a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/RunAgentInputs.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/RunAgentInputs.tsx
@@ -16,9 +16,11 @@ import {
BlockIOSubSchema,
BlockIOTableSubSchema,
DataType,
- determineDataType,
+ GoogleDrivePickerSchema,
+ resolveDataType,
TableRow,
} from "@/lib/autogpt-server-api/types";
+import { getSelectOptions } from "./helpers";
import { useRunAgentInputs } from "./useRunAgentInputs";
import { Cancel01Icon, PlusSignIcon } from "@hugeicons/core-free-icons";
import { Icon } from "@/components/atoms/Icon/Icon";
@@ -52,7 +54,15 @@ export function RunAgentInputs({
}: Props & React.HTMLAttributes<HTMLElement>) {
const { handleUploadFile, uploadProgress } = useRunAgentInputs();
- const dataType = determineDataType(schema);
+ // Options and keys come from the schema the type was judged by: an optional
+ // field keeps them on its anyOf member, not on the field itself.
+ const { type, schema: valueSchema } = resolveDataType(schema);
+ const selectOptions = getSelectOptions(valueSchema);
+ // A select with nothing to pick from, like an empty enum, takes text.
+ const dataType =
+ type === DataType.SELECT && selectOptions.length === 0
+ ? DataType.SHORT_TEXT
+ : type;
const baseId = String(schema.title ?? "input")
.replace(/\s+/g, "-")
@@ -100,9 +110,9 @@ export function RunAgentInputs({
break;
case DataType.GOOGLE_DRIVE_PICKER: {
- const pickerSchema = schema as any;
- const config: import("@/lib/autogpt-server-api/types").GoogleDrivePickerConfig =
- pickerSchema.google_drive_picker_config || {};
+ const config =
+ (valueSchema as GoogleDrivePickerSchema).google_drive_picker_config ??
+ {};
innerInputElement = (
<GoogleDrivePickerInput
@@ -208,29 +218,24 @@ export function RunAgentInputs({
break;
case DataType.SELECT:
- if (
- "enum" in schema &&
- Array.isArray(schema.enum) &&
- schema.enum.length > 0
- ) {
- innerInputElement = (
- <DSSelect
- id={`${baseId}-select`}
- label={schema.title ?? placeholder ?? "Select"}
- hideLabel
- value={value ?? ""}
- onValueChange={(val: string) => onChange(val)}
- placeholder={placeholder || "Select an option"}
- options={schema.enum
- .filter((opt) => opt)
- .map((opt) => ({ value: opt, label: String(opt) }))}
- />
- );
- break;
- }
+ innerInputElement = (
+ <DSSelect
+ id={`${baseId}-select`}
+ label={schema.title ?? placeholder ?? "Select"}
+ hideLabel
+ value={value ?? ""}
+ onValueChange={(val: string) => onChange(val)}
+ placeholder={placeholder || "Select an option"}
+ options={selectOptions.map((opt) => ({
+ value: opt,
+ label: String(opt),
+ }))}
+ />
+ );
+ break;
case DataType.MULTI_SELECT: {
- const _schema = schema as BlockIOObjectSubSchema;
+ const _schema = valueSchema as BlockIOObjectSubSchema;
const allKeys = Object.keys(_schema.properties);
const selectedValues = Object.entries(value || {})
.filter(([_, v]) => v)
@@ -259,7 +264,7 @@ export function RunAgentInputs({
case DataType.TABLE: {
// Render a simple table UI for the run modal
- const tableSchema = schema as BlockIOTableSubSchema;
+ const tableSchema = valueSchema as BlockIOTableSubSchema;
const headers = tableSchema.items?.properties
? Object.keys(tableSchema.items.properties)
: ["Column 1", "Column 2", "Column 3"];
diff --git a/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/helpers.ts
new file mode 100644
index 0000000000..22ad948708
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/library/agents/[id]/components/NewAgentLibraryView/components/modals/RunAgentInputs/helpers.ts
@@ -0,0 +1,6 @@
+import type { BlockIOSubSchema } from "@/lib/autogpt-server-api/types";
+
+export function getSelectOptions(schema: BlockIOSubSchema) {
+ if (!("enum" in schema) || !Array.isArray(schema.enum)) return [];
+ return schema.enum.filter((option) => option);
+}
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 0f3e1c3b1b..b407c3c40f 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
@@ -94,6 +94,120 @@ test("a non-editable payload is displayed in full", () => {
expect(screen.queryByRole("textbox")).toBeNull();
});
+function serveBlockSchema(properties: Record<string, unknown>) {
+ server.use(
+ http.get("*/api/builder/blocks/batch", () =>
+ HttpResponse.json([
+ {
+ id: "block-1",
+ name: "NotifyBlock",
+ inputSchema: { type: "object", properties },
+ },
+ ]),
+ ),
+ );
+}
+
+// An optional field's options live on its anyOf member, not on the field. The
+// card used to look for them on the field, find none, and crash the chat on
+// /home and /copilot (BUILDER-93V).
+test("offers an optional choice from the block's schema as a select", async () => {
+ const onReviewDataChange = vi.fn();
+ serveBlockSchema({
+ priority: {
+ title: "Priority",
+ anyOf: [{ type: "string", enum: ["low", "high"] }, { type: "null" }],
+ },
+ });
+
+ render(
+ <PendingReviewCard
+ review={makeReview({
+ block_id: "block-1",
+ payload: { priority: "high" },
+ })}
+ onReviewDataChange={onReviewDataChange}
+ />,
+ );
+
+ const priority = await screen.findByRole("combobox", { name: "Priority" });
+ expect(priority.textContent).toBe("high");
+
+ fireEvent.click(priority);
+ fireEvent.click(await screen.findByRole("option", { name: "low" }));
+
+ const [, data] = onReviewDataChange.mock.lastCall ?? [];
+ expect(JSON.parse(data)).toEqual({ priority: "low" });
+});
+
+// The same mismatch, in the other shapes a block's schema takes: an enum
+// wrapped in allOf and an enum with no members crashed the card too.
+test("gives wrapped, empty and untyped inputs a control instead of crashing", async () => {
+ vi.spyOn(console, "warn").mockImplementation(() => undefined);
+ serveBlockSchema({
+ model: {
+ title: "Model",
+ allOf: [{ type: "string", enum: ["gpt", "claude"] }],
+ },
+ tone: { title: "Tone", type: "string", enum: ["formal", "casual"] },
+ region: { title: "Region", enum: [] },
+ notes: { title: "Notes" },
+ });
+
+ render(
+ <PendingReviewCard
+ review={makeReview({
+ block_id: "block-1",
+ payload: {
+ model: "claude",
+ tone: "casual",
+ region: "eu",
+ notes: "keep it short",
+ },
+ })}
+ onReviewDataChange={() => {}}
+ />,
+ );
+
+ expect(
+ (await screen.findByRole("combobox", { name: "Model" })).textContent,
+ ).toBe("claude");
+ expect(screen.getByRole("combobox", { name: "Tone" }).textContent).toBe(
+ "casual",
+ );
+ expect(screen.getByDisplayValue("eu")).toBeDefined();
+ expect(screen.getByDisplayValue("keep it short")).toBeDefined();
+ vi.mocked(console.warn).mockRestore();
+});
+
+test("offers an optional set of switches the payload left empty", async () => {
+ serveBlockSchema({
+ channels: {
+ title: "Channels",
+ anyOf: [
+ {
+ type: "object",
+ properties: {
+ email: { type: "boolean", title: "Email" },
+ sms: { type: "boolean", title: "SMS" },
+ },
+ },
+ { type: "null" },
+ ],
+ },
+ });
+
+ render(
+ <PendingReviewCard
+ review={makeReview({ block_id: "block-1", payload: { channels: null } })}
+ onReviewDataChange={() => {}}
+ />,
+ );
+
+ expect(await screen.findByText("Email")).toBeDefined();
+ expect(screen.getByText("SMS")).toBeDefined();
+});
+
test("uses the block's input schema and never shows the credential id", async () => {
server.use(
http.get("*/api/builder/blocks/batch", () =>
diff --git a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
index 6e24c9f249..904526d790 100644
--- a/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
+++ b/autogpt_platform/frontend/src/lib/autogpt-server-api/types.ts
@@ -1045,7 +1045,7 @@ function _handleSingleTypeSchema(subSchema: BlockIOSubSchema): DataType {
if (subSchema.type === "object") {
if (
("additionalProperties" in subSchema && subSchema.additionalProperties) ||
- !("properties" in subSchema)
+ !("properties" in subSchema && subSchema.properties)
) {
return DataType.KEY_VALUE; // if additionalProperties / no properties => key-value
}
@@ -1062,6 +1062,20 @@ function _handleSingleTypeSchema(subSchema: BlockIOSubSchema): DataType {
}
export function determineDataType(schema: BlockIOSubSchema): DataType {
+ return resolveDataType(schema).type;
+}
+
+/**
+ * The data type a value's schema calls for, and the schema that holds what its
+ * control needs: the non-null member of an optional field's `anyOf`, or the
+ * schema an `allOf` wraps. A select's options and a multi-select's keys live
+ * there, not on the wrapper, so read them from here (BUILDER-93V). A table is
+ * the exception: its columns are on the field itself.
+ */
+export function resolveDataType(schema: BlockIOSubSchema): {
+ type: DataType;
+ schema: BlockIOSubSchema;
+} {
if ("allOf" in schema) {
// If this happens, that is because Pydantic wraps $refs in an allOf if the
// $ref has sibling schema properties (which isn't technically allowed),
@@ -1075,19 +1089,19 @@ export function determineDataType(schema: BlockIOSubSchema): DataType {
// Credentials override
if ("credentials_provider" in schema) {
- return DataType.CREDENTIALS;
+ return { type: DataType.CREDENTIALS, schema };
}
if (
"google_drive_picker_config" in schema ||
("format" in schema && schema.format === "google-drive-picker")
) {
- return DataType.GOOGLE_DRIVE_PICKER;
+ return { type: DataType.GOOGLE_DRIVE_PICKER, schema };
}
// enum == SELECT
if ("enum" in schema) {
- return DataType.SELECT;
+ return { type: DataType.SELECT, schema };
}
// Handle anyOf => optional types (string|null, number|null, etc.)
@@ -1102,56 +1116,45 @@ export function determineDataType(schema: BlockIOSubSchema): DataType {
const strSchema = schema.anyOf.find(
(s) => s.type === "string",
) as BlockIOStringSubSchema;
- return _handleStringSchema(strSchema);
+ return { type: _handleStringSchema(strSchema), schema: strSchema };
}
- // (number|integer) & null
- if (
- (types.includes("number") || types.includes("integer")) &&
- types.includes("null")
- ) {
- // Just reuse our single-type logic for whichever is not null
- const numSchema = schema.anyOf.find(
- (s) => s.type === "number" || s.type === "integer",
- );
- if (numSchema) {
- return _handleSingleTypeSchema(numSchema);
- }
- return DataType.NUMBER; // fallback
+ // (number|integer) & null: reuse the single-type logic for the number
+ const numSchema = schema.anyOf.find(
+ (s) => s.type === "number" || s.type === "integer",
+ );
+ if (numSchema && types.includes("null")) {
+ return { type: _handleSingleTypeSchema(numSchema), schema: numSchema };
}
// (array | null)
- if (types.includes("array") && types.includes("null")) {
- // Check for table format on the parent schema (where anyOf is)
+ const arrSchema = schema.anyOf.find((s) => s.type === "array");
+ if (arrSchema && types.includes("null")) {
+ // AgentTableInputBlock writes the table format and its columns (`items`)
+ // on the field itself, beside an anyOf member that has neither.
if ("format" in schema && schema.format === "table") {
- return DataType.TABLE;
+ return { type: DataType.TABLE, schema };
}
-
- const arrSchema = schema.anyOf.find((s) => s.type === "array");
- if (arrSchema) return _handleSingleTypeSchema(arrSchema);
- return DataType.ARRAY;
+ return { type: _handleSingleTypeSchema(arrSchema), schema: arrSchema };
}
// (object | null)
- if (types.includes("object") && types.includes("null")) {
- const objSchema = schema.anyOf.find(
- (s) => s.type === "object",
- ) as BlockIOObjectSubSchema;
- if (objSchema) return _handleSingleTypeSchema(objSchema);
- return DataType.OBJECT;
+ const objSchema = schema.anyOf.find((s) => s.type === "object");
+ if (objSchema && types.includes("null")) {
+ return { type: _handleSingleTypeSchema(objSchema), schema: objSchema };
}
}
// oneOf + discriminator => user picks which variant => SELECT
if ("oneOf" in schema && "discriminator" in schema && schema.discriminator) {
- return DataType.SELECT;
+ return { type: DataType.SELECT, schema };
}
// Direct type
if ("type" in schema) {
- return _handleSingleTypeSchema(schema);
+ return { type: _handleSingleTypeSchema(schema), schema };
}
// Fallback
- return DataType.SHORT_TEXT;
+ return { type: DataType.SHORT_TEXT, schema };
}