"use client";
import * as React from "react";
import { AlertCircleIcon, CheckCircle2Icon, DownloadIcon, PlugZapIcon, RefreshCwIcon, SearchIcon } from "lucide-react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { api } from "@/lib/api";
import type { SSProject, SSTask } from "@/lib/types";
import { t } from "@/i18n";
type SSStatus = {
exists: boolean;
configured: boolean;
enabled: boolean;
reachable: boolean;
url?: string;
tools: string[];
};
type Dimension = "project" | "task";
const ASSET_TYPES: { key: string; label: string }[] = [
{ key: "subdomain", label: t("Subdomain") },
{ key: "service", label: t("Service") },
{ key: "app", label: t("App") },
];
export default function AssetSyncPage() {
return (
{t("Asset sync")}
{t("Sync assets into the store from external data sources")}
ScopeSentry
);
}
function ScopeSentryPanel() {
const [status, setStatus] = React.useState(null);
const [loadingStatus, setLoadingStatus] = React.useState(true);
const loadStatus = React.useCallback(() => {
setLoadingStatus(true);
api
.ssStatus()
.then(setStatus)
.catch((e) => toast.error(t("Failed to read data source status: {error}", { error: e.message })))
.finally(() => setLoadingStatus(false));
}, []);
React.useEffect(() => {
loadStatus();
}, [loadStatus]);
const ready = !!status && status.exists && status.configured && status.enabled;
return (
{ready ? (
) : (
{t("Once the data source is ready, you can pick projects / tasks to sync.")}
)}
);
}
// ── Data source status card ─────────────────────────────────────────────────────────────
function DataSourceCard({
status,
loading,
onChanged,
}: {
status: SSStatus | null;
loading: boolean;
onChanged: () => void;
}) {
const [url, setUrl] = React.useState("");
const [apiKey, setApiKey] = React.useState("");
const [busy, setBusy] = React.useState(false);
React.useEffect(() => {
if (status?.url) setUrl(status.url);
}, [status?.url]);
const create = async () => {
setBusy(true);
try {
await api.ssDatasource({});
toast.success(t("ScopeSentry data source created; fill in the URL and key"));
onChanged();
} catch (e) {
toast.error(t("Create failed: {error}", { error: (e as Error).message }));
} finally {
setBusy(false);
}
};
const save = async () => {
if (!url.trim()) return toast.error(t("Please enter the MCP URL"));
setBusy(true);
try {
const r = await api.ssDatasource({ url: url.trim(), api_key: apiKey.trim() });
toast.success(r.enabled ? t("Data source saved and enabled") : t("Saved (enable conditions not yet met)"));
setApiKey("");
onChanged();
} catch (e) {
toast.error(t("Save failed: {error}", { error: (e as Error).message }));
} finally {
setBusy(false);
}
};
return (
{t("Data source status")}
{!status?.exists ? (
{t("No ScopeSentry data source yet. Creating one adds a placeholder MCP (empty URL/key, disabled).")}
) : (
<>
{!status.configured && (
{t("The data source is created but not configured; fill in the MCP URL and API key, then enable it.")}
)}
{status.configured && !status.enabled && (
{t("The data source is configured but not enabled; it will be enabled automatically on save.")}
)}
{status.enabled && status.tools.length > 0 && (
{t("{count} tools discovered", { count: status.tools.length })}
)}
>
)}
);
}
function StatusBadge({ status, loading }: { status: SSStatus | null; loading: boolean }) {
if (loading || !status) return {t("Checking…")};
if (!status.exists) return {t("Not created")};
if (!status.configured) return {t("Not configured")};
if (!status.enabled) return {t("Not enabled")};
if (status.reachable)
return (
{t("Connected")}
);
return (
{t("Unreachable")}
);
}
// ── Sync workbench (project / task dimension) ────────────────────────────────────────────────
function SyncWorkbench() {
const [dimension, setDimension] = React.useState("project");
const [assetTypes, setAssetTypes] = React.useState>({
subdomain: true,
service: true,
app: true,
});
const [createCompany, setCreateCompany] = React.useState(true);
const [projects, setProjects] = React.useState([]);
const [tasks, setTasks] = React.useState([]);
const [loading, setLoading] = React.useState(false);
const [search, setSearch] = React.useState("");
const [page, setPage] = React.useState(1);
const [selected, setSelected] = React.useState>(new Set());
const [syncing, setSyncing] = React.useState(false);
const [result, setResult] = React.useState> | null>(null);
const load = React.useCallback(() => {
setLoading(true);
setSelected(new Set());
const fn =
dimension === "project"
? api.ssProjects(page, 50, search).then((r) => setProjects(r.projects))
: api.ssTasks(page, 50, search).then(setTasks);
fn.catch((e) => toast.error(t("Failed to load the list: {error}", { error: e.message }))).finally(() =>
setLoading(false),
);
}, [dimension, page, search]);
React.useEffect(() => {
load();
}, [load]);
const rows = dimension === "project" ? projects : tasks;
const idOf = (row: SSProject | SSTask) => (dimension === "project" ? (row as SSProject).id : (row as SSTask).name);
const toggle = (id: string) => {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const toggleAll = () => {
setSelected((prev) => (prev.size === rows.length ? new Set() : new Set(rows.map(idOf))));
};
const chosenTypes = ASSET_TYPES.filter((t) => assetTypes[t.key]).map((t) => t.key);
const runSync = async () => {
if (selected.size === 0)
return toast.error(dimension === "project" ? t("Select at least one project") : t("Select at least one task"));
if (chosenTypes.length === 0) return toast.error(t("Select at least one asset type"));
setSyncing(true);
setResult(null);
try {
const r = await api.ssSync({
dimension,
targets: [...selected],
asset_types: chosenTypes,
create_company: dimension === "project" ? createCompany : false,
});
setResult(r);
const total = Object.values(r.synced ?? {}).reduce((a, b) => a + b, 0);
toast.success(t("Sync finished; {count} assets ingested in total", { count: total }));
} catch (e) {
toast.error(t("Sync failed: {error}", { error: (e as Error).message }));
} finally {
setSyncing(false);
}
};
const renderRows = () => {
if (loading) {
return (
{t("Loading…")}
);
}
if (rows.length === 0) {
return (
{t("No data")}
);
}
if (dimension === "project") {
return projects.map((p) => (
toggle(p.id)}>
e.stopPropagation()}>
toggle(p.id)} />
{p.name}
{p.tag ? {p.tag} : "—"}
{p.AssetCount ?? 0}
));
}
return tasks.map((t) => (
toggle(t.name)}>
e.stopPropagation()}>
toggle(t.name)} />
{t.name}
{t.progress != null ? `${t.progress}%` : "—"}
{t.endTime || t.creatTime || "—"}
));
};
return (
{t("Pick data to sync")}
{/* Dimension switch */}
{
setDimension(v as Dimension);
setPage(1);
}}
>
{t("By project")}
{t("By task")}
{/* Asset types + options */}
{t("Assets to sync:")}
{ASSET_TYPES.map((t) => (
))}
{dimension === "project" && (
)}
{/* Search + actions */}
{/* List */}
0 && selected.size === rows.length} onCheckedChange={toggleAll} />
{dimension === "project" ? t("Project name") : t("Task name")}
{dimension === "project" ? (
<>
{t("Tag")}
{t("Assets")}
>
) : (
<>
{t("Status")}
{t("Time")}
>
)}
{renderRows()}
{/* Pagination */}
{t("Page {page}", { page })}
{/* Result */}
{result && }
);
}
function SyncResult({ result }: { result: Awaited> }) {
const synced = result.synced ?? {};
const labels: Record = { subdomain: t("Subdomain"), service: t("Service"), app: t("App"), ip: "IP" };
return (
{Object.entries(synced).map(([k, v]) => (
{labels[k] ?? k}: {v}
))}
{result.companies && result.companies.length > 0 && (
{t("Companies created/updated: {names}", { names: result.companies.join(", ") })}
)}
{result.warnings && result.warnings.length > 0 && (
{result.warnings.map((wm) => (
- {wm}
))}
)}
{result.errors && result.errors.length > 0 && (
{result.errors.slice(0, 20).map((em) => (
- {em}
))}
{result.errors.length > 20 && - {t("… {count} errors in total", { count: result.errors.length })}
}
)}
);
}