Spaces:
Running

File size: 12,197 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
"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>
  );
}