Skip to content
This repository was archived by the owner on Jun 26, 2026. It is now read-only.

fix(console): preserve VM disk selection when toggling Form and YAML - #24

Closed
IvanHunters wants to merge 1 commit into
mainfrom
fix/vminstance-disk-form-yaml-race
Closed

IvanHunters wants to merge 1 commit into
mainfrom
fix/vminstance-disk-form-yaml-race

Conversation

@IvanHunters

@IvanHunters IvanHunters commented Jun 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Adding a VM disk and quickly toggling Form -> YAML used to serialize the disk without name (or drop it entirely as disks: [])
  • Replace the async-useEffect autoselect in VMDiskWidget with synchronous RJSF schema-level enum injection
  • Affects both create (/console/new/vm-instance) and edit (/console/vminstances/<name>/edit) flows

Root cause

VMDiskWidget populated the required name via useEffect(() => 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 required name) or normalized it out of the array entirely.

Fix

  • injectDiskEnum rewrites properties.disks.items.properties.name to carry an enum (available VMDisk names) and a default (first name) when name is required. RJSF's getDefaultFormState then seeds the disk name synchronously the moment + add runs.
  • useK8sList<VMDisk> is moved out of the per-field widget into a gated subcomponent of SchemaForm, so the K8s and tenant providers are only required when the schema actually declares disks[]. Other schemas (postgres, redis, etc.) skip the lookup entirely, and isolated SchemaForm tests render without providers.
  • VMDiskWidget.tsx is removed; the native SelectWidget handles the enum case correctly.
  • useOptionalTenantContext is added so consumers that may run outside a tenant scope can probe context without throwing.

Test plan

  • pnpm --filter @cozystack/console typecheck clean
  • pnpm --filter @cozystack/console test 209/209 passed
  • Manual: + add disk, switch to YAML (~100ms delay), `disks: - name: ` present
  • Manual: open edit page for VMInstance with existing disk, switch to YAML, disk preserved
  • Tenant with zero VMDisks: name field falls back to plain string input (verify in dev cluster)

Summary by CodeRabbit

Release Notes

  • Refactor
    • Improved handling of disk-related fields in configuration schemas with enhanced disk enumeration and intelligent default initialization for new disk entries.
    • Streamlined disk selection form behavior to provide better validation and user experience when managing VM disks in configurations.

… 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>
@coderabbitai

coderabbitai Bot commented Jun 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR consolidates disk selection logic by replacing a dedicated VMDiskWidget with schema-level enum injection. The refactor conditionally performs K8s disk lookups only for schemas containing a disks field, introduces an optional tenant context hook, and removes the widget from the template registry.

Changes

Disk Handling Refactor

Layer / File(s) Summary
Optional tenant context hook
apps/console/src/lib/tenant-context.tsx
New useOptionalTenantContext hook returns TenantContext or null without requiring TenantProvider.
Schema transformation helpers for disk enum injection
apps/console/src/components/SchemaForm.tsx
K8s list imports and VMDiskRef type added; schemaHasDiskField detects disks in schema; injectDiskEnum augments disks[].name with enum of disk names and conditional defaults.
SchemaForm refactor: conditional disk handling and widget removal
apps/console/src/components/SchemaForm.tsx
SchemaForm now parses/sanitizes schema once, detects disk field presence, and conditionally renders SchemaFormWithDisks (with K8s disk fetch and enum injection) or SchemaFormInner (direct path). Removes VMDiskWidget injection from UI-schema augmentation.
Widget registry cleanup
apps/console/src/components/rjsf-templates.tsx
Removes VMDiskWidget import and entry from customWidgets registry; VMDiskWidget.tsx module deleted entirely.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 Disks once danced in widgets tall,
Now schemas sing and enums call,
With optional contexts, soft and sweet,
The refactor makes the schema complete!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly addresses the main change: preserving VM disk selection when toggling between Form and YAML views, which is the primary objective of this refactor.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/vminstance-disk-form-yaml-race

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added size/L This PR changes 100-499 lines, ignoring generated files area/console Issues or PRs related to apps/console — routes, detail pages, marketplace, command palette kind/bug Categorizes issue or PR as related to a bug labels Jun 1, 2026
@IvanHunters
IvanHunters marked this pull request as ready for review June 1, 2026 12:53

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +373 to +376
const diskNames = useMemo(
() => (diskList?.items ?? []).map((d) => d.metadata.name),
[diskList],
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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.

Suggested change
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],
)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/console/src/components/SchemaForm.tsx (1)

363-371: ⚡ Quick win

Make 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 schema while the user is editing. Pass watch: false alongside the existing enabled gate.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4570d44 and 83a0039.

📒 Files selected for processing (4)
  • apps/console/src/components/SchemaForm.tsx
  • apps/console/src/components/VMDiskWidget.tsx
  • apps/console/src/components/rjsf-templates.tsx
  • apps/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

Comment on lines +136 to +152
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 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" || true

Repository: 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" || true

Repository: 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 several as any casts.
  • Lines 187-200: (schema as any).properties and value as any casts.

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.

Comment on lines +136 to +179
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

Comment on lines +373 to +380
const diskNames = useMemo(
() => (diskList?.items ?? []).map((d) => d.metadata.name),
[diskList],
)

const schema = useMemo<RJSFSchema>(
() => injectDiskEnum(props.sanitizedSchema, diskNames),
[props.sanitizedSchema, diskNames],

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area/console Issues or PRs related to apps/console — routes, detail pages, marketplace, command palette kind/bug Categorizes issue or PR as related to a bug size/L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants