"use client"; import Tooltip from "@/shared/ui/Tooltip"; import { useCallback, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { Ban, Globe, Loader2, Plus, RefreshCw, RotateCcw, Trash2, } from "lucide-react"; import { cancelWebSourceSync, addWebSource, listWebSources, removeWebSource, retryWebSourceSync, syncWebSources, updateWebSourceSchedule, listWebSourceSyncJobs, type WebSource, type WebSourceSyncJob, } from "@/features/knowledge/api/sources"; import { formatKnowledgeTimestamp } from "@/lib/knowledge-helpers"; interface KbWebSourcesSectionProps { kbName: string; } export default function KbWebSourcesSection({ kbName, }: KbWebSourcesSectionProps) { const { t } = useTranslation(); const [sources, setSources] = useState([]); const [jobs, setJobs] = useState([]); const [loading, setLoading] = useState(true); const [showForm, setShowForm] = useState(false); const [syncing, setSyncing] = useState(false); const [error, setError] = useState(null); const [urlInput, setUrlInput] = useState(""); const [maxDepth, setMaxDepth] = useState(3); const [submitting, setSubmitting] = useState(false); const [busySource, setBusySource] = useState(null); const [intervalInputs, setIntervalInputs] = useState>( {}, ); const refresh = useCallback(async () => { const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 15_000); try { const [nextSources, nextJobs] = await Promise.all([ listWebSources(kbName, { signal: controller.signal }), listWebSourceSyncJobs(kbName, { signal: controller.signal }), ]); setSources(nextSources); setJobs(nextJobs); setError(null); } catch (err) { if (err instanceof DOMException && err.name === "AbortError") { setError("Timed out loading web sources. Click retry."); } else { setError(err instanceof Error ? err.message : String(err)); } } finally { clearTimeout(timeout); setLoading(false); } }, [kbName]); useEffect(() => { void refresh(); }, [refresh]); useEffect(() => { const hasActiveJob = jobs.some( (job) => job.state === "running" || job.state === "pending", ); if (!hasActiveJob) return; const timer = setInterval(() => void refresh(), 5_000); return () => clearInterval(timer); }, [jobs, refresh]); const handleAdd = async () => { const url = urlInput.trim(); if (!url) return; setSubmitting(true); setError(null); try { await addWebSource(kbName, { url, max_depth: maxDepth }); setUrlInput(""); setMaxDepth(3); setShowForm(false); await refresh(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setSubmitting(false); } }; const handleRemove = async (id: string) => { setError(null); try { await removeWebSource(kbName, id); await refresh(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } }; const handleSync = async () => { setSyncing(true); setError(null); try { await syncWebSources(kbName); await refresh(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setSyncing(false); } }; const withSourceAction = async (id: string, action: () => Promise) => { setBusySource(id); setError(null); try { await action(); await refresh(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setBusySource(null); } }; const handleScheduleChange = ( source: WebSource, autoSyncEnabled: boolean, syncIntervalHours: number, ) => { const interval = Math.min(168, Math.max(1, syncIntervalHours || 24)); setIntervalInputs((current) => ({ ...current, [source.id]: interval })); return withSourceAction(source.id, async () => { await updateWebSourceSchedule(kbName, source.id, { auto_sync_enabled: autoSyncEnabled, sync_interval_hours: interval, }); }); }; if (loading) { return (
{error ? ( <>

{error}

) : ( )}
); } return (
{t("Web Sources")}

{t( "Crawl a documentation website on demand with bounded depth and page limits.", )}

{error && (
{error}
)} {showForm && (
)} {sources.length === 0 ? (

{t('No web sources yet. Click "Add source" to crawl a doc site.')}

) : (
{sources.map((src) => ( job.source_id === src.id)} busy={busySource === src.id} intervalValue={intervalInputs[src.id] ?? src.sync_interval_hours} onIntervalInput={(hours) => setIntervalInputs((current) => ({ ...current, [src.id]: hours, })) } onScheduleChange={(autoSync, hours) => void handleScheduleChange(src, autoSync, hours) } onCancel={() => void withSourceAction(src.id, () => cancelWebSourceSync(kbName, src.id), ) } onRetry={() => void withSourceAction(src.id, () => retryWebSourceSync(kbName, src.id), ) } onRemove={() => void handleRemove(src.id)} /> ))}
)}
); } function WebSourceCard({ source, job, busy, intervalValue, onIntervalInput, onScheduleChange, onCancel, onRetry, onRemove, }: { source: WebSource; job?: WebSourceSyncJob; busy: boolean; intervalValue: number; onIntervalInput: (hours: number) => void; onScheduleChange: (enabled: boolean, interval: number) => void; onCancel: () => void; onRetry: () => void; onRemove: () => void; }) { const { t } = useTranslation(); const statusColor = source.last_sync_status === "success" ? "text-emerald-600 dark:text-emerald-400" : source.last_sync_status === "error" ? "text-red-600 dark:text-red-400" : "text-[var(--muted-foreground)]"; const lastSync = formatKnowledgeTimestamp(source.last_synced_at); const jobColor = job?.state === "running" ? "text-blue-600 dark:text-blue-400" : job?.state === "error" || job?.state === "interrupted" ? "text-red-600 dark:text-red-400" : job?.state === "cancelled" ? "text-amber-600 dark:text-amber-400" : "text-[var(--muted-foreground)]"; const nextRun = job?.state === "pending" && job.next_run_at ? new Date(job.next_run_at).toLocaleString() : ""; return (
{source.url}
{t("Depth")}: {source.max_depth} {t("Status")}: {source.last_sync_status} {source.page_count > 0 && ( {t("Pages")}: {source.page_count} )} {source.bilingual_pairings && source.bilingual_pairings.length > 0 && ( `${p.source_lang.toUpperCase()} ↔ ${p.target_lang.toUpperCase()}: ${p.source_url} ↔ ${p.target_url}`, ) .join("\n")} > {t("Bilingual pairs")}: {source.bilingual_pairings.length} )} {lastSync && ( {t("Synced")}: {lastSync} )} {job && ( {t("Schedule")}: {t(job.state === "interrupted" ? "Interrupted" : job.state)} )} {nextRun && {t("Next run")}: {nextRun}} {job?.cancel_requested && {t("Cancelling…")}}
{source.last_sync_error && (

{source.last_sync_error}

)} {job?.error && (

{job.error}

)}
{job?.state === "running" || job?.state === "pending" ? ( ) : ( )}
); }