Files
next-ai-draw-io/hooks/use-validate-diagram.ts
T

85 lines
2.8 KiB
TypeScript
Raw Normal View History

2026-01-20 20:52:04 +09:00
"use client"
/**
* Hook for VLM-based diagram validation: one request, one JSON result.
2026-01-20 20:52:04 +09:00
*/
import { useCallback, useRef } from "react"
import { getSelectedAIConfig } from "@/hooks/use-model-config"
2026-01-20 20:52:04 +09:00
import { getApiEndpoint } from "@/lib/base-path"
import {
type ValidationResult,
ValidationResultSchema,
} from "@/lib/validation-schema"
// Default valid result for fallback cases
const DEFAULT_VALID_RESULT: ValidationResult = {
valid: true,
issues: [],
suggestions: [],
}
export function useValidateDiagram() {
// The running check's controller; a new check or cancel() aborts it
const controllerRef = useRef<AbortController | null>(null)
2026-01-20 20:52:04 +09:00
/**
* Validate a diagram image, with fallback: a failed check gives the
* default valid result so it never blocks the user. A cancelled check
* is passed on as its AbortError.
2026-01-20 20:52:04 +09:00
*/
const validateWithFallback = useCallback(
async (
imageData: string,
sessionId?: string,
): Promise<ValidationResult> => {
controllerRef.current?.abort()
const controller = new AbortController()
controllerRef.current = controller
2026-01-20 20:52:04 +09:00
try {
const res = await fetch(
getApiEndpoint("/api/validate-diagram"),
{
method: "POST",
headers: {
"Content-Type": "application/json",
// Read per request so a changed access code is
// picked up
"x-access-code": getSelectedAIConfig().accessCode,
},
body: JSON.stringify({ imageData, sessionId }),
signal: controller.signal,
},
)
if (!res.ok) {
throw new Error(`Validation request failed: ${res.status}`)
}
return ValidationResultSchema.parse(await res.json())
2026-01-20 20:52:04 +09:00
} catch (error) {
if ((error as Error)?.name === "AbortError") throw error
2026-01-20 20:52:04 +09:00
console.warn(
"[useValidateDiagram] Validation failed, using fallback:",
error,
)
return DEFAULT_VALID_RESULT
} finally {
if (controllerRef.current === controller) {
controllerRef.current = null
}
2026-01-20 20:52:04 +09:00
}
},
[],
2026-01-20 20:52:04 +09:00
)
/**
* End a running check (the user pressed Stop): its promise rejects with
* an AbortError, so the tool handler can finish at once.
*/
const cancel = useCallback(() => {
controllerRef.current?.abort()
controllerRef.current = null
}, [])
2026-01-20 20:52:04 +09:00
return { validateWithFallback, cancel }
2026-01-20 20:52:04 +09:00
}