"use client";
import { useState, useEffect, useCallback } from "react";
import { Card, Button, Modal, Input, CardSkeleton, ModelSelectModal } from "@/shared/components";
import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard";
import { isOpenAICompatibleProvider, isAnthropicCompatibleProvider } from "@/shared/constants/providers";
// Validate combo name: only a-z, A-Z, 0-9, -, _
const VALID_NAME_REGEX = /^[a-zA-Z0-9_-]+$/;
export default function CombosPage() {
const [combos, setCombos] = useState([]);
const [loading, setLoading] = useState(true);
const [showCreateModal, setShowCreateModal] = useState(false);
const [editingCombo, setEditingCombo] = useState(null);
const [activeProviders, setActiveProviders] = useState([]);
const { copied, copy } = useCopyToClipboard();
useEffect(() => {
fetchData();
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const fetchData = async () => {
try {
const [combosRes, providersRes] = await Promise.all([
fetch("/api/combos"),
fetch("/api/providers"),
]);
const combosData = await combosRes.json();
const providersData = await providersRes.json();
if (combosRes.ok) setCombos(combosData.combos || []);
if (providersRes.ok) {
const active = (providersData.connections || []).filter(
c => c.testStatus === "active" || c.testStatus === "success"
);
setActiveProviders(active);
}
} catch (error) {
console.log("Error fetching data:", error);
} finally {
setLoading(false);
}
};
const handleCreate = async (data) => {
try {
const res = await fetch("/api/combos", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (res.ok) {
await fetchData();
setShowCreateModal(false);
} else {
const err = await res.json();
alert(err.error || "Failed to create combo");
}
} catch (error) {
console.log("Error creating combo:", error);
}
};
const handleUpdate = async (id, data) => {
try {
const res = await fetch(`/api/combos/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data),
});
if (res.ok) {
await fetchData();
setEditingCombo(null);
} else {
const err = await res.json();
alert(err.error || "Failed to update combo");
}
} catch (error) {
console.log("Error updating combo:", error);
}
};
const handleDelete = async (id) => {
if (!confirm("Delete this combo?")) return;
try {
const res = await fetch(`/api/combos/${id}`, { method: "DELETE" });
if (res.ok) {
setCombos(combos.filter(c => c.id !== id));
}
} catch (error) {
console.log("Error deleting combo:", error);
}
};
if (loading) {
return (
);
}
return (
{/* Header */}
Combos
Create model combos with fallback support
setShowCreateModal(true)}>
Create Combo
{/* Combos List */}
{combos.length === 0 ? (
layers
No combos yet
Create model combos with fallback support
setShowCreateModal(true)}>
Create Combo
) : (
{combos.map((combo) => (
setEditingCombo(combo)}
onDelete={() => handleDelete(combo.id)}
/>
))}
)}
{/* Create Modal - Use key to force remount and reset state */}
setShowCreateModal(false)}
onSave={handleCreate}
activeProviders={activeProviders}
/>
{/* Edit Modal - Use key to force remount and reset state */}
setEditingCombo(null)}
onSave={(data) => handleUpdate(editingCombo.id, data)}
activeProviders={activeProviders}
/>
);
}
function ComboCard({ combo, copied, onCopy, onEdit, onDelete }) {
return (
layers
{combo.name}
{ e.stopPropagation(); onCopy(combo.name, `combo-${combo.id}`); }}
className="p-0.5 hover:bg-black/5 dark:hover:bg-white/5 rounded text-text-muted hover:text-primary transition-colors opacity-0 group-hover:opacity-100"
title="Copy combo name"
>
{copied === `combo-${combo.id}` ? "check" : "content_copy"}
{combo.models.length === 0 ? (
No models
) : (
combo.models.slice(0, 3).map((model, index) => (
{model}
))
)}
{combo.models.length > 3 && (
+{combo.models.length - 3} more
)}
{/* Actions */}
edit
delete
);
}
function ComboFormModal({ isOpen, combo, onClose, onSave, activeProviders }) {
// Initialize state with combo values - key prop on parent handles reset on remount
const [name, setName] = useState(combo?.name || "");
const [models, setModels] = useState(combo?.models || []);
const [showModelSelect, setShowModelSelect] = useState(false);
const [saving, setSaving] = useState(false);
const [nameError, setNameError] = useState("");
const [modelAliases, setModelAliases] = useState({});
const [providerNodes, setProviderNodes] = useState([]);
const fetchModalData = async () => {
try {
const [aliasesRes, nodesRes] = await Promise.all([
fetch("/api/models/alias"),
fetch("/api/provider-nodes"),
]);
if (!aliasesRes.ok || !nodesRes.ok) {
throw new Error(`Failed to fetch data: aliases=${aliasesRes.status}, nodes=${nodesRes.status}`);
}
const [aliasesData, nodesData] = await Promise.all([
aliasesRes.json(),
nodesRes.json(),
]);
setModelAliases(aliasesData.aliases || {});
setProviderNodes(nodesData.nodes || []);
} catch (error) {
console.error("Error fetching modal data:", error);
}
};
useEffect(() => {
if (isOpen) fetchModalData();
}, [isOpen]);
const validateName = (value) => {
if (!value.trim()) {
setNameError("Name is required");
return false;
}
if (!VALID_NAME_REGEX.test(value)) {
setNameError("Only letters, numbers, - and _ allowed");
return false;
}
setNameError("");
return true;
};
const handleNameChange = (e) => {
const value = e.target.value;
setName(value);
if (value) validateName(value);
else setNameError("");
};
const handleAddModel = (model) => {
if (!models.includes(model.value)) {
setModels([...models, model.value]);
}
};
const handleRemoveModel = (index) => {
setModels(models.filter((_, i) => i !== index));
};
// Format model display name with readable provider name
const formatModelDisplay = useCallback((modelValue) => {
const parts = modelValue.split('/');
if (parts.length !== 2) return modelValue;
const [providerId, modelId] = parts;
const matchedNode = providerNodes.find(node => node.id === providerId);
if (matchedNode) {
return `${matchedNode.name}/${modelId}`;
}
return modelValue;
}, [providerNodes]);
const handleMoveUp = (index) => {
if (index === 0) return;
const newModels = [...models];
[newModels[index - 1], newModels[index]] = [newModels[index], newModels[index - 1]];
setModels(newModels);
};
const handleMoveDown = (index) => {
if (index === models.length - 1) return;
const newModels = [...models];
[newModels[index], newModels[index + 1]] = [newModels[index + 1], newModels[index]];
setModels(newModels);
};
const handleSave = async () => {
if (!validateName(name)) return;
setSaving(true);
await onSave({ name: name.trim(), models });
setSaving(false);
};
const isEdit = !!combo;
return (
<>
{/* Name */}
{/* Models */}
Models
{models.length === 0 ? (
layers
No models added yet
) : (
{models.map((model, index) => (
{/* Index badge */}
{index + 1}
{/* Model display - show readable name only */}
{formatModelDisplay(model)}
{/* Priority arrows - horizontal, always visible */}
handleMoveUp(index)}
disabled={index === 0}
className={`p-0.5 rounded ${index === 0 ? "text-text-muted/20 cursor-not-allowed" : "text-text-muted hover:text-primary hover:bg-black/5 dark:hover:bg-white/5"}`}
title="Move up"
>
arrow_upward
handleMoveDown(index)}
disabled={index === models.length - 1}
className={`p-0.5 rounded ${index === models.length - 1 ? "text-text-muted/20 cursor-not-allowed" : "text-text-muted hover:text-primary hover:bg-black/5 dark:hover:bg-white/5"}`}
title="Move down"
>
arrow_downward
{/* Remove - always visible */}
handleRemoveModel(index)}
className="p-0.5 hover:bg-red-500/10 rounded text-text-muted hover:text-red-500 transition-all"
title="Remove"
>
close
))}
)}
{/* Add Model button - moved to bottom */}
setShowModelSelect(true)}
className="w-full mt-2 py-2 border border-dashed border-black/10 dark:border-white/10 rounded-lg text-xs text-text-muted hover:text-primary hover:border-primary/30 transition-colors flex items-center justify-center gap-1"
>
add
Add Model
{/* Actions */}
Cancel
{saving ? "Saving..." : isEdit ? "Save" : "Create"}
{/* Model Select Modal */}
setShowModelSelect(false)}
onSelect={handleAddModel}
activeProviders={activeProviders}
modelAliases={modelAliases}
title="Add Model to Combo"
/>
>
);
}