Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

1.8 KB
Raw Blame
"use client";

import { useCallback, useState } from "react";
import { useTranslations } from "next-intl";
import { chaosText, type ChaosTranslator } from "./chaosI18n";
import type { ChaosTestResult } from "./components/ChaosTestResultsPanel";
import type { ChaosPageConfig, ChaosPageMessage } from "./chaosPageTypes";

/**
 * "Test Chaos Mode" run trigger for the Chaos Mode config page. Extracted out
 * of the page component to keep it under the complexity/size ratchet
 * (config/quality/complexity-baseline.json).
 */
export function useChaosTestRun(
  config: ChaosPageConfig,
  setMessage: (message: ChaosPageMessage) => void
) {
  const t = useTranslations("chaosConfig") as ChaosTranslator;
  const [testing, setTesting] = useState(false);
  const [testResult, setTestResult] = useState<ChaosTestResult | null>(null);

  const testChaos = useCallback(async () => {
    setTesting(true);
    setTestResult(null);
    setMessage(null);
    try {
      const res = await fetch("/api/chaos/run", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          task: t("testTask"),
          mode: config.defaultMode,
          maxTokens: config.maxTokens,
        }),
      });

      if (res.ok) {
        const data: ChaosTestResult = await res.json();
        setTestResult(data);
      } else {
        const err = await res.json().catch(() => ({ error: null }));
        setMessage({
          type: "error",
          text: err.error || chaosText(t, "testFailed", "Test failed"),
        });
      }
    } catch (err: any) {
      setMessage({
        type: "error",
        text: err.message || chaosText(t, "testFailed", "Test failed"),
      });
    } finally {
      setTesting(false);
    }
  }, [config.defaultMode, config.maxTokens, setMessage, t]);

  return { testing, testResult, testChaos };
}