"use client";
import { PlugIcon, RefreshCwIcon, ShieldAlertIcon } from "lucide-react";
import { useState, type FormEvent, type ReactNode } from "react";
import { toast } from "sonner";
import { EmptyState, ErrorState, PageHeader } from "@/components/shell/page";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { useI18n } from "@/lib/i18n";
import { useApi } from "@/lib/use-api";
import { cn } from "@/lib/utils";
import type {
Connector,
GatewayOutcomeOut,
ImportReport,
McpChange,
McpConnection,
TenantTool,
ToolMode,
} from "./types";
const TIER_STYLE = [
"bg-success-soft text-success",
"bg-muted text-foreground",
"bg-warning-soft text-warning",
"bg-destructive/10 text-destructive",
];
export function TierBadge({ tier, testId }: { tier: number; testId?: string }) {
return (
T{tier}
);
}
function errText(err: unknown, fallback: string): string {
if (err instanceof ApiError) {
const d = (err.body as { detail?: unknown } | undefined)?.detail;
if (d && typeof d === "object" && "message" in d) return String((d as { message: string }).message);
return err.detail;
}
return fallback;
}
function Field({ label, hint, children }: { label: string; hint?: string; children: ReactNode }) {
return (
{hint &&
{hint}
}
);
}
// ---------------------------------------------------------------------------- tools
function ToolRow({ tool, owner, onChanged }: { tool: TenantTool; owner: boolean; onChanged: () => void }) {
const { t } = useI18n();
const [tier, setTier] = useState(tool.confirmed_tier ?? tool.suggested_tier);
const [mode, setMode] = useState(tool.mode === "live" ? "live" : "test");
const [ack, setAck] = useState(false);
const [busy, setBusy] = useState(false);
const [argsText, setArgsText] = useState("{}");
const [preview, setPreview] = useState(null);
const confirm = async () => {
setBusy(true);
try {
await api(`/ext/tools/${encodeURIComponent(tool.name)}/confirm`, {
method: "POST",
body: { tier, mode, acknowledge_risk: ack },
});
toast.success(t("integrations.confirmed"));
onChanged();
} catch (err) {
toast.error(errText(err, t("common.error")));
} finally {
setBusy(false);
}
};
const toggle = async (enabled: boolean) => {
try {
await api(`/ext/tools/${encodeURIComponent(tool.name)}/settings`, { method: "POST", body: { enabled } });
onChanged();
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
const dryRun = async () => {
let args: unknown;
try {
args = JSON.parse(argsText);
} catch {
toast.error(t("integrations.invalidJson"));
return;
}
try {
setPreview(
await api(`/ext/tools/${encodeURIComponent(tool.name)}/test`, {
method: "POST",
body: { args },
}),
);
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
return (
{tool.name}
{tool.description}
{tool.source}
{t("integrations.suggested")}
{t("integrations.tier")}
{tool.mode === "live" ? t("integrations.live") : t("integrations.test")}
{tool.confirmed_tier === null && {t("integrations.unconfirmed")}}
{tool.blocked_reason && (
{tool.pending ? t("integrations.changed") : tool.blocked_reason}
)}
{tool.pending && (
{t("integrations.before")}
{tool.description}
{t("integrations.after")}
{tool.pending.description}
)}
{owner && (
<>
{tier < tool.suggested_tier && (
)}
>
)}
{t("integrations.tryIt")}
);
}
function ToolsTab({ owner }: { owner: boolean }) {
const { t } = useI18n();
const tools = useApi("/ext/tools");
if (tools.error) return ;
if (!tools.data) return ;
if (tools.data.length === 0)
return ;
return (
{tools.data.map((tool) => (
))}
);
}
// --------------------------------------------------------------------------- import
function ImportTab({ onDone }: { onDone: () => void }) {
const { t } = useI18n();
const [form, setForm] = useState({ name: "", spec: "", url: "", base_url: "", sandbox_base_url: "", secret_ref: "", sandbox_secret_ref: "" });
const [busy, setBusy] = useState(false);
const set = (k: keyof typeof form) => (e: { target: { value: string } }) => setForm({ ...form, [k]: e.target.value });
const submit = async (e: FormEvent) => {
e.preventDefault();
setBusy(true);
const body = Object.fromEntries(Object.entries(form).filter(([, v]) => v.trim() !== ""));
try {
const r = await api<{ report: ImportReport }>("/ext/openapi/import", { method: "POST", body });
toast.success(t("integrations.imported", { n: r.report.created.length + r.report.changed.length }));
onDone();
} catch (err) {
toast.error(errText(err, t("common.error")));
} finally {
setBusy(false);
}
};
return (
);
}
// ------------------------------------------------------------------------------ MCP
function McpTab({ owner }: { owner: boolean }) {
const { t, m } = useI18n();
const conns = useApi("/ext/mcp");
const [form, setForm] = useState({ name: "", url: "", auth_type: "none", secret_ref: "" });
const [changes, setChanges] = useState([]);
const connect = async (e: FormEvent) => {
e.preventDefault();
try {
const r = await api<{ report: ImportReport }>("/ext/mcp", {
method: "POST",
body: { ...form, secret_ref: form.secret_ref || null },
});
toast.success(t("integrations.connected", { n: r.report.created.length }));
conns.reload();
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
const refresh = async (name: string) => {
try {
const r = await api<{ changes: McpChange[] }>(`/ext/mcp/${encodeURIComponent(name)}/refresh`, { method: "POST" });
setChanges(r.changes);
toast.success(t("integrations.refreshed"));
conns.reload();
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
return (
);
}
// ----------------------------------------------------------------------- connectors
function toBase64(file: File): Promise {
return new Promise((resolve, reject) => {
const r = new FileReader();
r.onload = () => resolve(String(r.result).split(",", 2)[1] ?? "");
r.onerror = () => reject(r.error);
r.readAsDataURL(file);
});
}
function ConnectorsTab({ owner }: { owner: boolean }) {
const { t } = useI18n();
const list = useApi("/ext/connectors");
const [form, setForm] = useState({ kind: "table", name: "", config: '{\n "key_column": "sku"\n}', secret_ref: "" });
const create = async (e: FormEvent) => {
e.preventDefault();
let config: unknown;
try {
config = JSON.parse(form.config);
} catch {
toast.error(t("integrations.invalidJson"));
return;
}
try {
await api("/ext/connectors", {
method: "POST",
body: { kind: form.kind, name: form.name, config, secret_ref: form.secret_ref || null },
});
toast.success(t("integrations.created"));
list.reload();
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
const upload = async (name: string, file: File | undefined) => {
if (!file) return;
try {
const r = await api<{ rows: number }>(`/ext/connectors/${encodeURIComponent(name)}/upload`, {
method: "POST",
body: { filename: file.name, content_base64: await toBase64(file) },
});
toast.success(t("integrations.uploaded", { n: r.rows }));
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
return (
{list.error &&
}
{list.data?.length === 0 &&
{t("integrations.noConnectors")}
}
{owner && (
)}
);
}
// ---------------------------------------------------------------------------- page
export function IntegrationsView() {
const { t } = useI18n();
const { hasRole } = useAuth();
const owner = hasRole("owner");
const [tab, setTab] = useState("tools");
const [nonce, setNonce] = useState(0);
return (
{!owner &&
{t("integrations.ownerOnly")}
}
{t("integrations.tabTools")}
{owner && {t("integrations.tabImport")}}
{t("integrations.tabMcp")}
{t("integrations.tabConnectors")}
{owner && (
{
setNonce((n) => n + 1);
setTab("tools");
}}
/>
)}
);
}