Spaces:
Running

WorkPilot-AI / web /src /components /settings /settings-view.tsx
Aynkhn's picture
Deploy WorkPilot demo (part 3)
03608f2 verified
Raw History Blame Contribute Delete
12.2 kB
"use client";
import { PlusIcon, Trash2Icon } from "lucide-react";
import { useState, type FormEvent } from "react";
import { toast } from "sonner";
import { ErrorState, PageHeader } from "@/components/shell/page";
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 { api, ApiError } from "@/lib/api";
import { useAuth } from "@/lib/auth";
import { useI18n } from "@/lib/i18n";
import type { ApprovalRule, Role, TenantSettings, ToolInfo } from "@/lib/types";
import { useApi } from "@/lib/use-api";
const ROLES: Role[] = ["viewer", "agent_operator", "manager", "owner"];
function Section({ title, hint, children }: { title: string; hint?: string; children: React.ReactNode }) {
return (
<section className="rounded-lg border bg-card">
<header className="border-b px-4 py-3">
<h2 className="text-sm font-semibold">{title}</h2>
{hint && <p className="text-xs text-muted-foreground">{hint}</p>}
</header>
<div className="p-4">{children}</div>
</section>
);
}
function PolicyForm({ settings, tools, onSaved }: { settings: TenantSettings; tools: ToolInfo[]; onSaved: () => void }) {
const { t, m } = useI18n();
const editable = settings.editable;
const [attrs, setAttrs] = useState<[string, string][]>(() =>
Object.entries(settings.policy_attrs).map(([k, v]) => [k, String(v)]),
);
const [rules, setRules] = useState<ApprovalRule[]>(() => settings.approval_rules);
const [busy, setBusy] = useState(false);
const save = async (e: FormEvent) => {
e.preventDefault();
setBusy(true);
try {
const policy_attrs = Object.fromEntries(
attrs
.filter(([k]) => k.trim())
.map(([k, v]) => [k.trim(), v === "true" ? true : v === "false" ? false : /^-?\d+$/.test(v) ? Number(v) : v]),
);
const approval_rules = rules.map((r) => ({
tool: r.tool,
role: r.role,
stepup: r.stepup,
...(r.arg ? { arg: r.arg, min: r.min ?? 0 } : {}),
}));
await api("/settings", { method: "PUT", body: { policy_attrs, approval_rules } });
toast.success(t("settings.saved"));
onSaved();
} catch (err) {
toast.error(err instanceof ApiError ? err.detail : t("common.error"));
} finally {
setBusy(false);
}
};
return (
<form onSubmit={save} className="space-y-5">
<Section title={t("settings.policies")} hint={t("settings.policiesHint")}>
<div className="space-y-2" data-testid="policy-attrs">
{attrs.map(([k, v], i) => (
<div key={i} className="flex gap-2">
<Input
dir="ltr"
className="font-mono"
aria-label={t("settings.attr")}
value={k}
disabled={!editable}
onChange={(e) => setAttrs(attrs.map((a, j) => (j === i ? [e.target.value, a[1]] : a)))}
/>
<Input
dir="ltr"
className="tabular"
aria-label={`${t("settings.value")} ${k}`}
value={v}
disabled={!editable}
onChange={(e) => setAttrs(attrs.map((a, j) => (j === i ? [a[0], e.target.value] : a)))}
/>
{editable && (
<Button type="button" variant="ghost" size="icon" aria-label={t("settings.remove")} onClick={() => setAttrs(attrs.filter((_, j) => j !== i))}>
<Trash2Icon />
</Button>
)}
</div>
))}
{editable && (
<Button type="button" variant="outline" size="sm" onClick={() => setAttrs([...attrs, ["", ""]])}>
<PlusIcon /> {t("settings.addAttr")}
</Button>
)}
</div>
</Section>
<Section title={t("settings.rules")} hint={t("settings.rulesHint")}>
<div className="space-y-2 overflow-x-auto" data-testid="approval-rules">
{rules.length > 0 && (
<div className="grid min-w-[40rem] grid-cols-[2fr_1fr_1fr_1fr_auto_auto] gap-2 text-xs text-muted-foreground">
<span>{t("settings.tool")}</span>
<span>{t("settings.arg")}</span>
<span>{t("settings.min")}</span>
<span>{t("settings.role")}</span>
<span>{t("settings.stepup")}</span>
<span />
</div>
)}
{rules.map((r, i) => {
const set = (patch: Partial<ApprovalRule>) => setRules(rules.map((x, j) => (j === i ? { ...x, ...patch } : x)));
return (
<div key={i} className="grid min-w-[40rem] grid-cols-[2fr_1fr_1fr_1fr_auto_auto] items-center gap-2">
<select className="h-8 rounded-md border bg-background px-2 font-mono text-xs" dir="ltr" value={r.tool} disabled={!editable} onChange={(e) => set({ tool: e.target.value })} aria-label={t("settings.tool")}>
<option value="*">{t("common.anyTool")}</option>
{tools.map((tl) => (
<option key={tl.name} value={tl.name}>{tl.name}</option>
))}
</select>
<Input dir="ltr" className="font-mono" value={r.arg ?? ""} disabled={!editable} onChange={(e) => set({ arg: e.target.value || null })} aria-label={t("settings.arg")} />
<Input dir="ltr" type="number" min={0} step={1} className="tabular" value={r.min ?? ""} disabled={!editable} onChange={(e) => set({ min: e.target.value === "" ? null : Number(e.target.value) })} aria-label={t("settings.min")} />
<select className="h-8 rounded-md border bg-background px-2 text-sm" value={r.role} disabled={!editable} onChange={(e) => set({ role: e.target.value as Role })} aria-label={t("settings.role")}>
{ROLES.map((ro) => (
<option key={ro} value={ro}>{m.settings.roles[ro]}</option>
))}
</select>
<Switch checked={r.stepup} disabled={!editable} onCheckedChange={(c) => set({ stepup: c })} aria-label={t("settings.stepup")} />
{editable ? (
<Button type="button" variant="ghost" size="icon" aria-label={t("settings.remove")} onClick={() => setRules(rules.filter((_, j) => j !== i))}>
<Trash2Icon />
</Button>
) : (
<span />
)}
</div>
);
})}
{editable && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setRules([...rules, { tool: tools[0]?.name ?? "*", arg: null, min: null, role: "manager", stepup: false }])}
>
<PlusIcon /> {t("settings.addRule")}
</Button>
)}
</div>
</Section>
{editable ? (
<div className="flex justify-end">
<Button type="submit" disabled={busy} data-testid="save-settings">
{t("common.save")}
</Button>
</div>
) : (
<p className="text-sm text-muted-foreground">{t("settings.ownerOnly")}</p>
)}
</form>
);
}
function KillSwitches({ settings, tools, onChanged }: { settings: TenantSettings; tools: ToolInfo[]; onChanged: () => void }) {
const { t } = useI18n();
const { me } = useAuth();
const [tool, setTool] = useState("");
const tenantOn = settings.kill_switches.some((k) => k.scope === "tenant" && k.target === me?.tenant.id && k.enabled);
const set = async (scope: "tenant" | "tool", enabled: boolean, target?: string) => {
try {
await api("/admin/killswitch", { method: "POST", body: { scope, target, enabled, reason: "set from dashboard" } });
onChanged();
} catch (err) {
toast.error(err instanceof ApiError ? err.detail : t("common.error"));
}
};
return (
<Section title={t("settings.killSwitches")} hint={t("settings.killHint")}>
<div className="space-y-4">
<label className="flex items-center justify-between gap-3 text-sm">
<span className="font-medium">{t("settings.tenantSwitch")}</span>
<Switch checked={tenantOn} disabled={!settings.editable} onCheckedChange={(c) => set("tenant", c)} data-testid="tenant-killswitch" />
</label>
<ul className="divide-y rounded-md border text-sm">
{settings.kill_switches.filter((k) => k.scope === "tool").length === 0 && (
<li className="px-3 py-2 text-muted-foreground">{t("settings.noSwitches")}</li>
)}
{settings.kill_switches
.filter((k) => k.scope === "tool")
.map((k) => (
<li key={`${k.target}-${k.global}`} className="flex items-center gap-3 px-3 py-2">
<code className="font-mono text-xs" dir="ltr">{k.target}</code>
<span className="text-xs text-muted-foreground">{k.reason}</span>
<Switch className="ms-auto" checked={k.enabled} disabled={!settings.editable || k.global} onCheckedChange={(c) => set("tool", c, k.target)} aria-label={k.target} />
</li>
))}
</ul>
{settings.editable && (
<div className="flex gap-2">
<select className="h-8 flex-1 rounded-md border bg-background px-2 font-mono text-xs" dir="ltr" value={tool} onChange={(e) => setTool(e.target.value)} aria-label={t("settings.toolSwitch")}>
<option value="">—</option>
{tools.map((tl) => (
<option key={tl.name} value={tl.name}>{tl.name}</option>
))}
</select>
<Button variant="outline" size="sm" disabled={!tool} onClick={() => set("tool", true, tool)}>
{t("settings.toolSwitch")}
</Button>
</div>
)}
</div>
</Section>
);
}
export function SettingsView() {
const { t, m } = useI18n();
const { me } = useAuth();
const s = useApi<TenantSettings>("/settings");
const tools = useApi<ToolInfo[]>("/tools");
return (
<div className="space-y-5">
<PageHeader title={t("settings.title")} subtitle={t("settings.subtitle")} />
{s.error && !s.data ? (
<ErrorState error={s.error} onRetry={s.reload} />
) : !s.data ? (
<Skeleton className="h-80 w-full" />
) : (
<div className="grid gap-5 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
<PolicyForm key={JSON.stringify([s.data.policy_attrs, s.data.approval_rules])} settings={s.data} tools={tools.data ?? []} onSaved={s.reload} />
<div className="space-y-5">
<KillSwitches settings={s.data} tools={tools.data ?? []} onChanged={s.reload} />
<Section title={t("settings.team")}>
<ul className="divide-y text-sm" data-testid="team">
{s.data.team.map((u) => (
<li key={u.user_id} className="flex items-center justify-between gap-2 py-2">
<span dir="ltr" className="truncate">{u.email}</span>
<span className="text-xs text-muted-foreground">{m.settings.roles[u.role]}</span>
</li>
))}
</ul>
</Section>
<Section title={t("settings.security")}>
<p className="flex items-center justify-between text-sm">
<span>{t("settings.totp")}</span>
<span className="text-muted-foreground">{me?.user.totp_enrolled ? t("settings.totpOn") : t("settings.totpOff")}</span>
</p>
</Section>
<Section title={t("settings.channels")}>
<p className="text-sm text-muted-foreground">{t("settings.channelsHint")}</p>
</Section>
</div>
</div>
)}
</div>
);
}