diff --git a/frontend/e2e/numeric-controls.spec.ts b/frontend/e2e/numeric-controls.spec.ts index d396155f34..789ae23a47 100644 --- a/frontend/e2e/numeric-controls.spec.ts +++ b/frontend/e2e/numeric-controls.spec.ts @@ -381,7 +381,8 @@ test('native round-robin weights step once and preserve bounds and integer valid await clickNativeSpinner(weight, 'down') await expect(weight).toHaveValue('1') await weight.fill('2.5') - await expect(dialog.getByRole('alert')).toContainText('Weight must be a whole number') + // The dialog also keeps an always-mounted (empty) error summary alert (#3710); target the weight error. + await expect(dialog.getByRole('alert').filter({ hasText: 'Weight must be a whole number' })).toContainText('Weight must be a whole number') }) test('shared stepper preserves decimal steps, boundaries, disabled state, and reset', async ({ page }) => { diff --git a/frontend/e2e/target-create-errors.spec.ts b/frontend/e2e/target-create-errors.spec.ts new file mode 100644 index 0000000000..a97d15d228 --- /dev/null +++ b/frontend/e2e/target-create-errors.spec.ts @@ -0,0 +1,183 @@ +import { test, expect, type Locator, type Page } from "./_fixtures"; + +// #3710: a failed create keeps focus in the dialog, focuses and announces the error, and marks the field. + +const TARGET_TYPES = { + items: [ + { + target_type: "HTTPTarget", + parameters: [ + { + name: "http_request", + type_name: "str", + required: true, + default: null, + multiline: true, + description: "The HTTP request template containing the prompt placeholder.", + }, + { + name: "use_tls", + type_name: "bool", + required: false, + default: "True", + description: "Whether to use TLS.", + }, + ], + supported_auth_modes: ["api_key"], + description: "Sends prompts through a raw HTTP request template.", + }, + { + // One text input, so Enter submits the form implicitly. + target_type: "WebhookTarget", + parameters: [ + { + name: "webhook_url", + type_name: "str", + required: true, + default: null, + description: "The URL that receives each prompt.", + }, + ], + supported_auth_modes: ["api_key"], + description: "Posts prompts to a webhook.", + }, + ], +}; + +interface HeldCreate { + /** Resolves once the browser has sent the create request. */ + readonly requested: Promise>; + /** Lets the held create request fail with a 400. */ + readonly release: () => void; +} + +/** Mock the target routes, holding the create request until released and then rejecting it. */ +async function holdCreateThenReject(page: Page, detail: string): Promise { + let release: () => void = () => {}; + const released = new Promise((resolve) => { + release = resolve; + }); + let markRequested: (body: Record) => void = () => {}; + const requested = new Promise>((resolve) => { + markRequested = resolve; + }); + + await page.route(/\/api\/targets\/types(?:\?.*)?$/, async (route) => { + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify(TARGET_TYPES), + }); + }); + await page.route(/\/api\/targets(?:\?.*)?$/, async (route) => { + if (route.request().method() === "POST") { + markRequested(JSON.parse(route.request().postData() ?? "{}")); + await released; + await route.fulfill({ + status: 400, + contentType: "application/json", + body: JSON.stringify({ detail }), + }); + return; + } + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ + items: [], + pagination: { limit: 200, has_more: false, next_cursor: null, prev_cursor: null }, + }), + }); + }); + + return { requested, release }; +} + +async function openCreateTargetDialog(page: Page): Promise { + await page.goto("/"); + await page.getByRole("button", { name: "Registry", exact: true }).click(); + await expect(page.getByText("Target Registry")).toBeVisible({ timeout: 10000 }); + await page.getByRole("button", { name: /new target/i }).click(); + const dialog = page.getByRole("dialog"); + await expect(dialog.getByText("Create New Target")).toBeVisible(); + return dialog; +} + +async function selectTargetType(page: Page, dialog: Locator, targetType: string): Promise { + const picker = dialog.getByRole("combobox", { name: "Target Type" }); + await expect(picker).toBeEnabled(); + await picker.click(); + await page.getByRole("option", { + name: new RegExp(`Implementation: ${targetType}`), + }).click(); +} + +/** Tag name of the focused element, so a failure reads e.g. `BODY`. */ +async function activeElementTag(page: Page): Promise { + return page.evaluate(() => document.activeElement?.tagName ?? "none"); +} + +test.describe("Create Target errors (#3710)", () => { + test("keeps focus on Create while in flight, then focuses the announced error", async ({ page }) => { + const HTTP_ERROR = "Invalid HTTP request line"; + const create = await holdCreateThenReject(page, HTTP_ERROR); + const dialog = await openCreateTargetDialog(page); + + await selectTargetType(page, dialog, "HTTPTarget"); + const httpRequest = dialog.getByLabel(/Http Request/); + await httpRequest.fill("not an HTTP request"); + + const createButton = dialog.getByRole("button", { name: /^(Create Target|Creating\.\.\.)$/ }); + await createButton.focus(); + await page.keyboard.press("Space"); + + expect(await create.requested).toMatchObject({ + type: "HTTPTarget", + params: { http_request: "not an HTTP request" }, + }); + // Chromium blurs a newly disabled control a tick later. + await page.waitForTimeout(250); + expect(await activeElementTag(page)).not.toBe("BODY"); + await expect(createButton).toBeFocused(); + + create.release(); + + const alert = dialog.getByRole("alert"); + await expect(alert).toContainText(HTTP_ERROR); + await expect(alert).toBeFocused(); + await expect(httpRequest).toHaveAttribute("aria-invalid", "true"); + + // Escape only reaches the dialog surface while focus is still inside it. + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + }); + + test("keeps focus in the field after Enter submits, then focuses the announced error", async ({ page }) => { + const WEBHOOK_ERROR = "webhook_url must be an absolute URL"; + const create = await holdCreateThenReject(page, WEBHOOK_ERROR); + const dialog = await openCreateTargetDialog(page); + + await selectTargetType(page, dialog, "WebhookTarget"); + const webhookUrl = dialog.getByLabel(/Webhook Url/); + await webhookUrl.fill("not-a-url"); + await webhookUrl.press("Enter"); + + expect(await create.requested).toMatchObject({ + type: "WebhookTarget", + params: { webhook_url: "not-a-url" }, + }); + await page.waitForTimeout(250); + expect(await activeElementTag(page)).not.toBe("BODY"); + await expect(webhookUrl).toBeFocused(); + + create.release(); + + const alert = dialog.getByRole("alert"); + await expect(alert).toContainText(WEBHOOK_ERROR); + await expect(alert).toBeFocused(); + await expect(webhookUrl).toHaveAttribute("aria-invalid", "true"); + + await page.keyboard.press("Escape"); + await expect(dialog).toBeHidden(); + }); +}); diff --git a/frontend/src/components/Config/CreateTargetDialog.styles.ts b/frontend/src/components/Config/CreateTargetDialog.styles.ts index a29a0878e2..b5e8dba475 100644 --- a/frontend/src/components/Config/CreateTargetDialog.styles.ts +++ b/frontend/src/components/Config/CreateTargetDialog.styles.ts @@ -21,6 +21,17 @@ export const useCreateTargetDialogStyles = makeStyles({ maxWidth: '100%', gap: tokens.spacingVerticalL, }, + // Visually hidden, not display:none, so the empty live region stays in the accessibility tree. + errorRegionEmpty: { + position: 'absolute', + width: '1px', + height: '1px', + padding: '0', + margin: '-1px', + overflow: 'hidden', + clip: 'rect(0,0,0,0)', + whiteSpace: 'nowrap', + }, formField: { minWidth: 0, maxWidth: '100%', diff --git a/frontend/src/components/Config/CreateTargetDialog.test.tsx b/frontend/src/components/Config/CreateTargetDialog.test.tsx index 6479d3cec9..01b880c261 100644 --- a/frontend/src/components/Config/CreateTargetDialog.test.tsx +++ b/frontend/src/components/Config/CreateTargetDialog.test.tsx @@ -981,7 +981,11 @@ describe("CreateTargetDialog", () => { } await waitFor(() => { - expect(screen.getByText("Please provide an endpoint URL")).toBeInTheDocument(); + // Scoped to the Endpoint URL field: the dialog's error summary (#3710) repeats the text. + const endpointField = screen + .getByPlaceholderText("https://your-resource.openai.azure.com/") + .closest(".fui-Field") as HTMLElement; + expect(within(endpointField).getByText("Please provide an endpoint URL")).toBeInTheDocument(); }); }); @@ -1572,7 +1576,8 @@ describe("CreateTargetDialog", () => { await user.type(screen.getByRole("textbox", { name: /Model \/ Deployment Name/ }), "gpt-4.1"); await user.click(screen.getByRole("button", { name: "Create Target" })); - expect(await screen.findByText(detail)).toBeVisible(); + // First match is the dialog's error summary; the GitHub Token field (#3710) may repeat the attributed text. + expect((await screen.findAllByText(detail))[0]).toBeVisible(); expect(defaultProps.onCreated).not.toHaveBeenCalled(); expect(screen.getByRole("textbox", { name: /Model \/ Deployment Name/ })).toHaveValue("gpt-4.1"); @@ -2514,3 +2519,672 @@ describe("CreateTargetDialog", () => { expect(mockedTargetsApi.createTarget).not.toHaveBeenCalled(); }, 30000); }); + +// #3710. jsdom never blurs a disabled element, so in-flight checks assert aria-disabled; +// the real focus check is in e2e/target-create-errors.spec.ts. +describe("submit error accessibility (#3710)", () => { + const HTTP_ERROR = "Invalid HTTP request line"; + const INVALID_HTTP_REQUEST = "not an HTTP request"; + + let dialogAccessibilityObserver: MutationObserver; + + beforeEach(() => { + dialogAccessibilityObserver = watchDialogAccessibility(); + jest.clearAllMocks(); + // clearAllMocks keeps queued *Once values from a test that stopped early. + mockedTargetsApi.createTarget.mockReset(); + mockedTargetsApi.listTargetTypes.mockResolvedValue(TARGET_TYPES); + mockedTargetsApi.listTargets.mockResolvedValue({ + items: [], + pagination: { limit: 200, has_more: false, next_cursor: null, prev_cursor: null }, + } as unknown as Awaited>); + }); + + afterEach(() => { + dialogAccessibilityObserver.disconnect(); + mockedTargetsApi.createTarget.mockReset(); + }); + + type CreateTargetResult = Awaited>; + + function axiosError(status: number, detail: string): Error { + return Object.assign(new Error(`Request failed with status code ${status}`), { + isAxiosError: true, + response: { status, data: { detail } }, + }); + } + + function deferredCreate() { + let reject: (reason: unknown) => void = () => {}; + const promise = new Promise((_, rejectPromise) => { + reject = rejectPromise; + }); + mockedTargetsApi.createTarget.mockReturnValueOnce(promise); + return { reject }; + } + + function dialogTree(props: Partial> = {}) { + return ( + + + + ); + } + + function getDialog(): HTMLElement { + const dialog = document.querySelector('[role="dialog"]'); + expect(dialog).not.toBeNull(); + return dialog!; + } + + function getErrorRegion(): HTMLElement { + return screen.getByTestId("create-target-error"); + } + + function getCreateButton(): HTMLButtonElement { + return screen.getByText("Create Target").closest("button")!; + } + + function getForm(): HTMLFormElement { + return screen.getByTestId("create-target-form") as HTMLFormElement; + } + + function invalidControls(): Element[] { + return Array.from(getDialog().querySelectorAll('[aria-invalid="true"]')); + } + + /** Concatenated text of every element the control's aria-describedby references. */ + function describedByText(element: Element): string { + const ids = (element.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean); + return ids.map((id) => document.getElementById(id)?.textContent ?? "").join(" "); + } + + async function fillHttpTarget(value = INVALID_HTTP_REQUEST): Promise { + await selectTargetType("HTTPTarget"); + const httpRequestField = screen.getByLabelText(/Http Request/, { selector: "textarea" }); + fireEvent.change(httpRequestField, { target: { value } }); + return httpRequestField; + } + + async function expectSummaryFocused(text: string): Promise { + const region = getErrorRegion(); + await waitFor(() => { + expect(region).toHaveTextContent(text); + }); + await waitFor(() => { + expect(region).toHaveFocus(); + }); + return region; + } + + it("renders an empty, focusable alert region before any error exists", async () => { + render(dialogTree()); + await flushTargetTypesFetch(); + + const region = getErrorRegion(); + expect(region).toHaveAttribute("role", "alert"); + expect(region).toHaveAttribute("aria-atomic", "true"); + expect(region).toHaveAttribute("tabindex", "-1"); + expect(region).toHaveTextContent(""); + expect(getDialog()).toContainElement(region); + }); + + it("announces, focuses and attributes the issue's HTTPTarget 400 to Http Request", async () => { + const user = userEvent.setup(); + mockedTargetsApi.createTarget.mockRejectedValueOnce(axiosError(400, HTTP_ERROR)); + render(dialogTree()); + + const httpRequestField = await fillHttpTarget(); + // The live region exists before the error arrives. + const region = getErrorRegion(); + await user.click(getCreateButton()); + + await expectSummaryFocused(HTTP_ERROR); + expect(getErrorRegion()).toBe(region); + expect(httpRequestField).toHaveAttribute("aria-invalid", "true"); + expect(describedByText(httpRequestField)).toContain(HTTP_ERROR); + // The field message must not add a second alert to the one live region. + const alerts = getDialog().querySelectorAll('[role="alert"]'); + expect(alerts).toHaveLength(1); + expect(alerts[0]).toBe(region); + }); + + it("keeps Create focusable (aria-disabled) and the form operable while the request is in flight", async () => { + const user = userEvent.setup(); + const create = deferredCreate(); + render(dialogTree()); + await selectTargetType("HTTPTarget"); + + // Disabled for validation reasons: still natively disabled. + const createButton = getCreateButton(); + expect(createButton).toHaveAttribute("disabled"); + + const httpRequestField = screen.getByLabelText(/Http Request/, { selector: "textarea" }); + fireEvent.change(httpRequestField, { target: { value: INVALID_HTTP_REQUEST } }); + expect(createButton).toBeEnabled(); + + await user.click(createButton); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + }); + + expect(createButton).toHaveAttribute("aria-disabled", "true"); + expect(createButton).not.toHaveAttribute("disabled"); + expect(screen.getByText("Cancel").closest("button")).toBeEnabled(); + expect(httpRequestField).not.toBeDisabled(); + + await act(async () => { + create.reject(axiosError(400, HTTP_ERROR)); + }); + await expectSummaryFocused(HTTP_ERROR); + }); + + it("clears the field's invalid state on edit but keeps the summary", async () => { + const user = userEvent.setup(); + mockedTargetsApi.createTarget.mockRejectedValueOnce(axiosError(400, HTTP_ERROR)); + render(dialogTree()); + + const httpRequestField = await fillHttpTarget(); + await user.click(getCreateButton()); + await expectSummaryFocused(HTTP_ERROR); + expect(httpRequestField).toHaveAttribute("aria-invalid", "true"); + + fireEvent.change(httpRequestField, { target: { value: "GET / HTTP/1.1" } }); + + expect(httpRequestField).not.toHaveAttribute("aria-invalid", "true"); + expect(getErrorRegion()).toHaveTextContent(HTTP_ERROR); + }); + + it("re-inserts and re-focuses an identical error on a second failure", async () => { + const user = userEvent.setup(); + mockedTargetsApi.createTarget + .mockRejectedValueOnce(axiosError(400, HTTP_ERROR)) + .mockRejectedValueOnce(axiosError(400, HTTP_ERROR)); + render(dialogTree()); + + await fillHttpTarget(); + await user.click(getCreateButton()); + const region = await expectSummaryFocused(HTTP_ERROR); + const firstMessageBar = region.querySelector(".fui-MessageBar"); + expect(firstMessageBar).not.toBeNull(); + + await user.click(getCreateButton()); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(2); + }); + await waitFor(() => { + const messageBar = region.querySelector(".fui-MessageBar"); + expect(messageBar).not.toBeNull(); + expect(messageBar).not.toBe(firstMessageBar); + }); + await expectSummaryFocused(HTTP_ERROR); + }); + + it.each([ + ["a 500 response", () => axiosError(500, "Upstream HTTP request failed"), "Upstream HTTP request failed"], + ["a 403 response", () => axiosError(403, "Not allowed to send this HTTP request"), "Not allowed to send this HTTP request"], + ["a non-axios Error", () => new Error(HTTP_ERROR), HTTP_ERROR], + ])("does not attribute %s to a field, but still announces and focuses it", async (_, makeError, shownText) => { + const user = userEvent.setup(); + mockedTargetsApi.createTarget.mockRejectedValueOnce(makeError()); + render(dialogTree()); + + const httpRequestField = await fillHttpTarget(); + await user.click(getCreateButton()); + + await expectSummaryFocused(shownText); + expect(httpRequestField).not.toHaveAttribute("aria-invalid", "true"); + expect(invalidControls()).toHaveLength(0); + }); + + it.each([ + "http_request and use_tls are incompatible", + "Http Request conflicts with Use Tls", + ])("does not guess a field when a 400 names two fields: %s", async (detail) => { + const user = userEvent.setup(); + mockedTargetsApi.createTarget.mockRejectedValueOnce(axiosError(400, detail)); + render(dialogTree()); + + await fillHttpTarget(); + await user.click(getCreateButton()); + + await expectSummaryFocused(detail); + expect(invalidControls()).toHaveLength(0); + }); + + it("announces, focuses and attributes a client-side parameter error from an Enter submit", async () => { + const user = userEvent.setup(); + render(dialogTree()); + + await selectTargetType("OpenAIChatTarget"); + await user.click(screen.getByText("Advanced settings")); + fireEvent.change(screen.getByPlaceholderText("https://your-resource.openai.azure.com/"), { + target: { value: "https://api.openai.com" }, + }); + const seedInput = screen.getByLabelText("Seed", { selector: "input" }); + fireEvent.change(seedInput, { target: { value: "2.5" } }); + + // Pressing Enter in a field submits the form, bypassing the Create button. + seedInput.focus(); + fireEvent.submit(getForm()); + + await expectSummaryFocused("seed must be an integer."); + expect(seedInput).toHaveAttribute("aria-invalid", "true"); + expect(invalidControls()).toEqual([seedInput]); + expect(mockedTargetsApi.createTarget).not.toHaveBeenCalled(); + }); + + it("does not show a stale error after closing mid-request and reopening", async () => { + const user = userEvent.setup(); + const onClose = jest.fn(); + const create = deferredCreate(); + const { rerender } = render(dialogTree({ onClose })); + + await fillHttpTarget(); + await user.click(getCreateButton()); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + }); + + // Escape while the request is in flight. + fireEvent.keyDown(getDialog(), { key: "Escape", code: "Escape" }); + expect(onClose).toHaveBeenCalled(); + rerender(dialogTree({ onClose, open: false })); + + await act(async () => { + create.reject(axiosError(400, HTTP_ERROR)); + }); + + rerender(dialogTree({ onClose, open: true })); + await flushTargetTypesFetch(); + + expect(screen.queryByText(HTTP_ERROR)).not.toBeInTheDocument(); + expect(getErrorRegion()).toHaveTextContent(""); + expect(invalidControls()).toHaveLength(0); + }); + + it("sends only one create request when the form is submitted twice in flight", async () => { + const create = deferredCreate(); + render(dialogTree()); + + await fillHttpTarget(); + fireEvent.submit(getForm()); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + }); + fireEvent.submit(getForm()); + await act(async () => {}); + + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + + await act(async () => { + create.reject(axiosError(400, HTTP_ERROR)); + }); + await expectSummaryFocused(HTTP_ERROR); + }); + + describe("RoundRobinTarget", () => { + const roundRobinTargets = [ + makeTarget({ + target_registry_name: "a", + target_type: "OpenAIChatTarget", + model_name: "gpt-4o", + identifier_hash: "hash-a", + }), + makeTarget({ + target_registry_name: "b", + target_type: "OpenAIChatTarget", + model_name: "gpt-4o", + identifier_hash: "hash-b", + }), + ]; + + async function selectRoundRobinTargets( + user: ReturnType, + names: string[], + ): Promise { + await selectTargetType("RoundRobinTarget"); + const select = screen.getByText("Select a target to add...").closest("select")!; + for (const name of names) { + await user.selectOptions(select, name); + } + await waitFor(() => { + expect(screen.getAllByLabelText(/Weight for /)).toHaveLength(names.length); + }, { timeout: 10000 }); + } + + it("announces and focuses the fewer-than-two-targets error from an Enter submit", async () => { + const user = userEvent.setup(); + render(dialogTree({ existingTargets: roundRobinTargets })); + await selectRoundRobinTargets(user, ["a"]); + + fireEvent.submit(getForm()); + + await expectSummaryFocused("Please select at least 2 targets."); + expect(invalidControls()).toHaveLength(0); + expect(mockedTargetsApi.createTarget).not.toHaveBeenCalled(); + }, 30000); + + it("announces and focuses a backend rejection without attributing it to a field", async () => { + const user = userEvent.setup(); + const detail = "Target 'b' endpoint and model_name differ from target 'a'."; + mockedTargetsApi.createTarget.mockRejectedValueOnce(axiosError(400, detail)); + render(dialogTree({ existingTargets: roundRobinTargets })); + await selectRoundRobinTargets(user, ["a", "b"]); + + await user.click(getCreateButton()); + + await expectSummaryFocused(detail); + expect(invalidControls()).toHaveLength(0); + }, 30000); + }); + + it("clears the error when the target type changes", async () => { + const user = userEvent.setup(); + mockedTargetsApi.createTarget.mockRejectedValueOnce(axiosError(400, HTTP_ERROR)); + render(dialogTree()); + + await fillHttpTarget(); + await user.click(getCreateButton()); + // The attributed error appears in the summary and in the field's message. + expect((await screen.findAllByText(HTTP_ERROR)).length).toBeGreaterThan(0); + + await selectTargetType("OpenAIChatTarget"); + + expect(screen.queryByText(HTTP_ERROR)).not.toBeInTheDocument(); + expect(getErrorRegion()).toHaveTextContent(""); + expect(invalidControls()).toHaveLength(0); + }); + + describe("late responses and edge cases", () => { + function deferredCreateSuccess() { + let resolve: (value: CreateTargetResult) => void = () => {}; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + mockedTargetsApi.createTarget.mockReturnValueOnce(promise); + return { resolve }; + } + + // A late success must not reset a reopened dialog. + it("leaves a newer opening untouched when a dismissed create succeeds", async () => { + const user = userEvent.setup(); + const onClose = jest.fn(); + const onCreated = jest.fn(); + const create = deferredCreateSuccess(); + const { rerender } = render(dialogTree({ onClose, onCreated })); + + await fillHttpTarget(); + await user.click(getCreateButton()); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + }); + + await user.click(screen.getByText("Cancel").closest("button")!); + expect(onClose).toHaveBeenCalled(); + rerender(dialogTree({ onClose, onCreated, open: false })); + rerender(dialogTree({ onClose, onCreated, open: true })); + await flushTargetTypesFetch(); + await fillHttpTarget("GET / HTTP/1.1"); + + await act(async () => { + create.resolve(makeTarget({ target_registry_name: "raw_http_target", target_type: "HTTPTarget" })); + }); + + expect(onCreated).toHaveBeenCalledTimes(1); + expect(onCreated).toHaveBeenCalledWith(false); + expect(screen.getByLabelText(/Http Request/, { selector: "textarea" })).toHaveValue("GET / HTTP/1.1"); + }); + + it("tells the parent a create from the current opening succeeded", async () => { + const user = userEvent.setup(); + const onCreated = jest.fn(); + mockedTargetsApi.createTarget.mockResolvedValueOnce( + makeTarget({ target_registry_name: "raw_http_target", target_type: "HTTPTarget" }), + ); + render(dialogTree({ onCreated })); + + await fillHttpTarget("GET / HTTP/1.1"); + await user.click(getCreateButton()); + + await waitFor(() => { + expect(onCreated).toHaveBeenCalledWith(true); + }); + }); + + it("leaves a newer RoundRobin opening untouched when a dismissed create succeeds", async () => { + const user = userEvent.setup(); + const onClose = jest.fn(); + const onCreated = jest.fn(); + const create = deferredCreateSuccess(); + const existingTargets = [ + makeTarget({ + target_registry_name: "a", + target_type: "OpenAIChatTarget", + model_name: "gpt-4o", + identifier_hash: "hash-a", + }), + makeTarget({ + target_registry_name: "b", + target_type: "OpenAIChatTarget", + model_name: "gpt-4o", + identifier_hash: "hash-b", + }), + ]; + const { rerender } = render(dialogTree({ onClose, onCreated, existingTargets })); + + await selectTargetType("RoundRobinTarget"); + const select = screen.getByText("Select a target to add...").closest("select")!; + await user.selectOptions(select, "a"); + await user.selectOptions(select, "b"); + await user.click(getCreateButton()); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + }); + + await user.click(screen.getByText("Cancel").closest("button")!); + expect(onClose).toHaveBeenCalled(); + rerender(dialogTree({ onClose, onCreated, existingTargets, open: false })); + rerender(dialogTree({ onClose, onCreated, existingTargets, open: true })); + await flushTargetTypesFetch(); + await selectTargetType("RoundRobinTarget"); + await user.selectOptions(screen.getByText("Select a target to add...").closest("select")!, "a"); + await waitFor(() => { + expect(screen.getAllByLabelText(/Weight for /)).toHaveLength(1); + }); + + await act(async () => { + create.resolve(makeTarget({ target_registry_name: "rr", target_type: "RoundRobinTarget" })); + }); + + expect(onCreated).toHaveBeenCalledTimes(1); + expect(onCreated).toHaveBeenCalledWith(false); + expect(screen.getAllByLabelText(/Weight for /)).toHaveLength(1); + }, 30000); + + // An error for a type the user switched away from is not attributed, even to a same-named field. + it("does not attribute a rejection to a field after the target type changed", async () => { + const user = userEvent.setup(); + const create = deferredCreate(); + render(dialogTree()); + + await selectTargetType("OpenAIChatTarget"); + fireEvent.change(screen.getByPlaceholderText("https://your-resource.openai.azure.com/"), { + target: { value: "https://example.com" }, + }); + await user.click(getCreateButton()); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + }); + + // AzureMLChatTarget also has an endpoint field. + await selectTargetType("AzureMLChatTarget"); + await act(async () => { + create.reject(axiosError(400, "endpoint is unreachable")); + }); + + await expectSummaryFocused("endpoint is unreachable"); + expect(invalidControls()).toHaveLength(0); + }); + + it("does not attribute a late rejection to a parameter edited while the request was pending", async () => { + const user = userEvent.setup(); + const create = deferredCreate(); + render(dialogTree()); + + const httpRequestField = await fillHttpTarget(); + await user.click(getCreateButton()); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + }); + + fireEvent.change(httpRequestField, { target: { value: "GET / HTTP/1.1" } }); + await act(async () => { + create.reject(axiosError(400, HTTP_ERROR)); + }); + + await expectSummaryFocused(HTTP_ERROR); + expect(httpRequestField).not.toHaveAttribute("aria-invalid", "true"); + expect(invalidControls()).toHaveLength(0); + }); + + it("does not attribute a late rejection to a client field edited while the request was pending", async () => { + const user = userEvent.setup(); + const create = deferredCreate(); + render(dialogTree()); + + await selectTargetType("OpenAIChatTarget"); + const endpointField = screen.getByPlaceholderText("https://your-resource.openai.azure.com/"); + fireEvent.change(endpointField, { target: { value: "https://example.com" } }); + await user.click(getCreateButton()); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + }); + + fireEvent.change(endpointField, { target: { value: "https://fixed.openai.azure.com/" } }); + await act(async () => { + create.reject(axiosError(400, "endpoint is unreachable")); + }); + + await expectSummaryFocused("endpoint is unreachable"); + expect(invalidControls()).toHaveLength(0); + }); + + it("still attributes a late rejection when only a different field was edited", async () => { + const user = userEvent.setup(); + const create = deferredCreate(); + render(dialogTree()); + + await selectTargetType("OpenAIChatTarget"); + const endpointField = screen.getByPlaceholderText("https://your-resource.openai.azure.com/"); + fireEvent.change(endpointField, { target: { value: "https://example.com" } }); + await user.click(getCreateButton()); + await waitFor(() => { + expect(mockedTargetsApi.createTarget).toHaveBeenCalledTimes(1); + }); + + fireEvent.change(screen.getByPlaceholderText("e.g. gpt-4o, my-deployment"), { + target: { value: "gpt-4o" }, + }); + await act(async () => { + create.reject(axiosError(400, "endpoint is unreachable")); + }); + + await expectSummaryFocused("endpoint is unreachable"); + expect(endpointField).toHaveAttribute("aria-invalid", "true"); + }); + + // An attributed optional parameter opens Advanced settings, and it stays open. + it("opens Advanced settings when the error is about an optional parameter", async () => { + const user = userEvent.setup(); + mockedTargetsApi.createTarget.mockRejectedValueOnce( + axiosError(400, "use_tls must be a boolean"), + ); + render(dialogTree()); + + const httpRequestField = await fillHttpTarget(); + const useTls = screen.getByTestId("target-param-use_tls"); + const advancedSettings = useTls.closest("details")!; + expect(advancedSettings).not.toHaveAttribute("open"); + + await user.click(getCreateButton()); + await expectSummaryFocused("use_tls must be a boolean"); + + expect(advancedSettings).toHaveAttribute("open"); + expect(useTls).toBeVisible(); + expect(useTls).toHaveAttribute("aria-invalid", "true"); + + fireEvent.change(httpRequestField, { target: { value: "GET / HTTP/1.1" } }); + expect(advancedSettings).toHaveAttribute("open"); + }); + + // The summary joins messages as sentences; field messages are unchanged. + it("joins several client validation messages into sentences in the summary", async () => { + mockedTargetsApi.listTargetTypes.mockResolvedValue({ + items: [ + { + target_type: "AzureMLChatTarget", + parameters: AZURE_ML_COMMON_PARAMETERS.map((parameter) => ( + parameter.name === "model_name" ? { ...parameter, required: true } : parameter + )), + supported_auth_modes: ["api_key"], + description: "A prompt target for Azure Machine Learning chat endpoints.", + }, + ], + }); + render(dialogTree()); + + await selectTargetType("AzureMLChatTarget"); + const endpointInput = screen.getByPlaceholderText( + "https://your-model.region.inference.ml.azure.com/score", + ); + act(() => { + endpointInput.focus(); + }); + fireEvent.submit(getForm()); + + const region = await expectSummaryFocused("Please provide an endpoint URL."); + expect(region).toHaveTextContent( + /^Please provide an endpoint URL\. Please provide a model name\.$/, + ); + const endpointField = endpointInput.closest(".fui-Field") as HTMLElement; + expect(within(endpointField).getByText("Please provide an endpoint URL")).toBeInTheDocument(); + const modelField = screen + .getByPlaceholderText("e.g. Llama-3.2-3B-Instruct") + .closest(".fui-Field") as HTMLElement; + expect(within(modelField).getByText("Please provide a model name")).toBeInTheDocument(); + }); + + it("ends a single client validation message with a period in the summary only", async () => { + const user = userEvent.setup(); + render(dialogTree()); + + await selectTargetType("OpenAIChatTarget"); + await user.click(screen.getByRole("radio", { name: /Identity-based/ })); + fireEvent.submit(getForm()); + + const region = await expectSummaryFocused("Please provide an endpoint URL"); + expect(region).toHaveTextContent(/^Please provide an endpoint URL\.$/); + const endpointField = screen + .getByPlaceholderText("https://your-resource.openai.azure.com/") + .closest(".fui-Field") as HTMLElement; + expect(within(endpointField).getByText("Please provide an endpoint URL")).toBeInTheDocument(); + }); + + // Under identity auth, an identity-conflicting parameter is never attributed. + it("does not attribute an error to an identity-conflicting parameter under identity auth", async () => { + const user = userEvent.setup(); + mockedTargetsApi.createTarget.mockRejectedValueOnce( + axiosError(400, "sas_token is not allowed with this storage account"), + ); + render(dialogTree()); + + await selectTargetType("AzureBlobStorageTarget"); + await user.click(screen.getByRole("radio", { name: /Identity-based/ })); + await user.click(getCreateButton()); + + await expectSummaryFocused("sas_token is not allowed with this storage account"); + expect(invalidControls()).toHaveLength(0); + }); + }); +}); diff --git a/frontend/src/components/Config/CreateTargetDialog.tsx b/frontend/src/components/Config/CreateTargetDialog.tsx index 6f30edefbd..bae83eec77 100644 --- a/frontend/src/components/Config/CreateTargetDialog.tsx +++ b/frontend/src/components/Config/CreateTargetDialog.tsx @@ -1,4 +1,4 @@ -import { useState, useEffect, useMemo } from 'react' +import { useState, useEffect, useMemo, useRef } from 'react' import { Dialog, DialogSurface, @@ -31,8 +31,9 @@ import { buildParametersFromForm, type ParameterFormValue, } from '@/components/Parameters/parameterForm' +import { describedOnly } from '@/components/Parameters/validationMessageSlot' import { targetsApi } from '@/services/api' -import { toApiError } from '@/services/errors' +import { toApiError, type ApiError } from '@/services/errors' import type { TargetInstance, TargetTypeEntry } from '@/types' import { targetIdentifierHash, @@ -41,6 +42,11 @@ import { targetUnderlyingModelName, } from '@/utils/targetIdentity' import { useCreateTargetDialogStyles } from './CreateTargetDialog.styles' +import { + attributeErrorToField, + getParameterLabel, + type AttributionCandidate, +} from './fieldErrorAttribution' import { canConfigureTargetType, getTargetParameterPolicy, @@ -149,13 +155,6 @@ function defaultSupportsIdentity(targetType: string): boolean { return FALLBACK_IDENTITY_TARGET_TYPES.has(targetType) } -function getParameterLabel(name: string): string { - return name - .split('_') - .map((word) => word.length === 1 ? word.toUpperCase() : `${word[0].toUpperCase()}${word.slice(1)}`) - .join(' ') -} - function isParameterValueSet(value: ParameterFormValue | undefined): boolean { if (typeof value === 'string') { return value.trim().length > 0 @@ -198,10 +197,25 @@ function isAzureMlEndpoint(endpoint: string): boolean { } } +type ClientFieldKey = 'targetType' | 'endpoint' | 'modelName' | 'underlyingModel' | 'apiKey' +type ClientFieldErrors = Partial> + +// `attempt` changes on every report, so an identical repeat is still refocused and re-announced. +interface DialogError { + message: string + field?: string + attempt: number +} + +function asSentence(message: string): string { + return /[.!?]$/.test(message) ? message : `${message}.` +} + interface CreateTargetDialogProps { open: boolean onClose: () => void - onCreated: () => void + /** `isCurrentOpening` is false when the user closed the dialog before the request finished. */ + onCreated: (isCurrentOpening: boolean) => void /** Existing targets, passed from the parent to avoid a redundant API call. */ existingTargets?: TargetInstance[] } @@ -268,14 +282,27 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT const [apiKey, setApiKey] = useState('') const [parameterValues, setParameterValues] = useState>({}) const [submitting, setSubmitting] = useState(false) - const [error, setError] = useState(null) - const [fieldErrors, setFieldErrors] = useState<{ - targetType?: string - endpoint?: string - modelName?: string - underlyingModel?: string - apiKey?: string - }>({}) + const [error, setError] = useState(null) + const [fieldErrors, setFieldErrors] = useState({}) + const attemptRef = useRef(0) + const errorRegionRef = useRef(null) + // Inputs stay enabled while submitting, so Enter could submit twice. + const submittingRef = useRef(false) + // Bumped on close; a response from an earlier opening is ignored. + const openEpochRef = useRef(0) + useEffect(() => () => { openEpochRef.current += 1 }, []) + // Bumped on type change; a failure from the previous type's form names no field. + const typeSelectionRef = useRef(0) + // Fields edited since the last submit; a late failure is not attributed to them. + const editedSinceSubmitRef = useRef(new Set()) + const advancedSettingsRef = useRef(null) + + // Keyed on the attempt only, so editing an attributed field doesn't steal focus back. + const focusAttempt = error?.attempt ?? 0 + useEffect(() => { + if (!focusAttempt) return + errorRegionRef.current?.focus() + }, [focusAttempt]) // --- RoundRobin-specific state --- // The list of targets available for selection (fetched once when dialog opens). @@ -492,15 +519,105 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT } const handleClose = () => { + openEpochRef.current += 1 + submittingRef.current = false + setSubmitting(false) resetForm() onClose() } + const reportError = (message: string, field?: string | null) => { + attemptRef.current += 1 + setError({ message, field: field ?? undefined, attempt: attemptRef.current }) + // Reveal an attributed field hidden in the collapsed Advanced settings. + if (field && optionalMetadataParameters.some((parameter) => parameter.name === field)) { + if (advancedSettingsRef.current) advancedSettingsRef.current.open = true + } + } + + // Editing the attributed field un-marks it; the summary stays until the next submit. + const clearFieldAttribution = (field: string) => { + editedSinceSubmitRef.current.add(field) + setError((current) => ( + current?.field === field ? { ...current, field: undefined } : current + )) + } + + const clearClientFieldError = (field: ClientFieldKey) => { + setFieldErrors((current) => { + if (current[field] === undefined) return current + const next = { ...current } + delete next[field] + return next + }) + clearFieldAttribution(field) + } + + const handleParameterChange = (name: string, value: ParameterFormValue) => { + setParameterValues((current) => ({ ...current, [name]: value })) + clearFieldAttribution(name) + } + + const buildAttributionCandidates = (): AttributionCandidate[] => { + const candidates: AttributionCandidate[] = [ + { key: 'targetType', names: ['target_type', 'Target Type'] }, + ] + if (hasEndpointField) candidates.push({ key: 'endpoint', names: ['endpoint', 'Endpoint URL'] }) + if (hasModelNameField) { + candidates.push({ key: 'modelName', names: ['model_name', 'Model / Deployment Name'] }) + } + if (hasUnderlyingModelField && (underlyingModelRequired || hasDifferentUnderlying)) { + candidates.push({ + key: 'underlyingModel', + names: [underlyingModelParameter?.name ?? 'underlying_model', 'Underlying Model'], + }) + } + if (hasApiKeyField && !isIdentity) candidates.push({ key: 'apiKey', names: ['api_key', 'API Key'] }) + for (const parameter of metadataDrivenParameters) { + // Disabled and not sent under identity auth. + if (isIdentity && parameter.identity_conflicting) continue + const label = parameter === githubTokenParameter ? 'GitHub Token' : getParameterLabel(parameter.name) + candidates.push({ key: parameter.name, names: [parameter.name, label] }) + } + return candidates + } + + // A response that outlives its opening only refreshes the list; it never touches a reopened dialog. + const submitCreate = async ( + request: Parameters[0], + fieldFor: (apiError: ApiError) => string | null = () => null, + ) => { + const epoch = openEpochRef.current + editedSinceSubmitRef.current.clear() + submittingRef.current = true + setSubmitting(true) + setError(null) + try { + await targetsApi.createTarget(request) + const isCurrentOpening = openEpochRef.current === epoch + if (isCurrentOpening) resetForm() + onCreated(isCurrentOpening) + } catch (err) { + // Surface the backend's RFC 7807 `detail` rather than axios's generic message. + const apiError = toApiError(err) + if (openEpochRef.current === epoch) { + const field = fieldFor(apiError) + reportError(apiError.detail, field && !editedSinceSubmitRef.current.has(field) ? field : null) + } + } finally { + if (openEpochRef.current === epoch) { + submittingRef.current = false + setSubmitting(false) + } + } + } + const handleSubmit = async () => { + if (submittingRef.current) return // For RoundRobinTarget, validation is different: we need ≥2 selected targets, not endpoint if (isRoundRobin) { if (selectedInnerTargets.length < 2) { - setError('Please select at least 2 targets.') + reportError('Please select at least 2 targets.') return } // Re-validate every weight at submit time. The Submit button's disabled @@ -510,42 +627,22 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT for (const t of selectedInnerTargets) { const parsed = parseWeight(t.weightInput) if (!parsed.ok) { - setError(`Invalid weight for "${t.registryName}": ${parsed.error}.`) + reportError(`Invalid weight for "${t.registryName}": ${parsed.error}.`) return } parsedWeights.push(parsed.value) } - - setSubmitting(true) - setError(null) - - try { - await targetsApi.createTarget({ - type: 'RoundRobinTarget', - params: { - targets: selectedInnerTargets.map((t) => t.registryName), - weights: parsedWeights, - }, - }) - resetForm() - onCreated() - } catch (err) { - // Surface the backend's RFC 7807 `detail` (e.g. RoundRobinTarget validation - // messages) rather than the generic axios "Request failed with status code 400". - setError(toApiError(err).detail) - } finally { - setSubmitting(false) - } + await submitCreate({ + type: 'RoundRobinTarget', + params: { + targets: selectedInnerTargets.map((t) => t.registryName), + weights: parsedWeights, + }, + }) return } - const errors: { - targetType?: string - endpoint?: string - modelName?: string - underlyingModel?: string - apiKey?: string - } = {} + const errors: ClientFieldErrors = {} if (!targetType) errors.targetType = 'Please select a target type' if (endpointRequired && !endpoint) errors.endpoint = 'Please provide an endpoint URL' if (modelNameRequired && !modelName) errors.modelName = 'Please provide a model name' @@ -553,60 +650,82 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT errors.underlyingModel = 'Please provide the underlying model' } if (apiKeyRequired && !apiKey) errors.apiKey = 'Please provide an API key' - if (Object.keys(errors).length > 0) { + const errorKeys = Object.keys(errors) as ClientFieldKey[] + if (errorKeys.length > 0) { setFieldErrors(errors) + reportError( + errorKeys.map((key) => asSentence(errors[key] ?? '')).join(' '), + errorKeys.length === 1 ? errorKeys[0] : null, + ) return } setFieldErrors({}) + const candidates = buildAttributionCandidates() const metadataParams = buildParametersFromForm(metadataDrivenParameters, parameterValues) if (!metadataParams.ok) { - setError(metadataParams.error) + reportError(metadataParams.error, attributeErrorToField(metadataParams.error, candidates)) return } - setSubmitting(true) - setError(null) - - try { - const params: Record = { ...(metadataParams.parameters ?? {}) } - // Identity-based auth must be enforceable: strip any metadata-driven - // parameter (e.g. AzureBlobStorageTarget's sas_token) that would let the - // backend authenticate a different way than the selected identity. - if (isIdentity) { - for (const parameter of metadataDrivenParameters) { - if (parameter.identity_conflicting) delete params[parameter.name] - } - } - if (hasEndpointField && endpoint) params.endpoint = endpoint - if (hasModelNameField && modelName) params.model_name = modelName - if (hasApiKeyField && !isIdentity && apiKey) params.api_key = apiKey - - if ( - (underlyingModelRequired || hasDifferentUnderlying) - && underlyingModel - && hasUnderlyingModelField - ) { - params[underlyingModelParameter?.name ?? 'underlying_model'] = underlyingModel + const params: Record = { ...(metadataParams.parameters ?? {}) } + // Identity-based auth must be enforceable: strip any metadata-driven + // parameter (e.g. AzureBlobStorageTarget's sas_token) that would let the + // backend authenticate a different way than the selected identity. + if (isIdentity) { + for (const parameter of metadataDrivenParameters) { + if (parameter.identity_conflicting) delete params[parameter.name] } + } + if (hasEndpointField && endpoint) params.endpoint = endpoint + if (hasModelNameField && modelName) params.model_name = modelName + if (hasApiKeyField && !isIdentity && apiKey) params.api_key = apiKey + + if ( + (underlyingModelRequired || hasDifferentUnderlying) + && underlyingModel + && hasUnderlyingModelField + ) { + params[underlyingModelParameter?.name ?? 'underlying_model'] = underlyingModel + } - await targetsApi.createTarget({ + const typeSelection = typeSelectionRef.current + await submitCreate( + { type: targetType, params, ...(isIdentity ? { auth_mode: 'identity' as const } : {}), - }) - - resetForm() - onCreated() - } catch (err) { - // Surface the backend's RFC 7807 `detail` (e.g. RoundRobinTarget validation - // messages) rather than the generic axios "Request failed with status code 400". - setError(toApiError(err).detail) - } finally { - setSubmitting(false) - } + }, + // Only a 400/422 can be about one field, and only if the target type hasn't changed since. + (apiError) => (apiError.status === 400 || apiError.status === 422) + && typeSelectionRef.current === typeSelection + ? attributeErrorToField(apiError.detail, candidates) + : null, + ) } + const clientFieldMessage = (field: ClientFieldKey) => ( + fieldErrors[field] ?? (error?.field === field ? error.message : undefined) + ) + const metadataFieldMessage = (name: string) => ( + error?.field === name ? error.message : undefined + ) + const targetTypeMessage = clientFieldMessage('targetType') + const endpointMessage = clientFieldMessage('endpoint') + const modelNameMessage = clientFieldMessage('modelName') + const underlyingModelMessage = clientFieldMessage('underlyingModel') + const apiKeyMessage = clientFieldMessage('apiKey') + + const validationDisabled = !targetType + || (isRoundRobin + ? selectedInnerTargets.length < 2 + || selectedInnerTargets.some((t) => !parseWeight(t.weightInput).ok) + : (endpointRequired && !endpoint) || showIdentityEndpointError) + || (modelNameRequired && !modelName) + || (underlyingModelRequired && !underlyingModel) + || (apiKeyRequired && !apiKey) + || requiredMetadataParameterMissing + return ( { if (!data.open) handleClose() }}> @@ -618,11 +737,22 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT data-testid="create-target-form" onSubmit={(e) => { e.preventDefault(); handleSubmit() }} > - {error && ( - - {error} - - )} + {/* Always mounted: screen readers only announce changes to a live region that + already exists, and MessageBar's own announcer isn't provided by this app. */} +
+ {error && ( + + {error.message} + + )} +
{typeMetadataStatus === 'loading' && ( @@ -642,8 +772,8 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT label="Target Type" hint="Each option shows what the target does, its implementation class, and how it authenticates." required - validationMessage={fieldErrors.targetType} - validationState={fieldErrors.targetType ? 'error' : 'none'} + validationMessage={describedOnly(targetTypeMessage)} + validationState={targetTypeMessage ? 'error' : 'none'} > { const next = data.optionValue if (!next) return + typeSelectionRef.current += 1 setTargetType(next) setParameterValues({}) + setError(null) + setFieldErrors({}) const nextEntry = targetTypeByName.get(next) const nextSupportsIdentity = nextEntry ? nextEntry.supported_auth_modes.includes('identity') @@ -864,8 +997,8 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT label="Endpoint URL" hint={endpointParameter?.description || undefined} required={endpointRequired} - validationMessage={fieldErrors.endpoint} - validationState={fieldErrors.endpoint ? 'error' : 'none'} + validationMessage={describedOnly(endpointMessage)} + validationState={endpointMessage ? 'error' : 'none'} > setEndpoint(data.value)} + onChange={(_, data) => { + setEndpoint(data.value) + clearClientFieldError('endpoint') + }} /> )} @@ -884,15 +1020,18 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT label="Model / Deployment Name" hint={isGitHubCopilot ? GITHUB_COPILOT_MODEL_HINT : modelNameParameter?.description || undefined} required={modelNameRequired} - validationMessage={fieldErrors.modelName} - validationState={fieldErrors.modelName ? 'error' : 'none'} + validationMessage={describedOnly(modelNameMessage)} + validationState={modelNameMessage ? 'error' : 'none'} > setModelName(data.value)} + onChange={(_, data) => { + setModelName(data.value) + clearClientFieldError('modelName') + }} /> )} @@ -925,13 +1064,16 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT label="Underlying Model" hint={underlyingModelParameter?.description || undefined} required={underlyingModelRequired} - validationMessage={fieldErrors.underlyingModel} - validationState={fieldErrors.underlyingModel ? 'error' : 'none'} + validationMessage={describedOnly(underlyingModelMessage)} + validationState={underlyingModelMessage ? 'error' : 'none'} > setUnderlyingModel(data.value)} + onChange={(_, data) => { + setUnderlyingModel(data.value) + clearClientFieldError('underlyingModel') + }} /> )} @@ -943,7 +1085,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT key={parameter.name} parameter={parameter} value={parameterValues[parameter.name] ?? ''} - disabled={submitting || identityConflict} + disabled={identityConflict} label={getParameterLabel(parameter.name)} showDefaultHint allowEmptyList @@ -951,10 +1093,8 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT extraHint={identityConflict ? 'Ignored with Identity-based authentication.' : undefined} - onChange={(name, value) => setParameterValues((current) => ({ - ...current, - [name]: value, - }))} + validationMessage={metadataFieldMessage(parameter.name)} + onChange={handleParameterChange} /> ) })} @@ -963,13 +1103,11 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT setParameterValues((current) => ({ - ...current, - [name]: value, - }))} + validationMessage={metadataFieldMessage(githubTokenParameter.name)} + onChange={handleParameterChange} /> )} @@ -1011,20 +1149,23 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT label="API Key" hint={apiKeyParameter?.description || undefined} required={apiKeyRequired} - validationMessage={fieldErrors.apiKey} - validationState={fieldErrors.apiKey ? 'error' : 'none'} + validationMessage={describedOnly(apiKeyMessage)} + validationState={apiKeyMessage ? 'error' : 'none'} > setApiKey(data.value)} + onChange={(_, data) => { + setApiKey(data.value) + clearClientFieldError('apiKey') + }} /> )} {(optionalMetadataParameters.length > 0 || customFunctionsReason) && ( -
+
Advanced settings @@ -1036,7 +1177,7 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT key={parameter.name} parameter={parameter} value={parameterValues[parameter.name] ?? ''} - disabled={submitting || identityConflict} + disabled={identityConflict} label={getParameterLabel(parameter.name)} showDefaultHint allowEmptyList @@ -1044,10 +1185,8 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT extraHint={identityConflict ? 'Ignored with Identity-based authentication.' : undefined} - onChange={(name, value) => setParameterValues((current) => ({ - ...current, - [name]: value, - }))} + validationMessage={metadataFieldMessage(parameter.name)} + onChange={handleParameterChange} /> ) })} @@ -1082,24 +1221,15 @@ export default function CreateTargetDialog({ open, onClose, onCreated, existingT - + {/* Natively disabling the focused button would drop focus to , so stay focusable while submitting. */} diff --git a/frontend/src/components/Config/TargetConfig.test.tsx b/frontend/src/components/Config/TargetConfig.test.tsx index dfb2ae948f..ce0bd370d8 100644 --- a/frontend/src/components/Config/TargetConfig.test.tsx +++ b/frontend/src/components/Config/TargetConfig.test.tsx @@ -28,7 +28,7 @@ jest.mock("./CreateTargetDialog", () => { }: { open: boolean; onClose: () => void; - onCreated: () => void; + onCreated: (isCurrentOpening: boolean) => void; }) => { if (!open) return null; return ( @@ -36,9 +36,13 @@ jest.mock("./CreateTargetDialog", () => { - + {/* A create request that an earlier, dismissed opening started (#3710). */} + ); }; @@ -567,4 +571,56 @@ describe("TargetConfig", () => { expect(screen.queryByTestId("create-dialog")).not.toBeInTheDocument(); }); + + describe("create results from an earlier opening (#3710)", () => { + it("refreshes the list but keeps the current opening when a stale create succeeds", async () => { + const user = userEvent.setup(); + mockedTargetsApi.listTargets + .mockResolvedValueOnce({ items: [], pagination: { limit: 200, has_more: false } }) + .mockResolvedValueOnce({ items: sampleTargets, pagination: { limit: 200, has_more: false } }); + + render( + + + + ); + + await waitFor(() => { + expect(screen.getByText("No Targets Configured")).toBeInTheDocument(); + }); + await user.click(screen.getByRole("button", { name: "New Target" })); + await user.click(screen.getByTestId("dialog-create-stale")); + + await waitFor(() => { + expect(screen.getAllByText("OpenAIChatTarget").length).toBeGreaterThanOrEqual(1); + }); + expect(mockedTargetsApi.listTargets).toHaveBeenCalledTimes(2); + expect(screen.getByTestId("create-dialog")).toBeInTheDocument(); + }); + + it("refreshes the list and closes the dialog when the current opening's create succeeds", async () => { + const user = userEvent.setup(); + mockedTargetsApi.listTargets + .mockResolvedValueOnce({ items: [], pagination: { limit: 200, has_more: false } }) + .mockResolvedValueOnce({ items: sampleTargets, pagination: { limit: 200, has_more: false } }); + + render( + + + + ); + + await waitFor(() => { + expect(screen.getByText("No Targets Configured")).toBeInTheDocument(); + }); + await user.click(screen.getByRole("button", { name: "New Target" })); + await user.click(screen.getByTestId("dialog-create")); + + await waitFor(() => { + expect(screen.getAllByText("OpenAIChatTarget").length).toBeGreaterThanOrEqual(1); + }); + expect(mockedTargetsApi.listTargets).toHaveBeenCalledTimes(2); + expect(screen.queryByTestId("create-dialog")).not.toBeInTheDocument(); + }); + }); }); diff --git a/frontend/src/components/Config/TargetConfig.tsx b/frontend/src/components/Config/TargetConfig.tsx index 0e175140ba..3d91504a33 100644 --- a/frontend/src/components/Config/TargetConfig.tsx +++ b/frontend/src/components/Config/TargetConfig.tsx @@ -77,8 +77,8 @@ export default function TargetConfig({ setRefetchCount(c => c + 1) }, []) - const handleTargetCreated = useCallback(() => { - setDialogOpen(false) + const handleTargetCreated = useCallback((isCurrentOpening: boolean) => { + if (isCurrentOpening) setDialogOpen(false) fetchTargets() }, [fetchTargets]) diff --git a/frontend/src/components/Config/fieldErrorAttribution.test.ts b/frontend/src/components/Config/fieldErrorAttribution.test.ts new file mode 100644 index 0000000000..33c7164ee0 --- /dev/null +++ b/frontend/src/components/Config/fieldErrorAttribution.test.ts @@ -0,0 +1,208 @@ +import { + attributeErrorToField, + getParameterLabel, + normalizeForMatch, + type AttributionCandidate, +} from "./fieldErrorAttribution"; + +const HTTP_REQUEST: AttributionCandidate = { + key: "http_request", + names: ["http_request", "Http Request"], +}; +const USE_TLS: AttributionCandidate = { + key: "use_tls", + names: ["use_tls", "Use Tls"], +}; + +describe("normalizeForMatch", () => { + it("lowercases and folds underscores, hyphens and whitespace runs into one space", () => { + expect(normalizeForMatch("HTTP_Request")).toBe("http request"); + expect(normalizeForMatch("use-tls")).toBe("use tls"); + expect(normalizeForMatch("a__b--c \t\n d")).toBe("a b c d"); + expect(normalizeForMatch("_-mixed_ -Separators-_")).toBe("mixed separators"); + }); + + it("trims leading and trailing separators", () => { + expect(normalizeForMatch(" http request ")).toBe("http request"); + }); + + it("applies NFKC normalization before matching", () => { + // Fullwidth Latin letters fold to their ASCII equivalents under NFKC. + expect(normalizeForMatch("HTTP_Request")).toBe("http request"); + // The "fi" ligature decomposes to "fi". + expect(normalizeForMatch("field")).toBe("field"); + }); + + it("returns an empty string for an empty or separator-only input", () => { + expect(normalizeForMatch("")).toBe(""); + expect(normalizeForMatch(" _- ")).toBe(""); + }); +}); + +describe("attributeErrorToField", () => { + it("attributes the issue's canonical backend error to the Http Request field", () => { + expect(attributeErrorToField("Invalid HTTP request line", [HTTP_REQUEST, USE_TLS])).toBe( + "http_request", + ); + }); + + it("matches the raw parameter name, the label, and differently separated spellings", () => { + expect(attributeErrorToField("http_request: field required", [HTTP_REQUEST])).toBe("http_request"); + expect(attributeErrorToField("Http Request is malformed", [HTTP_REQUEST])).toBe("http_request"); + expect(attributeErrorToField("HTTP-REQUEST could not be parsed", [HTTP_REQUEST])).toBe("http_request"); + expect(attributeErrorToField("'http_request' is invalid.", [HTTP_REQUEST])).toBe("http_request"); + }); + + it("matches NFKC-equivalent text in the message", () => { + expect(attributeErrorToField("Invalid HTTP request line", [HTTP_REQUEST])).toBe( + "http_request", + ); + }); + + it("returns the key once when several names of the same candidate match", () => { + expect( + attributeErrorToField("http_request (Http Request) is invalid", [HTTP_REQUEST]), + ).toBe("http_request"); + }); + + it("returns the key when two candidates share it", () => { + expect( + attributeErrorToField("Invalid HTTP request line", [ + { key: "http_request", names: ["http_request"] }, + { key: "http_request", names: ["Http Request"] }, + ]), + ).toBe("http_request"); + }); + + it("refuses to guess when two different fields are named", () => { + expect( + attributeErrorToField("http_request and use_tls are incompatible", [HTTP_REQUEST, USE_TLS]), + ).toBeNull(); + expect( + attributeErrorToField("Http Request conflicts with Use Tls", [HTTP_REQUEST, USE_TLS]), + ).toBeNull(); + }); + + it("returns null when a blocker matches, even alongside a single field match", () => { + const blocker: AttributionCandidate = { key: null, names: ["substring"] }; + expect(attributeErrorToField("substring is required", [HTTP_REQUEST, blocker])).toBeNull(); + expect( + attributeErrorToField("Invalid HTTP request line: substring is required", [HTTP_REQUEST, blocker]), + ).toBeNull(); + }); + + it("ignores a blocker that does not match", () => { + const blocker: AttributionCandidate = { key: null, names: ["substring"] }; + expect(attributeErrorToField("Invalid HTTP request line", [HTTP_REQUEST, blocker])).toBe( + "http_request", + ); + }); + + it("requires a word boundary on both sides of the name", () => { + const url: AttributionCandidate = { key: "url", names: ["url"] }; + expect(attributeErrorToField("Unexpected curly brace", [url])).toBeNull(); + expect(attributeErrorToField("urls are not allowed", [url])).toBeNull(); + expect(attributeErrorToField("Too many http requests", [HTTP_REQUEST])).toBeNull(); + expect(attributeErrorToField("url is required", [url])).toBe("url"); + expect(attributeErrorToField("Bad url.", [url])).toBe("url"); + }); + + it("treats non-ASCII letters as word characters when finding boundaries", () => { + // An ASCII-only \b would see a boundary between "caf" and "é". + const caf: AttributionCandidate = { key: "caf", names: ["caf"] }; + expect(attributeErrorToField("café is closed", [caf])).toBeNull(); + + const groesse: AttributionCandidate = { key: "groesse", names: ["größe"] }; + expect(attributeErrorToField("größe must be positive", [groesse])).toBe("groesse"); + expect(attributeErrorToField("übergrößen must be positive", [groesse])).toBeNull(); + }); + + it("matches names literally rather than as regular expressions", () => { + const dotted: AttributionCandidate = { key: "dotted", names: ["x.y"] }; + expect(attributeErrorToField("xzy failed", [dotted])).toBeNull(); + expect(attributeErrorToField("x.y failed", [dotted])).toBe("dotted"); + + const modelName: AttributionCandidate = { + key: "modelName", + names: ["model_name", "Model / Deployment Name"], + }; + expect(attributeErrorToField("Model / Deployment Name is not available", [modelName])).toBe( + "modelName", + ); + }); + + it("ignores names shorter than three characters after normalization", () => { + const id: AttributionCandidate = { key: "id", names: ["id", "_i_"] }; + expect(attributeErrorToField("id is invalid", [id])).toBeNull(); + // A short name that is ignored does not make a real match ambiguous. + expect(attributeErrorToField("id for HTTP request is invalid", [id, HTTP_REQUEST])).toBe( + "http_request", + ); + }); + + describe("raw names do not match inside longer snake_case names (loop 2, N3)", () => { + const ENDPOINT: AttributionCandidate = { key: "endpoint", names: ["endpoint", "Endpoint"] }; + const MODEL_NAME: AttributionCandidate = { + key: "modelName", + names: ["model_name", "Model / Deployment Name"], + }; + const UNDERLYING_MODEL: AttributionCandidate = { + key: "underlyingModel", + names: ["underlying_model_name", "Underlying Model"], + }; + + it("does not match endpoint inside azure_endpoint", () => { + expect(attributeErrorToField("Unknown parameter 'azure_endpoint'", [ENDPOINT])).toBeNull(); + }); + + it("does not match model_name inside underlying_model_name", () => { + expect(attributeErrorToField("underlying_model_name must be set", [MODEL_NAME])).toBeNull(); + }); + + it("attributes underlying_model_name to its own field, not also to model_name", () => { + expect( + attributeErrorToField("underlying_model_name must be set", [MODEL_NAME, UNDERLYING_MODEL]), + ).toBe("underlyingModel"); + }); + + it("still matches a raw name standing on its own", () => { + expect(attributeErrorToField("http_request must not be empty", [HTTP_REQUEST, USE_TLS])).toBe( + "http_request", + ); + expect(attributeErrorToField("Invalid HTTP request line", [HTTP_REQUEST, USE_TLS])).toBe( + "http_request", + ); + expect(attributeErrorToField("endpoint: invalid URL", [ENDPOINT])).toBe("endpoint"); + }); + }); + + it("returns null for an empty message or no candidates", () => { + expect(attributeErrorToField("", [HTTP_REQUEST])).toBeNull(); + expect(attributeErrorToField(" ", [HTTP_REQUEST])).toBeNull(); + expect(attributeErrorToField("Invalid HTTP request line", [])).toBeNull(); + }); + + it("returns null when nothing matches or a candidate has no names", () => { + expect(attributeErrorToField("Server exploded", [HTTP_REQUEST, USE_TLS])).toBeNull(); + expect(attributeErrorToField("Invalid HTTP request line", [{ key: "empty", names: [] }])).toBeNull(); + }); +}); + +describe("getParameterLabel", () => { + it("splits on underscores and capitalises each word", () => { + expect(getParameterLabel("http_request")).toBe("Http Request"); + expect(getParameterLabel("use_tls")).toBe("Use Tls"); + expect(getParameterLabel("extra_body_parameters")).toBe("Extra Body Parameters"); + }); + + it("upper-cases single-letter words and single-word names", () => { + expect(getParameterLabel("top_p")).toBe("Top P"); + expect(getParameterLabel("x")).toBe("X"); + expect(getParameterLabel("endpoint")).toBe("Endpoint"); + }); + + it("leaves the rest of each word's casing unchanged", () => { + expect(getParameterLabel("api_URL")).toBe("Api URL"); + expect(getParameterLabel("httpx_client_kwargs")).toBe("Httpx Client Kwargs"); + }); +}); diff --git a/frontend/src/components/Config/fieldErrorAttribution.ts b/frontend/src/components/Config/fieldErrorAttribution.ts new file mode 100644 index 0000000000..116291598c --- /dev/null +++ b/frontend/src/components/Config/fieldErrorAttribution.ts @@ -0,0 +1,65 @@ +/** + * Match a create-target error message to the one form field it names. + * Returns a field only when exactly one field matches; otherwise the error + * stays a form-level summary. + */ + +export interface AttributionCandidate { + /** `null` marks a name the dialog cannot mark invalid; matching it attributes nothing. */ + key: string | null + names: string[] +} + +// Shorter names ("id", "n") match too much ordinary prose. +const MIN_NAME_LENGTH = 3 + +/** `http_request` → `Http Request` */ +export function getParameterLabel(name: string): string { + return name + .split('_') + .map((word) => word.length === 1 ? word.toUpperCase() : `${word[0].toUpperCase()}${word.slice(1)}`) + .join(' ') +} + +/** `http_request`, `Http Request` and `HTTP-request` all become `http request`. */ +export function normalizeForMatch(text: string): string { + return text + .normalize('NFKC') + .toLowerCase() + .replace(/[_\-\s]+/g, ' ') + .trim() +} + +function escapeRegExp(text: string): string { + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +// Unicode-aware word boundaries (\b is ASCII-only), so `endpoint` never matches inside `azure_endpoint`. +const NOT_AFTER_WORD = '(?() + for (const candidate of candidates) { + if (!candidate.names.some((name) => namePattern(name)?.test(normalizedMessage))) continue + if (candidate.key === null) return null + matchedKeys.add(candidate.key) + } + return matchedKeys.size === 1 ? [...matchedKeys][0] : null +} diff --git a/frontend/src/components/Parameters/ParameterField.test.tsx b/frontend/src/components/Parameters/ParameterField.test.tsx index 7819b69a23..ca5617a174 100644 --- a/frontend/src/components/Parameters/ParameterField.test.tsx +++ b/frontend/src/components/Parameters/ParameterField.test.tsx @@ -1,8 +1,220 @@ -import { render, screen } from '@testing-library/react' -import userEvent from '@testing-library/user-event' -import { FluentProvider, webLightTheme } from '@fluentui/react-components' +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { FluentProvider, webLightTheme } from "@fluentui/react-components"; -import ParameterField from './ParameterField' +import type { Parameter } from "@/types"; + +import ParameterField, { type ParameterFieldProps } from "./ParameterField"; +import type { ParameterFormValue } from "./parameterForm"; + +// #3710: an external validationMessage marks the control invalid and describes it, without a second role="alert". + +const MESSAGE = "Rejected by the server for this field"; + +function renderField( + parameter: Parameter, + value: ParameterFormValue, + props: Partial = {}, +) { + const tree = (extra: Partial) => ( + + + + ); + const result = render(tree({})); + return { + ...result, + rerenderWith: (extra: Partial) => result.rerender(tree(extra)), + }; +} + +/** Concatenated text of every element the control's aria-describedby references. */ +function describedByText(element: Element): string { + const ids = (element.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean); + return ids.map((id) => document.getElementById(id)?.textContent ?? "").join(" "); +} + +function expectNoAlertRole(container: HTMLElement): void { + expect(container.querySelectorAll('[role="alert"]')).toHaveLength(0); +} + +function expectMarkedInvalid(control: Element, container: HTMLElement): void { + expect(control).toHaveAttribute("aria-invalid", "true"); + expect(describedByText(control)).toContain(MESSAGE); + expect(screen.getByText(MESSAGE)).toBeVisible(); + expectNoAlertRole(container); +} + +function expectNotMarkedInvalid(control: Element): void { + expect(control).not.toHaveAttribute("aria-invalid", "true"); + expect(screen.queryByText(MESSAGE)).not.toBeInTheDocument(); +} + +const SIMPLE_KINDS: Array<{ + kind: string; + parameter: Parameter; + value: ParameterFormValue; + tagName: string; +}> = [ + { + kind: "text", + parameter: { name: "model_id", type_name: "str", required: true }, + value: "abc", + tagName: "INPUT", + }, + { + kind: "number", + parameter: { name: "max_tokens", type_name: "int", required: false }, + value: "5", + tagName: "INPUT", + }, + { + kind: "list", + parameter: { name: "stop", type_name: "list[str]", is_list: true, required: false }, + value: "a, b", + tagName: "INPUT", + }, + { + kind: "multiline", + parameter: { name: "http_request", type_name: "str", multiline: true, required: true }, + value: "not an HTTP request", + tagName: "TEXTAREA", + }, + { + kind: "select", + parameter: { + name: "reasoning_effort", + type_name: "str", + choices: ["low", "high"], + required: false, + }, + value: "low", + tagName: "SELECT", + }, + { + kind: "boolean", + parameter: { name: "use_tls", type_name: "bool", required: false, default: "True" }, + value: "", + tagName: "SELECT", + }, +]; + +describe("ParameterField validationMessage (#3710)", () => { + it.each(SIMPLE_KINDS)( + "marks the $kind control invalid and describes it with the message, then clears it", + ({ parameter, value, tagName }) => { + const { container, rerenderWith } = renderField(parameter, value, { + validationMessage: MESSAGE, + }); + const control = screen.getByTestId(`param-${parameter.name}`); + expect(control.tagName).toBe(tagName); + + expectMarkedInvalid(control, container); + + // Regression guard: without the prop the control is not invalid. + rerenderWith({ validationMessage: undefined }); + expectNotMarkedInvalid(screen.getByTestId(`param-${parameter.name}`)); + }, + ); + + it("shows the external message on a valid JSON field and lets a local parse error win", () => { + const parameter: Parameter = { + name: "extra_body", + type_name: "dict[str, typing.Any]", + required: false, + }; + const { container, rerender } = renderField(parameter, '{"a": 1}', { + validationMessage: MESSAGE, + }); + const control = screen.getByTestId("param-extra_body"); + expectMarkedInvalid(control, container); + + // Malformed JSON: the field's own parse error is the one shown. + rerender( + + + , + ); + expect(screen.getByText("extra_body must contain valid JSON.")).toBeVisible(); + expect(screen.queryByText(MESSAGE)).not.toBeInTheDocument(); + expect(screen.getByTestId("param-extra_body")).toHaveAttribute("aria-invalid", "true"); + }); + + it("puts a structured parameter's message on the variant select only", () => { + const parameter: Parameter = { + name: "scorer", + type_name: "Scorer", + required: false, + variants: { + SubStringScorer: [{ name: "substring", type_name: "str", required: true }], + }, + }; + const { container, rerenderWith } = renderField( + parameter, + { type: "SubStringScorer", values: { substring: "x" } }, + { validationMessage: MESSAGE }, + ); + + const variantSelect = screen.getByTestId("param-scorer"); + expect(variantSelect.tagName).toBe("SELECT"); + expectMarkedInvalid(variantSelect, container); + expect(screen.getAllByText(MESSAGE)).toHaveLength(1); + + const nested = screen.getByTestId("param-scorer-substring"); + expect(nested).not.toHaveAttribute("aria-invalid", "true"); + expect(describedByText(nested)).not.toContain(MESSAGE); + + rerenderWith({ validationMessage: undefined }); + expectNotMarkedInvalid(screen.getByTestId("param-scorer")); + }); + + it("describes a multiselect group with the message and marks every checkbox invalid", () => { + const parameter: Parameter = { + name: "harm_categories", + type_name: "list[str]", + is_list: true, + choices: ["hate", "violence"], + required: false, + }; + const { container, rerenderWith } = renderField(parameter, ["hate"], { + validationMessage: MESSAGE, + }); + + const group = container.querySelector('[role="group"]'); + expect(group).not.toBeNull(); + expect(describedByText(group!)).toContain(MESSAGE); + expect(screen.getByText(MESSAGE)).toBeVisible(); + for (const choice of ["hate", "violence"]) { + expect(screen.getByTestId(`param-harm_categories-${choice}`)).toHaveAttribute( + "aria-invalid", + "true", + ); + } + expectNoAlertRole(container); + + rerenderWith({ validationMessage: undefined }); + expect(screen.queryByText(MESSAGE)).not.toBeInTheDocument(); + for (const choice of ["hate", "violence"]) { + expect(screen.getByTestId(`param-harm_categories-${choice}`)).not.toHaveAttribute( + "aria-invalid", + "true", + ); + } + }); +}); describe('ParameterField help', () => { beforeEach(() => jest.clearAllMocks()) diff --git a/frontend/src/components/Parameters/ParameterField.tsx b/frontend/src/components/Parameters/ParameterField.tsx index 9a4c9776e2..57118d6964 100644 --- a/frontend/src/components/Parameters/ParameterField.tsx +++ b/frontend/src/components/Parameters/ParameterField.tsx @@ -3,6 +3,7 @@ import { Input, Select, Textarea, + useId, } from '@fluentui/react-components' import HelpField from '@/components/HelpField' @@ -16,6 +17,7 @@ import { parseJsonObjectFormValue, type ParameterFormValue, } from './parameterForm' +import { describedOnly } from './validationMessageSlot' export interface ParameterFieldProps { parameter: Parameter @@ -34,6 +36,8 @@ export interface ParameterFieldProps { testIdPrefix?: string /** Extra guidance appended to the field's hint, e.g. explaining why it's disabled. */ extraHint?: string + /** An error the form attributes to this field. Marked invalid, not announced: the form announces it. */ + validationMessage?: string } /** @@ -57,8 +61,15 @@ export default function ParameterField({ showRequiredError = false, testIdPrefix = 'param', extraHint, + validationMessage: externalMessage, }: ParameterFieldProps) { const styles = useParameterFieldStyles() + const validationMessageId = useId('parameter-validation-') + const externalSlot = describedOnly(externalMessage) + const externalValidation = { + validationMessage: externalSlot, + validationState: externalSlot ? 'error' as const : 'none' as const, + } const kind = getParameterControlKind(parameter) const label = labelOverride ?? parameter.name const testId = `${testIdPrefix}-${parameter.name}` @@ -76,6 +87,7 @@ export default function ParameterField({ if (kind === 'structured') { const current = isStructuredParameterFormValue(value) ? value : { type: '', values: {} } + const structuredMessage = showRequiredError && !current.type ? 'Required' : externalSlot return ( <> -
+ +
{label} @@ -213,7 +241,7 @@ export default function ParameterField({ if (kind === 'select') { return ( - +