Spaces:
Running
Running
File size: 23,098 Bytes
03608f2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | "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 (
<span
className={cn("tabular rounded px-1.5 py-0.5 text-xs font-semibold", TIER_STYLE[tier] ?? TIER_STYLE[3])}
data-testid={testId}
>
T{tier}
</span>
);
}
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 (
<div className="space-y-1.5">
<label className="block space-y-1.5">
<span className="text-sm leading-none font-medium">{label}</span>
{children}
</label>
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
</div>
);
}
// ---------------------------------------------------------------------------- tools
function ToolRow({ tool, owner, onChanged }: { tool: TenantTool; owner: boolean; onChanged: () => void }) {
const { t } = useI18n();
const [tier, setTier] = useState<number>(tool.confirmed_tier ?? tool.suggested_tier);
const [mode, setMode] = useState<ToolMode>(tool.mode === "live" ? "live" : "test");
const [ack, setAck] = useState(false);
const [busy, setBusy] = useState(false);
const [argsText, setArgsText] = useState("{}");
const [preview, setPreview] = useState<GatewayOutcomeOut | null>(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<GatewayOutcomeOut>(`/ext/tools/${encodeURIComponent(tool.name)}/test`, {
method: "POST",
body: { args },
}),
);
} catch (err) {
toast.error(errText(err, t("common.error")));
}
};
return (
<li className="space-y-3 rounded-lg border bg-card p-4" data-testid="tenant-tool" data-tool={tool.name}>
<div className="flex flex-wrap items-start justify-between gap-3">
<div className="min-w-0 space-y-1">
<p className="font-mono text-sm font-medium" dir="ltr">
{tool.name}
</p>
<p className="text-sm text-muted-foreground">{tool.description}</p>
</div>
<div className="flex items-center gap-2 text-xs">
<Badge variant="outline">{tool.source}</Badge>
<span className="text-muted-foreground">{t("integrations.suggested")}</span>
<TierBadge tier={tool.suggested_tier} />
<span className="text-muted-foreground">{t("integrations.tier")}</span>
<TierBadge tier={tool.effective_tier} testId="effective-tier" />
<Badge variant={tool.mode === "live" ? "default" : "secondary"} data-testid="tool-mode">
{tool.mode === "live" ? t("integrations.live") : t("integrations.test")}
</Badge>
{tool.confirmed_tier === null && <Badge variant="secondary">{t("integrations.unconfirmed")}</Badge>}
</div>
</div>
{tool.blocked_reason && (
<p className="flex items-center gap-2 rounded-md bg-warning-soft px-3 py-2 text-sm text-warning" role="status">
<ShieldAlertIcon className="size-4 shrink-0" aria-hidden />
{tool.pending ? t("integrations.changed") : tool.blocked_reason}
</p>
)}
{tool.pending && (
<div className="grid gap-2 text-sm md:grid-cols-2" data-testid="pending-change">
<div className="rounded-md border p-2">
<p className="text-xs text-muted-foreground">{t("integrations.before")}</p>
<p>{tool.description}</p>
</div>
<div className="rounded-md border border-warning/40 p-2">
<p className="text-xs text-muted-foreground">{t("integrations.after")}</p>
<p>{tool.pending.description}</p>
</div>
</div>
)}
<div className="flex flex-wrap items-end gap-3">
{owner && (
<>
<Field label={t("integrations.tier")}>
<select
className="h-8 rounded-md border bg-background px-2 text-sm"
value={tier}
onChange={(e) => setTier(Number(e.target.value))}
aria-label={`${t("integrations.tier")} ${tool.name}`}
>
{[0, 1, 2, 3].map((n) => (
<option key={n} value={n}>
T{n}
</option>
))}
</select>
</Field>
<Field label={t("integrations.mode")}>
<select
className="h-8 rounded-md border bg-background px-2 text-sm"
value={mode}
onChange={(e) => setMode(e.target.value as ToolMode)}
aria-label={`${t("integrations.mode")} ${tool.name}`}
>
<option value="test">{t("integrations.test")}</option>
<option value="live">{t("integrations.live")}</option>
</select>
</Field>
{tier < tool.suggested_tier && (
<label className="flex items-center gap-2 text-xs">
<input type="checkbox" checked={ack} onChange={(e) => setAck(e.target.checked)} />
{t("integrations.lowerTier")}
</label>
)}
<Button size="sm" onClick={confirm} disabled={busy || (tier < tool.suggested_tier && !ack)}>
{t("integrations.confirm")}
</Button>
<label className="ms-auto flex items-center gap-2 text-sm">
<Switch
checked={tool.enabled}
onCheckedChange={(v) => void toggle(v)}
aria-label={`${t("integrations.enabled")} ${tool.name}`}
/>
{tool.enabled ? t("integrations.enabled") : t("integrations.disabled")}
</label>
</>
)}
</div>
<details className="text-sm">
<summary className="cursor-pointer text-muted-foreground">{t("integrations.tryIt")}</summary>
<div className="mt-2 space-y-2">
<Textarea
dir="ltr"
className="font-mono text-xs"
rows={3}
value={argsText}
onChange={(e) => setArgsText(e.target.value)}
aria-label={`${t("integrations.args")} ${tool.name}`}
/>
<Button size="sm" variant="outline" onClick={dryRun}>
{t("integrations.runDryRun")}
</Button>
{preview && (
<pre
dir="ltr"
className="max-h-64 overflow-auto rounded-md bg-muted p-2 text-xs"
data-testid="dry-run-preview"
>
{JSON.stringify({ status: preview.status, reason: preview.reason, data: preview.result?.data }, null, 2)}
</pre>
)}
</div>
</details>
</li>
);
}
function ToolsTab({ owner }: { owner: boolean }) {
const { t } = useI18n();
const tools = useApi<TenantTool[]>("/ext/tools");
if (tools.error) return <ErrorState error={tools.error} onRetry={tools.reload} />;
if (!tools.data) return <Skeleton className="h-32 w-full" />;
if (tools.data.length === 0)
return <EmptyState icon={PlugIcon} title={t("integrations.noTools")} hint={t("integrations.noToolsHint")} />;
return (
<ul className="space-y-3" data-testid="tenant-tools">
{tools.data.map((tool) => (
<ToolRow key={`${tool.name}:${tool.definition_hash}:${tool.updated_at}`} tool={tool} owner={owner} onChanged={tools.reload} />
))}
</ul>
);
}
// --------------------------------------------------------------------------- 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 (
<form onSubmit={submit} className="grid gap-4 rounded-lg border bg-card p-4 md:grid-cols-2" data-testid="import-form">
<Field label={t("integrations.name")} hint={t("integrations.nameHint")}>
<Input dir="ltr" value={form.name} onChange={set("name")} required pattern="[a-z][a-z0-9_]{1,39}" />
</Field>
<Field label={t("integrations.specUrl")}>
<Input dir="ltr" type="url" value={form.url} onChange={set("url")} />
</Field>
<div className="md:col-span-2">
<Field label={t("integrations.spec")}>
<Textarea dir="ltr" className="font-mono text-xs" rows={8} value={form.spec} onChange={set("spec")} />
</Field>
</div>
<Field label={t("integrations.baseUrl")}>
<Input dir="ltr" value={form.base_url} onChange={set("base_url")} />
</Field>
<Field label={t("integrations.sandboxUrl")}>
<Input dir="ltr" value={form.sandbox_base_url} onChange={set("sandbox_base_url")} />
</Field>
<Field label={t("integrations.secretRef")} hint={t("integrations.secretRefHint")}>
<Input dir="ltr" value={form.secret_ref} onChange={set("secret_ref")} autoComplete="off" />
</Field>
<Field label={t("integrations.sandboxSecretRef")}>
<Input dir="ltr" value={form.sandbox_secret_ref} onChange={set("sandbox_secret_ref")} autoComplete="off" />
</Field>
<div className="md:col-span-2">
<Button type="submit" disabled={busy}>
{t("integrations.importButton")}
</Button>
</div>
</form>
);
}
// ------------------------------------------------------------------------------ MCP
function McpTab({ owner }: { owner: boolean }) {
const { t, m } = useI18n();
const conns = useApi<McpConnection[]>("/ext/mcp");
const [form, setForm] = useState({ name: "", url: "", auth_type: "none", secret_ref: "" });
const [changes, setChanges] = useState<McpChange[]>([]);
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 (
<div className="space-y-4">
{conns.error && <ErrorState error={conns.error} onRetry={conns.reload} />}
{conns.data?.length === 0 && <p className="text-sm text-muted-foreground">{t("integrations.noMcp")}</p>}
<ul className="space-y-2">
{conns.data?.map((c) => (
<li key={c.id} className="flex flex-wrap items-center gap-3 rounded-lg border bg-card p-3 text-sm" data-testid="mcp-connection">
<span className="font-mono font-medium">{c.name}</span>
<span className="truncate text-muted-foreground" dir="ltr">
{c.url}
</span>
<Badge variant={c.status === "changed" ? "destructive" : "secondary"}>{(m.integrations.mcpStatuses as Record<string, string>)[c.status] ?? c.status}</Badge>
{c.last_diff?.changed?.length ? (
<span className="text-xs text-warning">
{t("integrations.lastDiff")}: {c.last_diff.changed.join(", ")}
</span>
) : null}
{owner && (
<Button size="sm" variant="outline" className="ms-auto" onClick={() => void refresh(c.name)}>
<RefreshCwIcon /> {t("integrations.refresh")}
</Button>
)}
</li>
))}
</ul>
{changes.length > 0 && (
<ul className="space-y-2" data-testid="mcp-changes">
{changes.map((ch) => (
<li key={ch.name} className="rounded-md border border-warning/40 p-3 text-sm">
<p className="font-mono">{ch.name}</p>
<p className="text-xs text-muted-foreground">{t("integrations.before")}: {ch.before.description}</p>
<p className="text-xs">{t("integrations.after")}: {ch.after.description}</p>
</li>
))}
</ul>
)}
{owner && (
<form onSubmit={connect} className="grid gap-4 rounded-lg border bg-card p-4 md:grid-cols-2">
<Field label={t("integrations.name")} hint={t("integrations.nameHint")}>
<Input dir="ltr" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
</Field>
<Field label={t("integrations.url")}>
<Input dir="ltr" type="url" value={form.url} onChange={(e) => setForm({ ...form, url: e.target.value })} required />
</Field>
<Field label={t("integrations.auth")}>
<select
className="h-8 rounded-md border bg-background px-2 text-sm"
value={form.auth_type}
onChange={(e) => setForm({ ...form, auth_type: e.target.value })}
>
<option value="none">{t("integrations.authNone")}</option>
<option value="bearer">{t("integrations.authBearer")}</option>
</select>
</Field>
<Field label={t("integrations.secretRef")} hint={t("integrations.secretRefHint")}>
<Input dir="ltr" value={form.secret_ref} onChange={(e) => setForm({ ...form, secret_ref: e.target.value })} />
</Field>
<div>
<Button type="submit">{t("integrations.connect")}</Button>
</div>
</form>
)}
</div>
);
}
// ----------------------------------------------------------------------- connectors
function toBase64(file: File): Promise<string> {
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<Connector[]>("/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 (
<div className="space-y-4">
{list.error && <ErrorState error={list.error} onRetry={list.reload} />}
{list.data?.length === 0 && <p className="text-sm text-muted-foreground">{t("integrations.noConnectors")}</p>}
<ul className="space-y-2">
{list.data?.map((c) => (
<li key={c.id} className="flex flex-wrap items-center gap-3 rounded-lg border bg-card p-3 text-sm" data-testid="connector">
<span className="font-mono font-medium">{c.name}</span>
<Badge variant="outline">{c.kind}</Badge>
{owner && c.kind === "table" && (
<label className="ms-auto flex items-center gap-2 text-xs">
{t("integrations.upload")}
<input
type="file"
accept=".csv,.xlsx,text/csv"
onChange={(e) => void upload(c.name, e.target.files?.[0])}
aria-label={`${t("integrations.upload")} ${c.name}`}
/>
</label>
)}
</li>
))}
</ul>
{owner && (
<form onSubmit={create} className="grid gap-4 rounded-lg border bg-card p-4 md:grid-cols-2">
<Field label={t("integrations.kind")}>
<select
className="h-8 rounded-md border bg-background px-2 text-sm"
value={form.kind}
onChange={(e) => setForm({ ...form, kind: e.target.value })}
>
<option value="table">{t("integrations.kinds.table")}</option>
<option value="google_sheets">{t("integrations.kinds.google_sheets")}</option>
<option value="http_action">{t("integrations.kinds.http_action")}</option>
<option value="webhook">{t("integrations.kinds.webhook")}</option>
</select>
</Field>
<Field label={t("integrations.name")} hint={t("integrations.nameHint")}>
<Input dir="ltr" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
</Field>
<div className="md:col-span-2">
<Field label={t("integrations.config")}>
<Textarea dir="ltr" className="font-mono text-xs" rows={6} value={form.config} onChange={(e) => setForm({ ...form, config: e.target.value })} />
</Field>
</div>
<Field label={t("integrations.secretRef")} hint={t("integrations.secretRefHint")}>
<Input dir="ltr" value={form.secret_ref} onChange={(e) => setForm({ ...form, secret_ref: e.target.value })} />
</Field>
<div className="flex items-end">
<Button type="submit">{t("integrations.create")}</Button>
</div>
</form>
)}
</div>
);
}
// ---------------------------------------------------------------------------- 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 (
<div className="space-y-5">
<PageHeader title={t("integrations.title")} subtitle={t("integrations.subtitle")} />
{!owner && <p className="text-sm text-muted-foreground">{t("integrations.ownerOnly")}</p>}
<Tabs value={tab} onValueChange={setTab}>
<TabsList>
<TabsTrigger value="tools">{t("integrations.tabTools")}</TabsTrigger>
{owner && <TabsTrigger value="import">{t("integrations.tabImport")}</TabsTrigger>}
<TabsTrigger value="mcp">{t("integrations.tabMcp")}</TabsTrigger>
<TabsTrigger value="connectors">{t("integrations.tabConnectors")}</TabsTrigger>
</TabsList>
<TabsContent value="tools">
<ToolsTab key={nonce} owner={owner} />
</TabsContent>
{owner && (
<TabsContent value="import">
<ImportTab
onDone={() => {
setNonce((n) => n + 1);
setTab("tools");
}}
/>
</TabsContent>
)}
<TabsContent value="mcp">
<McpTab owner={owner} />
</TabsContent>
<TabsContent value="connectors">
<ConnectorsTab owner={owner} />
</TabsContent>
</Tabs>
</div>
);
}
|