diff --git a/packages/system/dashboard/images/console/CLAUDE.md b/packages/system/dashboard/images/console/CLAUDE.md index c7b04a3b3..b5655567c 100644 --- a/packages/system/dashboard/images/console/CLAUDE.md +++ b/packages/system/dashboard/images/console/CLAUDE.md @@ -109,8 +109,7 @@ schema). The pipeline in `apps/console/src/components/SchemaForm.tsx`: - credential-shaped fields (`password`, `*token`, `*accessKey`, …) → `SensitiveStringWidget` — see `lib/sensitive-fields.ts` and its tests for the exact matching rules. -4. Defaults are emitted to the parent once per schema via `getDefaultFormState` - so the first submit always carries a populated spec. +4. Application forms use server-prepared values: the order page asks `dryRunCreate` once when it opens and starts the form from the returned spec (no previews on edits), and editing starts with the saved API response. In `defaulting="server"` mode, schema defaults are stripped at every depth and RJSF cannot populate defaults, a field with a schema default is not required inside an object because the server fills it (array rows and dictionary values keep their requirements), while a dynamic option list still selects its server-marked default when the field is empty, except after a failed preview (`autoSelectDefaults` off), where the empty field stays empty and the API applies the platform's default. A cleared plain text input leaves its key out, so on create the API fills it again from the defaults, unless that empties a nested object: the form then sends `{}` for it, which stops installation defaults for that object. A dropdown's None and a sensitive field are written as `""`. Other resource forms retain their existing schema-default mode. When you add a new widget binding: diff --git a/packages/system/dashboard/images/console/apps/console/src/components/AdditionalPropertiesField.tsx b/packages/system/dashboard/images/console/apps/console/src/components/AdditionalPropertiesField.tsx index e2c0371eb..4aa2a74d0 100644 --- a/packages/system/dashboard/images/console/apps/console/src/components/AdditionalPropertiesField.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/components/AdditionalPropertiesField.tsx @@ -5,6 +5,7 @@ import Form from "@rjsf/core" import validator from "@rjsf/validator-ajv8" import { customTemplates, customWidgets } from "./rjsf-registry.ts" import { addDynamicOptionWidgets } from "../lib/dynamic-options.ts" +import { serverFormStateBehavior } from "../lib/server-form.ts" export function AdditionalPropertiesField(props: FieldProps) { const { schema, formData, onChange, readonly, disabled, name, required, idSchema } = @@ -17,6 +18,7 @@ export function AdditionalPropertiesField(props: FieldProps) { [schema.additionalProperties], ) const keys = Object.keys(formData || {}) + const serverDefaults = props.formContext?.serverDefaults === true // The nested
renders its own subtree, so it needs its own uiSchema to // bind x-cozystack-options fields (e.g. nodeGroups.*.instanceType) to the @@ -41,8 +43,8 @@ export function AdditionalPropertiesField(props: FieldProps) { return } - // Initialize with default value from schema - const defaultValue = itemSchema.type === "object" ? {} : itemSchema.default ?? "" + // Server mode adds an empty entry and leaves defaults to the API on create. + const defaultValue = itemSchema.type === "object" ? {} : serverDefaults ? "" : itemSchema.default ?? "" onChange({ ...formData, [newKey]: defaultValue }) setNewKey("") } @@ -98,9 +100,12 @@ export function AdditionalPropertiesField(props: FieldProps) { schema={itemSchema} uiSchema={itemUiSchema} formData={formData[key]} + formContext={props.formContext} + experimental_defaultFormStateBehavior={serverDefaults ? serverFormStateBehavior : undefined} validator={validator} templates={templatesWithoutSubmit} widgets={customWidgets} + fields={props.registry.fields} onChange={(e) => handleValueChange(key, e.formData)} disabled={isReadonly} liveValidate={false} diff --git a/packages/system/dashboard/images/console/apps/console/src/components/DynamicOptionsWidget.test.tsx b/packages/system/dashboard/images/console/apps/console/src/components/DynamicOptionsWidget.test.tsx index 9047e24fb..f84f51182 100644 --- a/packages/system/dashboard/images/console/apps/console/src/components/DynamicOptionsWidget.test.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/components/DynamicOptionsWidget.test.tsx @@ -61,7 +61,7 @@ function clientWith(result: ListResult) { const NEVER_RESOLVES = () => new Promise>(() => {}) -function makeProps(overrides: Partial = {}, source = "storageclass"): WidgetProps { +function makeProps(overrides: Omit, "registry"> & { registry?: Partial } = {}, source = "storageclass"): WidgetProps { const base = { id: "field", name: "field", @@ -88,6 +88,56 @@ function makeProps(overrides: Partial = {}, source = "storageclass" } describe("DynamicOptionsWidget", () => { + it.each(["", null, undefined])("selects the default item in server mode when the prepared value is empty %s", async (value) => { + const onChange = vi.fn() + renderWithK8sProvider( + , + { client: clientWith(list(option("storageclass", [{ value: "standard", default: true }]))) }, + ) + await waitFor(() => expect(onChange).toHaveBeenCalledWith("standard")) + expect(onChange).toHaveBeenCalledTimes(1) + }) + + it("keeps a value the server prepared, such as an installation default, over the default item", async () => { + const onChange = vi.fn() + renderWithK8sProvider( + , + { client: clientWith(list(option("storageclass", [{ value: "standard", default: true }, { value: "installed" }]))) }, + ) + await screen.findByRole("option", { name: "standard" }) + expect(onChange).not.toHaveBeenCalled() + }) + + it("leaves the field empty when the form did not start from the server's values", async () => { + const onChange = vi.fn() + renderWithK8sProvider( + , + { client: clientWith(list(option("storageclass", [{ value: "standard", default: true }, { value: "replicated" }]))) }, + ) + await screen.findByRole("option", { name: "standard" }) + expect(onChange).not.toHaveBeenCalled() + expect(screen.getByRole("combobox")).toHaveValue("") + }) + + it("keeps None as an explicit empty string after clearing installation defaults", async () => { + const onChange = vi.fn() + function Harness() { + const [value, setValue] = useState("installed") + return { onChange(next); setValue(next) }, + registry: { formContext: { serverDefaults: true } }, + })} /> + } + renderWithK8sProvider(, { + client: clientWith(list(option("storageclass", [{ value: "standard", default: true }]))), + }) + await screen.findByRole("option", { name: "standard" }) + fireEvent.change(screen.getByRole("combobox"), { target: { value: "" } }) + expect(onChange.mock.calls).toEqual([[""]]) + expect(screen.getByRole("combobox")).toHaveValue("") + }) + it("auto-selects the server-marked default item exactly once when no value is set", async () => { const onChange = vi.fn() renderWithK8sProvider( diff --git a/packages/system/dashboard/images/console/apps/console/src/components/DynamicOptionsWidget.tsx b/packages/system/dashboard/images/console/apps/console/src/components/DynamicOptionsWidget.tsx index f4e1f7fe5..718e78d01 100644 --- a/packages/system/dashboard/images/console/apps/console/src/components/DynamicOptionsWidget.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/components/DynamicOptionsWidget.tsx @@ -42,6 +42,8 @@ export function DynamicOptionsWidget(props: WidgetProps) { ]?.source const rootFormData = (registry?.formContext as { rootFormData?: unknown })?.rootFormData + const serverDefaults = !!registry?.formContext?.serverDefaults + const autoSelectDefaults = registry?.formContext?.autoSelectDefaults !== false const { name: source, parameterised } = resolveSource(rawSource, rootFormData) // A parameterised source is deliberately absent from the Option list — it @@ -81,14 +83,15 @@ export function DynamicOptionsWidget(props: WidgetProps) { // on initial load. The ref latches after the first auto-default and is never // reset, so deliberately clearing an optional field sticks — re-arming it // here would let the effect immediately re-apply the default and make the - // field impossible to clear. + // field impossible to clear. A form that did not start from the server's + // values leaves an empty field alone, so the API applies its own default. const hasAutoDefaulted = useRef(false) useEffect(() => { - if (!hasAutoDefaulted.current && !value && defaultItem && !isLoading) { + if (autoSelectDefaults && !hasAutoDefaulted.current && !value && defaultItem && !isLoading) { hasAutoDefaulted.current = true onChange(defaultItem.value) } - }, [value, defaultItem, isLoading, onChange]) + }, [autoSelectDefaults, value, defaultItem, isLoading, onChange]) const placeholder = isLoading ? "Loading..." @@ -106,7 +109,10 @@ export function DynamicOptionsWidget(props: WidgetProps) { control associated with its label, regardless of state", () => { renderWithLabel(makeProps({ value: "super-secret" })) diff --git a/packages/system/dashboard/images/console/apps/console/src/components/SensitiveStringWidget.tsx b/packages/system/dashboard/images/console/apps/console/src/components/SensitiveStringWidget.tsx index 26e8f6185..888fad21e 100644 --- a/packages/system/dashboard/images/console/apps/console/src/components/SensitiveStringWidget.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/components/SensitiveStringWidget.tsx @@ -14,6 +14,7 @@ const TOGGLE_CLASS = export function SensitiveStringWidget(props: WidgetProps) { const { id, value, onChange, required, disabled, readonly, autofocus, placeholder } = props + const serverDefaults = !!props.registry?.formContext?.serverDefaults const [revealed, setRevealed] = useState(false) const stringValue = typeof value === "string" ? value : "" @@ -36,9 +37,11 @@ export function SensitiveStringWidget(props: WidgetProps) { onChange={(event) => { // Empty string is coerced to undefined so the surrounding form // drops the key from the spec entirely on clear, matching the - // convention used by the other custom widgets in this folder. + // convention used by the other custom widgets in this folder. When + // the server owns defaults an omitted key gets its default back, so + // the empty string is kept as the user's explicit value. const next = event.target.value - onChange(next === "" ? undefined : next) + onChange(next === "" && !serverDefaults ? undefined : next) }} className={INPUT_CLASS} /> diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/server-form.test.ts b/packages/system/dashboard/images/console/apps/console/src/lib/server-form.test.ts new file mode 100644 index 000000000..25ceb42cc --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/lib/server-form.test.ts @@ -0,0 +1,54 @@ +import { describe, it, expect } from "vitest" +import { withoutSchemaDefaults } from "./server-form.ts" + +describe("server form schema", () => { + it("removes defaults at every form depth while preserving properties and the original schema", () => { + const leaf = { type: "string", default: "client" } + const original = { type: "object", default: {}, properties: { + default: leaf, + rows: { type: "array", items: leaf }, + map: { type: "object", additionalProperties: leaf }, + } } + expect(withoutSchemaDefaults(original)).toEqual({ type: "object", properties: { + default: { type: "string" }, + rows: { type: "array", items: { type: "string" } }, + map: { type: "object", additionalProperties: { type: "string" } }, + } }) + expect(leaf.default).toBe("client") + expect(original.default).toEqual({}) + }) + + it("does not require a field that has a default, because the server fills it", () => { + const original = { type: "object", required: ["enabled", "name"], properties: { + enabled: { type: "boolean", default: false }, + name: { type: "string" }, + nested: { type: "object", required: ["size"], properties: { size: { type: "integer", default: 1 } } }, + } } + expect(withoutSchemaDefaults(original)).toEqual({ type: "object", required: ["name"], properties: { + enabled: { type: "boolean" }, + name: { type: "string" }, + nested: { type: "object", properties: { size: { type: "integer" } } }, + } }) + expect(original.required).toEqual(["enabled", "name"]) + }) + + it("keeps the requirements of array rows and dictionary values, which the server does not complete", () => { + const row = { type: "object", required: ["storage", "name"], properties: { + storage: { type: "string", default: "10Gi" }, + name: { type: "string" }, + } } + const kept = { type: "object", required: ["storage", "name"], properties: { + storage: { type: "string" }, + name: { type: "string" }, + } } + expect(withoutSchemaDefaults({ type: "object", properties: { + rows: { type: "array", items: row }, + map: { type: "object", additionalProperties: row }, + nested: { type: "object", properties: { rows: { type: "array", items: row } } }, + } })).toEqual({ type: "object", properties: { + rows: { type: "array", items: kept }, + map: { type: "object", additionalProperties: kept }, + nested: { type: "object", properties: { rows: { type: "array", items: kept } } }, + } }) + }) +}) diff --git a/packages/system/dashboard/images/console/apps/console/src/lib/server-form.ts b/packages/system/dashboard/images/console/apps/console/src/lib/server-form.ts new file mode 100644 index 000000000..b3adcda7e --- /dev/null +++ b/packages/system/dashboard/images/console/apps/console/src/lib/server-form.ts @@ -0,0 +1,45 @@ +import type { Experimental_DefaultFormStateBehavior } from "@rjsf/utils" + +export function isObject(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value) +} + +export function withoutSchemaDefaults(schema: unknown, inReplaced = false): unknown { + if (!isObject(schema)) return schema + const result = { ...schema } + delete result.default + // Inside an object the server fills a field that has a default, so the form need + // not require it. An array row or a dictionary value is stored as typed, with no + // defaults added, so its requirements stay. + if (!inReplaced && isObject(result.properties) && Array.isArray(result.required)) { + const properties = result.properties + const required = result.required.filter((name) => !(isObject(properties[name]) && "default" in properties[name])) + if (required.length > 0) result.required = required + else delete result.required + } + for (const key of ["properties", "patternProperties", "definitions", "$defs", "dependentSchemas"]) { + if (isObject(result[key])) { + result[key] = Object.fromEntries(Object.entries(result[key]).map( + ([name, child]) => [name, withoutSchemaDefaults(child, inReplaced)], + )) + } + } + for (const key of ["items", "additionalProperties", "additionalItems"]) { + if (isObject(result[key])) result[key] = withoutSchemaDefaults(result[key], true) + else if (Array.isArray(result[key])) result[key] = result[key].map((child) => withoutSchemaDefaults(child, true)) + } + if (Array.isArray(result.prefixItems)) result.prefixItems = result.prefixItems.map((child) => withoutSchemaDefaults(child, true)) + for (const key of ["not", "if", "then", "else"]) { + if (isObject(result[key])) result[key] = withoutSchemaDefaults(result[key], inReplaced) + } + for (const key of ["oneOf", "anyOf", "allOf"]) { + if (Array.isArray(result[key])) result[key] = result[key].map((child) => withoutSchemaDefaults(child, inReplaced)) + } + return result +} + +export const serverFormStateBehavior: Experimental_DefaultFormStateBehavior = { + emptyObjectFields: "skipDefaults", + arrayMinItems: { populate: "never" }, + constAsDefaults: "never", +} diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/ApplicationOrderPage.freeform.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/ApplicationOrderPage.freeform.test.tsx index fb0e7d1fb..356f748af 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/ApplicationOrderPage.freeform.test.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/ApplicationOrderPage.freeform.test.tsx @@ -6,6 +6,7 @@ import { MemoryRouter } from "react-router" const h = vi.hoisted(() => ({ create: vi.fn(), update: vi.fn(), + client: { dryRunCreate: vi.fn() }, ad: { spec: { application: { @@ -38,6 +39,7 @@ vi.mock("../lib/app-definitions.ts", () => ({ vi.mock("@cozystack/k8s-client", () => ({ useK8sCreate: () => ({ mutateAsync: h.create, isPending: false }), useK8sUpdate: () => ({ mutateAsync: h.update, isPending: false }), + useK8sClient: () => h.client, K8sApiError: class extends Error {}, })) vi.mock("../components/YamlEditor.tsx", () => ({ @@ -51,12 +53,13 @@ describe("ApplicationOrderPage free-form objects", () => { beforeEach(() => { h.create.mockReset().mockResolvedValue({}) h.update.mockReset().mockResolvedValue({}) + h.client.dryRunCreate.mockReset().mockImplementation(async (_g, _v, _p, body: unknown) => body) }) it("sends nested objects on create after a form/YAML round trip", async () => { const user = userEvent.setup() render() - await user.type(screen.getByPlaceholderText("nats"), "demo") + await user.type(await screen.findByPlaceholderText("nats"), "demo") fireEvent.change(screen.getByLabelText("merge"), { target: { value: JSON.stringify(merge) } }) fireEvent.change(screen.getByLabelText("resolver"), { target: { value: '{"type":"full"}' } }) await user.click(screen.getByRole("button", { name: /^yaml$/i })) @@ -81,7 +84,9 @@ describe("ApplicationOrderPage free-form objects", () => { it.each([false, true])("blocks invalid JSON from the API in edit mode %s", async (edit) => { const user = userEvent.setup() render() - if (!edit) await user.type(screen.getByPlaceholderText("nats"), "demo") + if (!edit) { + await user.type(await screen.findByPlaceholderText("nats"), "demo") + } fireEvent.change(screen.getByLabelText("merge"), { target: { value: "{" } }) await user.click(screen.getByRole("button", { name: edit ? /^save$/i : /^deploy$/i })) expect(h.create).not.toHaveBeenCalled() diff --git a/packages/system/dashboard/images/console/apps/console/src/routes/ApplicationOrderPage.test.tsx b/packages/system/dashboard/images/console/apps/console/src/routes/ApplicationOrderPage.test.tsx index 8993974ac..2525b1864 100644 --- a/packages/system/dashboard/images/console/apps/console/src/routes/ApplicationOrderPage.test.tsx +++ b/packages/system/dashboard/images/console/apps/console/src/routes/ApplicationOrderPage.test.tsx @@ -1,105 +1,382 @@ import { forwardRef, useImperativeHandle } from "react" import { describe, it, expect, vi, beforeEach } from "vitest" -import { render, screen } from "@testing-library/react" +import { act, fireEvent, render, screen } from "@testing-library/react" import userEvent from "@testing-library/user-event" import { MemoryRouter } from "react-router" +import yaml from "js-yaml" +import type { ApplicationInstance } from "@cozystack/types" -// The Deploy button bypasses RJSF; in form mode the gate calls -// SchemaForm.validate(), in YAML mode it is skipped. Mock SchemaForm so the -// test drives that boolean directly, and YamlEditor so Monaco stays out. const h = vi.hoisted(() => ({ - validateReturn: true, - createMutateAsync: vi.fn(), - updateMutateAsync: vi.fn(), - ad: { - spec: { - application: { - kind: "VirtualMachine", - plural: "virtualmachines", - singular: "virtualmachine", - openAPISchema: JSON.stringify({ type: "object", properties: {} }), - }, - dashboard: {}, - }, - }, -})) - -vi.mock("../lib/tenant-context.tsx", () => ({ - useTenantContext: () => ({ tenantNamespace: "tenant-test" }), + validate: true, create: vi.fn(), update: vi.fn(), client: { dryRunCreate: vi.fn() }, + tenant: { ns: "tenant-test" as string | null, loading: false }, + ad: { spec: { application: { kind: "Widget", plural: "widgets", singular: "widget", + openAPISchema: JSON.stringify({ type: "object", properties: { setting: { type: "string", default: "client-schema" } } }), + }, dashboard: {} } }, })) +vi.mock("../lib/tenant-context.tsx", () => ({ useTenantContext: () => ({ tenantNamespace: h.tenant.ns, isLoading: h.tenant.loading }) })) vi.mock("../lib/app-definitions.ts", () => ({ useApplicationDefinition: () => ({ data: h.ad, isLoading: false, error: null }), - appDisplayName: () => "Virtual Machine", - iconDataUrl: () => null, + appDisplayName: () => "Widget", iconDataUrl: () => null, })) vi.mock("@cozystack/k8s-client", () => ({ - useK8sCreate: () => ({ mutateAsync: h.createMutateAsync, isPending: false }), - useK8sUpdate: () => ({ mutateAsync: h.updateMutateAsync, isPending: false }), - K8sApiError: class K8sApiError extends Error {}, + useK8sClient: () => h.client, + useK8sCreate: () => ({ mutateAsync: h.create, isPending: false }), + useK8sUpdate: () => ({ mutateAsync: h.update, isPending: false }), + K8sApiError: class extends Error {}, })) vi.mock("../components/SchemaForm.tsx", () => ({ - SchemaForm: forwardRef<{ validate: () => boolean }, Record>( - function MockSchemaForm(_props, ref) { - useImperativeHandle(ref, () => ({ validate: () => h.validateReturn })) - return null + SchemaForm: forwardRef<{ validate: () => boolean }, { formData: unknown; onChange: (value: unknown) => void; defaulting: string; autoSelectDefaults?: boolean }>( + function MockSchemaForm(props, ref) { + useImperativeHandle(ref, () => ({ validate: () => h.validate })) + return