File size: 10,705 Bytes
cdfb5de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Alert, Button, Card, Checkbox, Group, PasswordInput, SegmentedControl, Select, Stack, Table, Text, TextInput, Title } from '@mantine/core';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { api, unwrap } from '../../api/client';
import { useAutonomy, useConfig, useHealth, useKill, useUsers } from '../../api/hooks';
import { Can, ErrorAlert, fmtTs, pct, PageHeader } from '../../components/common';
import { DataTable } from '../../components/states';
import './admin.css';

export function KillSwitchPage() {
  const kill = useKill();
  const health = useHealth();
  const cfg = useConfig();
  const qc = useQueryClient();
  const [reason, setReason] = useState('');
  const m = useMutation({
    mutationFn: (engaged: boolean) => unwrap(api.POST('/api/kill-switch', { body: { engaged, reason } })),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['kill'] }); qc.invalidateQueries({ queryKey: ['runs'] }); },
  });
  const k = kill.data;
  const providers = (cfg.data?.providers ?? {}) as Record<string, string | boolean | null>;
  return (
    <Stack>
      <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Administration' }, { label: 'Kill switch' }]} title="Kill switch" />
      <section className="fpt-card fpt-danger" aria-label="Emergency stop" data-engaged={k?.engaged || undefined}>
        <Text fw={600} mb={6}>Emergency stop</Text>
        <Group justify="space-between" wrap="wrap" align="flex-start">
          <div style={{ flex: '1 1 300px' }}>
            <Text size="lg" fw={600} c={k?.engaged ? 'red' : undefined} data-testid="kill-state">{k?.engaged ? 'ENGAGED' : 'released'}</Text>
            {k?.engaged && <Text size="sm">{k.reason} - by {k.actor} since {fmtTs(k.since)}</Text>}
            <Text size="xs" c="dimmed">Engaging stops the active run and its Playwright process tree, blocks all egress (pod, web, LLM, tickets) and refuses new runs. Also settable by creating var/KILL.</Text>
          </div>
          <Can perm="admin" fallback={<Text size="xs" c="dimmed">Admin only.</Text>}>
            <Stack gap="xs">
              <TextInput label="Reason" value={reason} onChange={(e) => setReason(e.currentTarget.value)} />
              {k?.engaged
                ? <Button onClick={() => m.mutate(false)} loading={m.isPending}>Release</Button>
                : <Button color="red" variant="filled" onClick={() => m.mutate(true)} loading={m.isPending}>Engage kill switch</Button>}
            </Stack>
          </Can>
        </Group>
        <ErrorAlert error={m.error} />
      </section>
      <section className="fpt-card" style={{ padding: 16 }} aria-label="Providers and health">
        <Text fw={600} mb={4}>Providers and health</Text>
        <Text size="sm">Mock app: {health.data?.mock_up ? 'up' : 'DOWN'} - Ollama: {health.data?.ollama_up ? 'up' : 'off/down'} - frontier: {health.data?.frontier_configured ? 'configured' : 'not configured'}</Text>
        <Text size="sm">LLM routing: stub (always) - local: {String(providers.local ?? 'none')} - frontier: {String(providers.frontier ?? 'off')} - local model {String(cfg.data?.ollama_model ?? '')}</Text>
      </section>
    </Stack>
  );
}

/** Settings > Health check: what a run needs, read-only. Every line says what is wrong and how to fix it. */
export function HealthCheckPanel() {
  const q = useQuery({ queryKey: ['health-readiness'], queryFn: () => unwrap(api.GET('/api/admin/readiness')), staleTime: 0 });
  const items = q.data?.items ?? [];
  const bad = items.filter((i) => !i.ok).length;
  return (
    <Stack>
      <section className="fpt-card" style={{ padding: 16 }} aria-label="Readiness">
        <Group justify="space-between" wrap="wrap" align="flex-start" mb="xs">
          <div style={{ flex: '1 1 300px' }}>
            <Text fw={600}>Health check</Text>
            <Text size="sm" c="dimmed" data-testid="health-summary">
              {q.isLoading ? 'Checking...' : q.data ? (bad ? `${bad} of ${items.length} checks need attention.` : 'All checks passed.') : 'Not checked.'}
            </Text>
            <Text size="xs" c="dimmed">Read-only: nothing is sent to the pod or changed.</Text>
          </div>
          <Button variant="default" onClick={() => q.refetch()} loading={q.isFetching} data-testid="health-check-again">Check again</Button>
        </Group>
        <ErrorAlert error={q.error} />
        {items.map((i) => (
          <div className="trio-row" key={i.key} data-testid={`health-${i.key}`}>
            <span className="trio-row-body">
              <b>{i.label}</b>
              <span>{i.detail}</span>
              {!i.ok && i.fix && <span>Fix: {i.fix}</span>}
            </span>
            <span className="trio-dotword" data-tone={i.ok ? 'green' : 'red'}>{i.ok ? 'OK' : 'Needs attention'}</span>
          </div>
        ))}
      </section>
    </Stack>
  );
}

export function AutonomyPage() {
  const q = useAutonomy();
  const qc = useQueryClient();
  const m = useMutation({
    mutationFn: ({ module, level }: { module: string; level: 'L0' | 'L1' | 'L2' }) => unwrap(api.PUT('/api/autonomy/{module}', { params: { path: { module } }, body: { level } })),
    onSettled: () => qc.invalidateQueries({ queryKey: ['autonomy'] }),
  });
  return (
    <Stack>
      <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Administration' }, { label: 'Automatic approval per business area' }]} title="Automatic approval per business area" />
      <Text size="sm" c="dimmed">L0: humans approve every new/changed/generated case. L1: approved library cases and patch-touched cases auto-approve. L2: generated drafts too. Real-defect confirmation and tickets are never autonomous. Promotion is refused unless the metrics meet the thresholds; demotion is always allowed.</Text>
      <ErrorAlert error={m.error} title="Change refused" />
      <DataTable label="Automatic approval per business area" minWidth={760} q={q} rowCount={Object.keys(q.data ?? {}).length}
        columns={['Business area', 'Level', 'Approval decisions', 'Approval rate', 'Defect recall', 'Can promote', 'Set']}
        empty="No business areas yet. They appear after the first test run.">
            {Object.entries(q.data ?? {}).map(([mod, a]) => (
              <Table.Tr key={mod}>
                <Table.Td>{mod}</Table.Td><Table.Td><b>{a.level}</b></Table.Td>
                <Table.Td>{a.metrics.n_approval_decisions} / {a.thresholds.min_labels}</Table.Td>
                <Table.Td>{pct(a.metrics.case_approval_rate)} (min {pct(a.thresholds.min_agreement)})</Table.Td>
                <Table.Td>{pct(a.metrics.real_defect_recall)} (min {pct(a.thresholds.min_recall)})</Table.Td>
                <Table.Td>L1 {a.can_promote.L1 ? 'yes' : 'no'} / L2 {a.can_promote.L2 ? 'yes' : 'no'}</Table.Td>
                <Table.Td><Can perm="admin" fallback={<Text size="xs">admin only</Text>}>
                  <SegmentedControl size="xs" aria-label={`level for ${mod}`} value={a.level} data={['L0', 'L1', 'L2']} onChange={(v) => m.mutate({ module: mod, level: v as 'L0' | 'L1' | 'L2' })} />
                </Can></Table.Td>
              </Table.Tr>
            ))}
      </DataTable>
    </Stack>
  );
}

/** Scheduled runs (step 7): the same screen at /schedules, /admin/scheduler and Settings > Schedules. */
export { ScheduledRunsPage as SchedulerPage } from '../runs/ScheduledRunsPage';

export function UsersPage() {
  const q = useUsers();
  const qc = useQueryClient();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [role, setRole] = useState<'viewer' | 'consultant' | 'qa_approver' | 'admin'>('viewer');
  const create = useMutation({
    mutationFn: () => unwrap(api.POST('/api/users', { body: { username, password, role } })),
    onSuccess: () => { setUsername(''); setPassword(''); qc.invalidateQueries({ queryKey: ['users'] }); },
  });
  const update = useMutation({
    mutationFn: ({ uid, body }: { uid: number; body: { role?: 'viewer' | 'consultant' | 'qa_approver' | 'admin'; disabled?: boolean } }) => unwrap(api.PATCH('/api/users/{uid}', { params: { path: { uid } }, body })),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['users'] }),
  });
  return (
    <Stack>
      <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Administration' }, { label: 'Users' }]} title="Users" />
      <Alert color="gray" data-testid="users-roles" className="adm-note">
        <b>People who sign themselves up start as viewers:</b> they can read test runs and reports, but cannot start runs. Give them a role here.
        Roles: viewer (read), consultant (start test runs, approve scenarios, self-heal fixes, drafts), qa_approver (start test runs, decide on failures, waivers, owners, sign off reports),
        admin (everything, including the emergency stop, automatic approval, scheduled runs and users).
      </Alert>
      <ErrorAlert error={create.error || update.error} />
      <DataTable label="Users" minWidth={640} q={q} rowCount={q.data?.length ?? 0} empty="No users yet."
        columns={['User', 'Role', 'Active', 'Last login', 'Created']}>
            {(q.data ?? []).map((u) => (
              <Table.Tr key={u.id}><Table.Td>{u.username}</Table.Td>
                <Table.Td><Select aria-label={`role of ${u.username}`} size="xs" w={150} data={['viewer', 'consultant', 'qa_approver', 'admin']} value={u.role} onChange={(v) => v && update.mutate({ uid: u.id, body: { role: v as 'viewer' } })} /></Table.Td>
                <Table.Td><Checkbox aria-label={`active ${u.username}`} checked={!u.disabled} onChange={(e) => update.mutate({ uid: u.id, body: { disabled: !e.currentTarget.checked } })} /></Table.Td>
                <Table.Td>{fmtTs(u.last_login_at)}</Table.Td><Table.Td>{fmtTs(u.created_at)} by {u.created_by}</Table.Td></Table.Tr>
            ))}
      </DataTable>
      <Card withBorder component="form" onSubmit={(e) => { e.preventDefault(); create.mutate(); }} aria-label="create user">
        <Title order={2} size="h5">Create user</Title>
        <Group align="flex-end" wrap="wrap">
          <TextInput label="Username" required value={username} onChange={(e) => setUsername(e.currentTarget.value)} />
          <PasswordInput label="Password (min 12)" required value={password} onChange={(e) => setPassword(e.currentTarget.value)} w={220} />
          <Select label="Role" w={160} data={['viewer', 'consultant', 'qa_approver', 'admin']} value={role} onChange={(v) => setRole((v as typeof role) ?? 'viewer')} />
          <Button type="submit" variant="filled" loading={create.isPending}>Create</Button>
        </Group>
      </Card>
    </Stack>
  );
}