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

5.1 KB
Raw Blame
"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { Button, Card } from "@/shared/components";
import { useNotificationStore } from "@/store/notificationStore";
import { formatRemaining } from "@/shared/utils/formatRemaining";

type CooldownItem = {
  provider: string;
  model: string;
  reason: string;
  remainingMs: number;
  unavailableSince: string;
};

export default function ModelCooldownsCard() {
  const t = useTranslations("settings");
  const notify = useNotificationStore();
  const [items, setItems] = useState<CooldownItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [busyKey, setBusyKey] = useState<string | null>(null);

  const load = useCallback(async () => {
    try {
      const res = await fetch("/api/resilience/model-cooldowns", { cache: "no-store" });
      const json = await res.json();
      if (!res.ok) throw new Error(json?.error || `HTTP ${res.status}`);
      setItems(Array.isArray(json.items) ? json.items : []);
    } catch (error) {
      notify.error(error instanceof Error ? error.message : t("modelCooldownsLoadFailed"));
    } finally {
      setLoading(false);
    }
  }, [notify, t]);

  useEffect(() => {
    void (async () => {
      await load();
    })();
    const timer = setInterval(() => {
      void load();
    }, 5000);
    return () => clearInterval(timer);
  }, [load]);

  const clearOne = useCallback(
    async (provider: string, model: string) => {
      const key = `${provider}::${model}`;
      setBusyKey(key);
      try {
        const res = await fetch("/api/resilience/model-cooldowns", {
          method: "DELETE",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ provider, model }),
        });
        const json = await res.json();
        if (!res.ok) throw new Error(json?.error || `HTTP ${res.status}`);
        notify.success(t("modelCooldownReactivated", { model: `${provider}/${model}` }));
        await load();
      } catch (error) {
        notify.error(error instanceof Error ? error.message : t("modelCooldownClearFailed"));
      } finally {
        setBusyKey(null);
      }
    },
    [load, notify, t]
  );

  const clearAll = useCallback(async () => {
    setBusyKey("ALL");
    try {
      const res = await fetch("/api/resilience/model-cooldowns", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ all: true }),
      });
      const json = await res.json();
      if (!res.ok) throw new Error(json?.error || `HTTP ${res.status}`);
      notify.success(t("modelCooldownsAllReactivated"));
      await load();
    } catch (error) {
      notify.error(error instanceof Error ? error.message : t("modelCooldownsClearFailed"));
    } finally {
      setBusyKey(null);
    }
  }, [load, notify, t]);

  const hasItems = items.length > 0;
  const sorted = useMemo(() => [...items].sort((a, b) => b.remainingMs - a.remainingMs), [items]);

  return (
    <Card className="p-6">
      <div className="flex items-start justify-between gap-4">
        <div>
          <h2 className="text-lg font-bold text-text-main">{t("modelCooldownsTitle")}</h2>
          <p className="mt-1 text-sm text-text-muted">{t("modelCooldownsDescription")}</p>
        </div>
        <div className="flex gap-2">
          <Button size="sm" variant="secondary" onClick={() => void load()} disabled={loading}>
            {t("refresh")}
          </Button>
          <Button
            size="sm"
            variant="primary"
            onClick={() => void clearAll()}
            disabled={!hasItems || busyKey === "ALL"}
          >
            {t("modelCooldownsReactivateAll")}
          </Button>
        </div>
      </div>

      <div className="mt-4 space-y-2">
        {loading ? (
          <p className="text-sm text-text-muted">{t("loading")}</p>
        ) : !hasItems ? (
          <p className="text-sm text-text-muted">{t("modelCooldownsEmpty")}</p>
        ) : (
          sorted.map((item) => {
            const rowKey = `${item.provider}::${item.model}`;
            return (
              <div
                key={rowKey}
                className="rounded-lg border border-border bg-bg-subtle px-3 py-2 flex items-center justify-between gap-3"
              >
                <div className="min-w-0">
                  <p className="text-sm font-medium text-text-main truncate">
                    {item.provider}/{item.model}
                  </p>
                  <p className="text-xs text-text-muted">
                    {t("modelCooldownsReasonRemaining", {
                      reason: item.reason,
                      remaining: formatRemaining(item.remainingMs),
                    })}
                  </p>
                </div>
                <Button
                  size="sm"
                  variant="secondary"
                  onClick={() => void clearOne(item.provider, item.model)}
                  disabled={busyKey === rowKey}
                >
                  {t("modelCooldownsReactivate")}
                </Button>
              </div>
            );
          })
        )}
      </div>
    </Card>
  );
}