Repository navigation
fix(console): preserve VM disk selection when toggling Form and YAML - #24
IvanHunters wants to merge 1 commit into
Conversation
… VMInstance Replace the async-useEffect-based VMDiskWidget with synchronous schema-level enum injection. The widget previously called onChange from a useEffect to seed the disk name from the first available VMDisk, but a quick "+ add" followed by a YAML toggle could serialize before the effect fired, dropping the disk or producing an empty object item without name. Lift the vmdisks lookup into SchemaForm via a gated subcomponent so the K8s and tenant providers are only required when the schema actually declares a disks[] field, and inject enum plus default into disks[].name in the RJSF schema. getDefaultFormState now seeds the first disk name the moment "+ add" runs, eliminating the race for both create and edit flows. Signed-off-by: IvanHunters <xorokhotnikov@gmail.com>
📝 WalkthroughWalkthroughThis PR consolidates disk selection logic by replacing a dedicated ChangesDisk Handling Refactor
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Code Review
This pull request refactors SchemaForm to conditionally fetch Kubernetes VM disk data only when the schema contains a disks field, removing the custom VMDiskWidget and instead injecting disk names directly as an enum. This avoids unnecessary hook execution in environments or tests where disks are not used. Feedback suggests optimizing the memoization of diskNames by comparing a joined string of names to prevent unnecessary re-renders when other disk properties change.
| const diskNames = useMemo( | ||
| () => (diskList?.items ?? []).map((d) => d.metadata.name), | ||
| [diskList], | ||
| ) |
There was a problem hiding this comment.
To prevent unnecessary re-renders of the form, we can optimize the diskNames memoization. Currently, diskNames is recomputed and returns a new array reference every time diskList changes (even if the actual disk names remain the same, e.g., due to status or size updates on the disks). By memoizing a joined string of the disk names first, we can ensure that diskNames only changes its reference when the actual list of names changes.
| const diskNames = useMemo( | |
| () => (diskList?.items ?? []).map((d) => d.metadata.name), | |
| [diskList], | |
| ) | |
| const diskNamesJoined = useMemo( | |
| () => (diskList?.items ?? []).map((d) => d.metadata.name).join(","), | |
| [diskList], | |
| ) | |
| const diskNames = useMemo( | |
| () => diskNamesJoined.split(",").filter(Boolean), | |
| [diskNamesJoined], | |
| ) |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
apps/console/src/components/SchemaForm.tsx (1)
363-371: ⚡ Quick winMake the VMDisk lookup one-shot.
This query only feeds enum/default generation for the current form, so keeping the default watch behavior on needlessly churns
schemawhile the user is editing. Passwatch: falsealongside the existingenabledgate.Suggested change
const { data: diskList } = useK8sList<VMDiskRef>( { apiGroup: APPS_GROUP, apiVersion: APPS_VERSION, plural: "vmdisks", namespace: tenantNamespace ?? undefined, }, - { enabled: !!tenantNamespace }, + { enabled: !!tenantNamespace, watch: false }, )As per coding guidelines "useK8sList already handles watches via chunked-encoding. Don't poll, don't add
refetchInterval, use{ watch: false }for one-shot queries".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/console/src/components/SchemaForm.tsx` around lines 363 - 371, The VMDisk lookup is currently left as a watch and should be one-shot; update the useK8sList call (the invocation that returns diskList and uses VMDiskRef and tenantNamespace) to include watch: false in the options object alongside the existing enabled gate so the query runs once for enum/default generation and doesn’t keep watching/updating the schema while the user edits the form.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/console/src/components/SchemaForm.tsx`:
- Around line 136-179: The visitor currently only descends into
object.properties so nested array schemas (e.g., disks inside an items) are
never processed; update the visit function (and the analogous helper around
lines 185-204) to also recurse into array.items when items is an object: when
you detect an array node (node.type === "array" or value.type === "array") and
node.items is an object, call visit(node.items) (or visit(value.items)) and if
the returned items differ, set the updated items back on the node/value and mark
changed so the modified node is returned; do this in addition to the existing
properties traversal and still avoid recursing into oneOf/anyOf/allOf per the
guideline.
- Around line 373-380: The diskNames array is not sorted so diskNames[0] can
vary; update the useMemo that computes diskNames (the const diskNames =
useMemo(...) block) to produce a stable, sorted list (e.g., sort the mapped
names alphabetically or by desired comparator) before passing it into
injectDiskEnum; ensure the dependency remains [diskList] and that
injectDiskEnum(props.sanitizedSchema, diskNames) receives the sorted diskNames
so default selection is stable.
- Around line 136-152: The walker uses many explicit any types (e.g., function
visit signature, Record<string, any>, and casts like value as any and (schema as
any).properties); replace these with safer typings by changing visit(node: any):
any to visit(node: unknown): unknown (or declare a small local interface like
SchemaNode/SchemaObject with optional properties: properties, type, items,
required, etc.), use type guards and instanceof/typeof checks to narrow node
before accessing properties, replace Record<string, any> with Record<string,
unknown> (or Record<string, SchemaNode>), and cast to the local interface (e.g.,
const props = (node as SchemaObject).properties) only after narrowing; update
usages like disksField and (schema).properties to the local interface types so
no explicit any or as any remains.
---
Nitpick comments:
In `@apps/console/src/components/SchemaForm.tsx`:
- Around line 363-371: The VMDisk lookup is currently left as a watch and should
be one-shot; update the useK8sList call (the invocation that returns diskList
and uses VMDiskRef and tenantNamespace) to include watch: false in the options
object alongside the existing enabled gate so the query runs once for
enum/default generation and doesn’t keep watching/updating the schema while the
user edits the form.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 2429949a-46a8-4356-a29a-24936da39988
📒 Files selected for processing (4)
apps/console/src/components/SchemaForm.tsxapps/console/src/components/VMDiskWidget.tsxapps/console/src/components/rjsf-templates.tsxapps/console/src/lib/tenant-context.tsx
💤 Files with no reviewable changes (2)
- apps/console/src/components/VMDiskWidget.tsx
- apps/console/src/components/rjsf-templates.tsx
| const visit = (node: any): any => { | ||
| if (!node || typeof node !== "object") return node | ||
| const props = node.properties | ||
| if (!props || typeof props !== "object") return node | ||
| const nextProps: Record<string, any> = { ...props } | ||
| let changed = false | ||
| for (const [key, value] of Object.entries(props)) { | ||
| if ( | ||
| fieldSchema.type === "array" && | ||
| fieldSchema.items?.type === "object" && | ||
| fieldSchema.items?.properties?.name | ||
| key === "disks" && | ||
| value && | ||
| typeof value === "object" && | ||
| (value as any).type === "array" && | ||
| (value as any).items?.type === "object" && | ||
| (value as any).items?.properties?.name?.type === "string" | ||
| ) { | ||
| // Add VMDiskWidget to the "name" field inside array items | ||
| result[key] = { | ||
| ...result[key], | ||
| const disksField = value as any | ||
| const itemRequired: string[] = Array.isArray(disksField.items.required) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="apps/console/src/components/SchemaForm.tsx"
# Show the exact sections referenced by the review comment
sed -n '110,170p' "$FILE" | nl -ba | sed -n '1,120p'
echo "-----"
sed -n '170,230p' "$FILE" | nl -ba | sed -n '1,120p'
# Grep for explicit "any" in the file (limited output)
echo "-----"
rg -n ":\s*any\b|=\s*any\b|<\s*any\s*>|no-explicit-any|any\s*\)" "$FILE" || true
# Also show any uses of "as any" in the nearby region
echo "-----"
sed -n '120,230p' "$FILE" | rg -n "as any|:\s*any\b" || trueRepository: cozystack/cozystack-ui
Length of output: 109
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="apps/console/src/components/SchemaForm.tsx"
# Helper: print numbered line ranges
print_range() {
local start="$1" end="$2"
awk -v s="$start" -v e="$end" 'NR>=s && NR<=e {printf "%6d\t%s\n", NR, $0}' "$FILE"
}
echo "=== Range 120-170 ==="
print_range 120 170
echo "=== Range 170-230 ==="
print_range 170 230
echo "=== Search for explicit any patterns ==="
# Most relevant: explicit type annotations, casts, and generic any
rg -n --no-heading --color never ":\s*any\b|=\s*any\b|<\s*any\s*>|\bas any\b|no-explicit-any|no-explicit-any|`@typescript-eslint/no-explicit-any`" "$FILE" || true
echo "=== Search for 'as any' in file (all occurrences) ==="
rg -n --no-heading --color never "as any" "$FILE" || trueRepository: cozystack/cozystack-ui
Length of output: 7435
Remove explicit any in SchemaForm schema walkers (type-safe unknown/local interfaces needed)
apps/console/src/components/SchemaForm.tsx introduces any in the walkers:
- Lines 136-152:
const visit = (node: any): any,Record<string, any>, and severalas anycasts. - Lines 187-200:
(schema as any).propertiesandvalue as anycasts.
Replace with unknown + narrowing (or a small local schema-node interface) to satisfy the “No any types” rule and avoid @typescript-eslint/no-explicit-any lint failures.
🧰 Tools
🪛 ESLint
[error] 136-136: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 136-136: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 140-140: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 147-147: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 148-148: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 149-149: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 151-151: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/console/src/components/SchemaForm.tsx` around lines 136 - 152, The
walker uses many explicit any types (e.g., function visit signature,
Record<string, any>, and casts like value as any and (schema as
any).properties); replace these with safer typings by changing visit(node: any):
any to visit(node: unknown): unknown (or declare a small local interface like
SchemaNode/SchemaObject with optional properties: properties, type, items,
required, etc.), use type guards and instanceof/typeof checks to narrow node
before accessing properties, replace Record<string, any> with Record<string,
unknown> (or Record<string, SchemaNode>), and cast to the local interface (e.g.,
const props = (node as SchemaObject).properties) only after narrowing; update
usages like disksField and (schema).properties to the local interface types so
no explicit any or as any remains.
| const visit = (node: any): any => { | ||
| if (!node || typeof node !== "object") return node | ||
| const props = node.properties | ||
| if (!props || typeof props !== "object") return node | ||
| const nextProps: Record<string, any> = { ...props } | ||
| let changed = false | ||
| for (const [key, value] of Object.entries(props)) { | ||
| if ( | ||
| fieldSchema.type === "array" && | ||
| fieldSchema.items?.type === "object" && | ||
| fieldSchema.items?.properties?.name | ||
| key === "disks" && | ||
| value && | ||
| typeof value === "object" && | ||
| (value as any).type === "array" && | ||
| (value as any).items?.type === "object" && | ||
| (value as any).items?.properties?.name?.type === "string" | ||
| ) { | ||
| // Add VMDiskWidget to the "name" field inside array items | ||
| result[key] = { | ||
| ...result[key], | ||
| const disksField = value as any | ||
| const itemRequired: string[] = Array.isArray(disksField.items.required) | ||
| ? disksField.items.required | ||
| : [] | ||
| const nameRequired = itemRequired.includes("name") | ||
| nextProps[key] = { | ||
| ...disksField, | ||
| items: { | ||
| ...(result[key] as any)?.items, | ||
| name: { | ||
| ...((result[key] as any)?.items?.name || {}), | ||
| "ui:widget": "VMDiskWidget", | ||
| ...disksField.items, | ||
| properties: { | ||
| ...disksField.items.properties, | ||
| name: { | ||
| ...disksField.items.properties.name, | ||
| enum: [...diskNames], | ||
| ...(nameRequired ? { default: diskNames[0] } : {}), | ||
| }, | ||
| }, | ||
| }, | ||
| } | ||
| changed = true | ||
| continue | ||
| } | ||
| const visited = visit(value) | ||
| if (visited !== value) { | ||
| nextProps[key] = visited | ||
| changed = true | ||
| } | ||
| } else if (typeof value === "object" && (value as any).properties) { | ||
| // Recursively process nested objects | ||
| result[key] = addVMDiskWidgets(value as RJSFSchema, result[key] as UiSchema) | ||
| } | ||
| return changed ? { ...node, properties: nextProps } : node |
There was a problem hiding this comment.
Recurse through items as well as properties.
These walkers stop at object properties, so a schema that reaches disks through an array item never triggers SchemaFormWithDisks and never gets the enum/default injection. Please descend into items in both helpers so the fix applies to nested array shapes too.
As per coding guidelines "For form widget binding, walk both properties and items for arrays, but do not walk oneOf/anyOf/allOf unless a real chart needs it".
Also applies to: 185-204
🧰 Tools
🪛 ESLint
[error] 136-136: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 136-136: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 140-140: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 147-147: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 148-148: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 149-149: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
[error] 151-151: Unexpected any. Specify a different type.
(@typescript-eslint/no-explicit-any)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/console/src/components/SchemaForm.tsx` around lines 136 - 179, The
visitor currently only descends into object.properties so nested array schemas
(e.g., disks inside an items) are never processed; update the visit function
(and the analogous helper around lines 185-204) to also recurse into array.items
when items is an object: when you detect an array node (node.type === "array" or
value.type === "array") and node.items is an object, call visit(node.items) (or
visit(value.items)) and if the returned items differ, set the updated items back
on the node/value and mark changed so the modified node is returned; do this in
addition to the existing properties traversal and still avoid recursing into
oneOf/anyOf/allOf per the guideline.
| const diskNames = useMemo( | ||
| () => (diskList?.items ?? []).map((d) => d.metadata.name), | ||
| [diskList], | ||
| ) | ||
|
|
||
| const schema = useMemo<RJSFSchema>( | ||
| () => injectDiskEnum(props.sanitizedSchema, diskNames), | ||
| [props.sanitizedSchema, diskNames], |
There was a problem hiding this comment.
Sort diskNames before using the first entry as the default.
diskNames[0] becomes the implicit selection for required disk fields, but Kubernetes list order is not stable. Without a sort, the preselected disk can flip between loads.
Suggested change
const diskNames = useMemo(
- () => (diskList?.items ?? []).map((d) => d.metadata.name),
+ () =>
+ (diskList?.items ?? [])
+ .map((d) => d.metadata.name)
+ .sort((a, b) => a.localeCompare(b)),
[diskList],
)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/console/src/components/SchemaForm.tsx` around lines 373 - 380, The
diskNames array is not sorted so diskNames[0] can vary; update the useMemo that
computes diskNames (the const diskNames = useMemo(...) block) to produce a
stable, sorted list (e.g., sort the mapped names alphabetically or by desired
comparator) before passing it into injectDiskEnum; ensure the dependency remains
[diskList] and that injectDiskEnum(props.sanitizedSchema, diskNames) receives
the sorted diskNames so default selection is stable.
Summary
name(or drop it entirely asdisks: [])useEffectautoselect inVMDiskWidgetwith synchronous RJSF schema-level enum injection/console/new/vm-instance) and edit (/console/vminstances/<name>/edit) flowsRoot cause
VMDiskWidgetpopulated the requirednameviauseEffect(() => onChange(disks[0].metadata.name)). The native<select>visually showed the first option as a browser default while React state stayed empty until the effect fired one tick later. Toggling to YAML before the effect ran serialized the disk as{}(missing requiredname) or normalized it out of the array entirely.Fix
injectDiskEnumrewritesproperties.disks.items.properties.nameto carry anenum(available VMDisk names) and adefault(first name) whennameis required. RJSF'sgetDefaultFormStatethen seeds the disk name synchronously the moment+ addruns.useK8sList<VMDisk>is moved out of the per-field widget into a gated subcomponent ofSchemaForm, so the K8s and tenant providers are only required when the schema actually declaresdisks[]. Other schemas (postgres, redis, etc.) skip the lookup entirely, and isolated SchemaForm tests render without providers.VMDiskWidget.tsxis removed; the nativeSelectWidgethandles the enum case correctly.useOptionalTenantContextis added so consumers that may run outside a tenant scope can probe context without throwing.Test plan
pnpm --filter @cozystack/console typecheckcleanpnpm --filter @cozystack/console test209/209 passed+ adddisk, switch to YAML (~100ms delay), `disks: - name: ` presentSummary by CodeRabbit
Release Notes