File size: 26,337 Bytes
af1bee9
fb43301
af1bee9
 
 
fb43301
 
af1bee9
 
1de224d
ccfcfd5
af1bee9
 
152e0c1
af1bee9
 
 
ea59f21
af1bee9
 
 
 
 
ea59f21
af1bee9
ea59f21
af1bee9
 
1de224d
152e0c1
 
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1de224d
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1de224d
 
ccfcfd5
 
1de224d
af1bee9
1de224d
 
 
 
af1bee9
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
1de224d
af1bee9
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
ccfcfd5
ea59f21
ccfcfd5
1de224d
 
 
ccfcfd5
1de224d
 
 
 
 
ccfcfd5
1de224d
 
 
 
 
 
 
 
 
ccfcfd5
1de224d
ccfcfd5
 
 
1de224d
 
 
ea59f21
1de224d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152e0c1
 
 
af1bee9
 
 
 
152e0c1
 
af1bee9
 
 
 
 
 
 
 
 
152e0c1
 
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330591c
af1bee9
ea59f21
af1bee9
 
 
 
 
 
 
 
 
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
import { Badge, Button, CopyButton, Group, JsonInput, Modal, Stack, Table, Text, TextInput } from '@mantine/core';
import { IconCheck, IconCopy, IconPlus, IconRefresh } from '@/components/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { getJson, sendJson } from '../../api/client';
import { ErrorAlert, fmtTs, PageHeader } from '../../components/common';
import './agent-studio.css';

interface FusionDelivery { base_url: string; token_url: string; client_id: string; scope: string; workflow_code: string; invocation_mode: string; workflow_status: string; has_secret: boolean }
interface Client { client_id: string; name: string; callback_url: string | null; release_watch_url: string | null; created_at: string; last_used_at: string | null; revoked_at: string | null; delivery?: 'url' | 'fusion' | 'pull'; fusion?: FusionDelivery | null }
interface Created extends Client { client_secret: string; signing_key: string }
interface Cycle { cycle_id: string; run_id: string; areas: string[]; status: string | null; waiting_for: string | null; data_approved_by: string; scripts_approved_by: string | null; created_at: string; correlation_id: string | null }
interface Delivery { id: number; delivery_id: string; event: string; cycle_id: string | null; attempts: number; status_code: number | null; error: string | null; created_at: string; delivered_at: string | null; job_id?: string | null; dead_at?: string | null; state?: 'queued' | 'picked_up' | 'retrying' | 'delivered' | 'superseded' | 'dead' }
interface Watch { checked_at?: string; checked?: { release: string; area: string; changes?: number; new?: number; error?: string }[]; updates?: number }
interface InboxItem { id: number; event: string; signature_ok: boolean; received_at: string; payload: Record<string, unknown> & { cycle_id?: string; scenarios?: { id: string; title: string; area: string; written_by: string }[]; verdict?: string; areas?: { area: string; verdict: string }[] } }

/** The workflow in Oracle Fusion, and which steps are Astra's. */
const FLOW: { n: number; text: string; who: 'fusion' | 'patchwise' | 'person' }[] = [
  { n: 1, text: 'Read the module space', who: 'fusion' },
  { n: 2, text: 'Generate synthetic test data', who: 'fusion' },
  { n: 3, text: 'Mask and validate it', who: 'fusion' },
  { n: 4, text: 'A person approves the test data', who: 'person' },
  { n: 5, text: 'Astra writes the scripts; Fusion emails them', who: 'patchwise' },
  { n: 6, text: 'A person approves start testing', who: 'person' },
  { n: 7, text: 'Astra tests and reports; Fusion emails the results', who: 'patchwise' },
];

const deliveryState = (d: Delivery) => (d.delivered_at ? { tone: 'green', words: `Delivered${d.attempts > 1 ? ` after ${d.attempts} tries` : ''}${d.job_id ? ` (Fusion job ${d.job_id})` : ''}` }
  : d.state === 'dead' || d.dead_at ? { tone: 'red', words: `Not delivered: ${d.error ?? ''}` }
  : d.state === 'superseded' ? { tone: 'neutral', words: 'Replaced by a newer event' }
  : d.attempts >= 6 ? { tone: 'red', words: `Failed: ${d.error ?? ''}` } : d.attempts ? { tone: 'orange', words: `Retrying (${d.error ?? 'no answer'})` } : { tone: 'neutral', words: 'Queued' });

function Secret({ label, value }: { label: string; value: string }) {
  return (
    <div className="as-secret">

      <Text size="xs" c="dimmed">{label}</Text>

      <Group gap={6} wrap="nowrap"><code>{value}</code>

        <CopyButton value={value}>{({ copied, copy }) => <Button size="compact-xs" variant="default" onClick={copy} leftSection={copied ? <IconCheck size={12} /> : <IconCopy size={12} />}>{copied ? 'Copied' : 'Copy'}</Button>}</CopyButton>

      </Group>

    </div>
  );
}

/** The Fusion side's OAuth clients: create one (its secret and signing key are shown once), point its callbacks, revoke. */
function Clients() {
  const qc = useQueryClient();
  const q = useQuery({ queryKey: ['as-clients'], queryFn: () => getJson<{ items: Client[] }>('/api/agent-studio/clients') });
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({ name: '', callback_url: '', release_watch_url: '' });
  const [made, setMade] = useState<Created | null>(null);
  const [editing, setEditing] = useState<Client | null>(null);
  const create = useMutation({
    mutationFn: () => sendJson<Created>('POST', '/api/agent-studio/clients', { name: form.name, callback_url: form.callback_url || null, release_watch_url: form.release_watch_url || null }),
    onSuccess: (c) => { setMade(c); setOpen(false); void qc.invalidateQueries({ queryKey: ['as-clients'] }); },
  });
  const revoke = useMutation({ mutationFn: (id: string) => sendJson('DELETE', `/api/agent-studio/clients/${id}`), onSuccess: () => void qc.invalidateQueries({ queryKey: ['as-clients'] }) });
  const items = (q.data?.items ?? []).filter((c) => !c.revoked_at);
  return (
    <section className="pw-card as-card" aria-labelledby="as-clients-h">

      <div className="as-card-head">

        <div><h2 id="as-clients-h">OAuth clients</h2><p>The Fusion workflow signs in with one of these (client credentials, scope <code>patchwise.invoke</code>).</p></div>

        <Button leftSection={<IconPlus size={14} />} onClick={() => setOpen(true)}>New client</Button>

      </div>

      <ErrorAlert error={q.error || revoke.error} />

      {items.length === 0 && <Text c="dimmed" size="sm">No client yet. Create one and paste its ID and secret into the Fusion workflow’s REST connection.</Text>}

      {items.length > 0 && (

        <Table className="pw-table" verticalSpacing="sm">

          <Table.Thead><Table.Tr><Table.Th>Client</Table.Th><Table.Th>Callbacks go to</Table.Th><Table.Th>Last used</Table.Th><Table.Th /></Table.Tr></Table.Thead>

          <Table.Tbody>{items.map((c) => (

            <Table.Tr key={c.client_id}>

              <Table.Td><b>{c.name}</b><div className="as-mono">{c.client_id}</div></Table.Td>

              <Table.Td>{c.delivery === 'fusion' && c.fusion

                ? <><Badge size="sm" variant="light" mb={4}>Oracle Fusion directly</Badge><div className="as-url">{c.fusion.workflow_code} on {c.fusion.base_url}</div></>

                : c.delivery === 'pull'

                ? <><Badge size="sm" variant="light" mb={4}>Fusion picks them up</Badge><div className="as-url as-dim">events/claim, then events/ack</div></>

                : <><div className="as-url">{c.callback_url ?? 'Not set'}</div>{c.release_watch_url && <div className="as-url as-dim">Release watch: {c.release_watch_url}</div>}</>}</Table.Td>

              <Table.Td>{c.last_used_at ? fmtTs(c.last_used_at) : 'Never'}</Table.Td>

              <Table.Td ta="right"><Group gap={6} justify="flex-end" wrap="nowrap">

                <Button size="xs" variant="default" onClick={() => setEditing(c)}>Delivery</Button>

                <Button size="xs" variant="default" color="red" onClick={() => revoke.mutate(c.client_id)}>Revoke</Button>

              </Group></Table.Td>

            </Table.Tr>
          ))}</Table.Tbody>
        </Table>
      )}
      <Modal opened={open} onClose={() => setOpen(false)} title="New OAuth client" centered>
        <Stack>

          <TextInput label="Name" placeholder="Fusion test pod, Agent Studio" required value={form.name} onChange={(e) => setForm({ ...form, name: e.currentTarget.value })} />

          <TextInput label="Callback address" description="Where Astra sends scripts ready, results and stopped (https)." placeholder="https://…/patchwise/callback" value={form.callback_url} onChange={(e) => setForm({ ...form, callback_url: e.currentTarget.value })} />

          <TextInput label="Release watch address" description="Where patch updates go: the Release Watch Agent (https). Optional." placeholder="https://…/release-watch" value={form.release_watch_url} onChange={(e) => setForm({ ...form, release_watch_url: e.currentTarget.value })} />

          <ErrorAlert error={create.error} />

          <Group justify="flex-end"><Button variant="default" onClick={() => setOpen(false)}>Cancel</Button><Button onClick={() => create.mutate()} loading={create.isPending} disabled={!form.name.trim()}>Create client</Button></Group>

        </Stack>
      </Modal>
      {editing && <DeliverySheet c={editing} onClose={() => setEditing(null)} />}
      <Modal opened={!!made} onClose={() => setMade(null)} title="Client created: copy these now" centered size="lg">
        {made && (
          <Stack>

            <Text size="sm">The secret and the signing key are shown <b>once</b>. Astra keeps only the secret’s hash.</Text>

            <Secret label="Client ID" value={made.client_id} />

            <Secret label="Client secret" value={made.client_secret} />

            <Secret label="Signing key (checks the X-Patchwise-Signature of each callback)" value={made.signing_key} />

            <Group justify="flex-end"><Button onClick={() => setMade(null)}>Done</Button></Group>

          </Stack>
        )}
      </Modal>
    </section>
  );
}

/** Where a client's events go: signed POSTs to its callback address (a relay), straight to Oracle Fusion, where

 * Astra signs in to the identity domain and starts the callback workflow (invokeAsync), or nowhere until the Fusion

 * workflow picks them up (pull: no OCI IAM app needed). The secret is write-only. */
function DeliverySheet({ c, onClose }: { c: Client; onClose: () => void }) {
  const qc = useQueryClient();
  const f = c.fusion;
  const [mode, setMode] = useState<'url' | 'fusion' | 'pull'>(c.delivery ?? 'url');
  const [form, setForm] = useState({ base_url: f?.base_url ?? '', token_url: f?.token_url ?? '', client_id: f?.client_id ?? '', client_secret: '',
    scope: f?.scope ?? '', workflow_code: f?.workflow_code ?? 'PATCH_TEST_CALLBACK_V3_7' });
  const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) => setForm({ ...form, [k]: e.currentTarget.value });
  const save = useMutation({
    mutationFn: () => sendJson<Client>('PUT', `/api/agent-studio/clients/${c.client_id}/delivery`,
      mode !== 'fusion' ? { mode } : { mode, fusion: { ...form, client_secret: form.client_secret || null, scope: form.scope || null } }),
    onSuccess: () => void qc.invalidateQueries({ queryKey: ['as-clients'] }),
  });
  const test = useMutation({ mutationFn: () => sendJson<{ ok: boolean; detail: string }>('POST', `/api/agent-studio/clients/${c.client_id}/delivery/test`) });
  return (
    <Modal opened onClose={onClose} title={`Where ${c.name} gets its events`} centered size="lg">

      <Stack>

        <div className="as-view" role="group" aria-label="Delivery">

          <Button variant={mode === 'url' ? 'filled' : 'default'} size="xs" onClick={() => setMode('url')} aria-pressed={mode === 'url'}>Callback address (relay)</Button>

          <Button variant={mode === 'fusion' ? 'filled' : 'default'} size="xs" onClick={() => setMode('fusion')} aria-pressed={mode === 'fusion'}>Oracle Fusion directly</Button>

          <Button variant={mode === 'pull' ? 'filled' : 'default'} size="xs" onClick={() => setMode('pull')} aria-pressed={mode === 'pull'}>Fusion picks them up</Button>

        </div>

        {mode === 'pull' ? (

          <Text size="sm" c="dimmed">Nothing is sent. The Fusion workflow asks for its events with this client’s own token (<code>POST /api/agent-studio/v1/events/claim</code>, then <code>/events/ack</code>), in a While Loop with a Wait. No Oracle identity domain app is needed.</Text>

        ) : mode === 'url' ? (

          <Text size="sm" c="dimmed">Signed POSTs go to the client’s callback address{c.callback_url ? <> (<code>{c.callback_url}</code>)</> : ' (not set)'}, for example the PATCH_TEST_RELAY.</Text>

        ) : (

          <>

            <Text size="sm" c="dimmed">Astra signs in to your Oracle identity domain with a confidential app (client credentials) and starts the callback workflow with <code>invokeAsync</code>. No relay is needed.</Text>

            <TextInput label="Fusion address" placeholder="https://<pod host>" required value={form.base_url} onChange={set('base_url')} />

            <TextInput label="Token address (OCI IAM)" placeholder="https://idcs-….identity.oraclecloud.com/oauth2/v1/token" required value={form.token_url} onChange={set('token_url')} />

            <Group grow>

              <TextInput label="Client ID" required value={form.client_id} onChange={set('client_id')} />

              <TextInput label="Client secret" type="password" autoComplete="new-password" placeholder={f?.has_secret ? 'Saved (leave empty to keep)' : ''} value={form.client_secret} onChange={set('client_secret')} />

            </Group>

            <TextInput label="Scope" description="Only if your identity domain asks for one." value={form.scope} onChange={set('scope')} />

            <TextInput label="Callback workflow" value={form.workflow_code} onChange={set('workflow_code')} />

          </>

        )}

        <ErrorAlert error={save.error || test.error} />

        {test.data && <Text size="sm" c={test.data.ok ? 'teal' : 'red'} role="status">{test.data.detail}</Text>}

        <Group justify="space-between">

          {mode === 'fusion' && c.delivery === 'fusion' ? <Button variant="default" onClick={() => test.mutate()} loading={test.isPending}>Test sign-in</Button> : <span />}

          <Group gap={8}><Button variant="default" onClick={onClose}>Close</Button><Button onClick={() => save.mutate()} loading={save.isPending}>Save</Button></Group>

        </Group>

        {save.isSuccess && <Text size="sm" c="teal" role="status">Saved.</Text>}

      </Stack>
    </Modal>
  );
}

function Cycles() {
  const q = useQuery({ queryKey: ['as-cycles'], queryFn: () => getJson<{ items: Cycle[] }>('/api/agent-studio/cycles'), refetchInterval: 10_000 });
  const items = q.data?.items ?? [];
  return (
    <section className="pw-card as-card" aria-labelledby="as-cycles-h">

      <div className="as-card-head"><div><h2 id="as-cycles-h">Test cycles</h2><p>Each one started by the Fusion workflow with its approved synthetic test data.</p></div></div>

      <ErrorAlert error={q.error} />

      {items.length === 0 ? <Text c="dimmed" size="sm">No test cycle yet.</Text> : (

        <Table className="pw-table" verticalSpacing="sm">

          <Table.Thead><Table.Tr><Table.Th>Cycle</Table.Th><Table.Th>Areas</Table.Th><Table.Th>Now</Table.Th><Table.Th>Test data approved by</Table.Th><Table.Th>Start approved by</Table.Th><Table.Th>Started</Table.Th></Table.Tr></Table.Thead>

          <Table.Tbody>{items.map((c) => (

            <Table.Tr key={c.cycle_id}>

              <Table.Td><Link to={`/runs/${c.run_id}`}><b>{c.cycle_id}</b></Link>{c.correlation_id && <div className="as-mono">{c.correlation_id}</div>}</Table.Td>

              <Table.Td>{c.areas.join(', ')}</Table.Td>

              <Table.Td>{c.waiting_for ? <Badge color="orange" variant="light">Waiting for {c.waiting_for}</Badge> : <Badge variant="light" color={c.status === 'completed' ? 'green' : 'gray'}>{c.status}</Badge>}</Table.Td>

              <Table.Td>{c.data_approved_by}</Table.Td>

              <Table.Td>{c.scripts_approved_by ?? '—'}</Table.Td>

              <Table.Td>{fmtTs(c.created_at)}</Table.Td>

            </Table.Tr>

          ))}</Table.Tbody>

        </Table>

      )}

    </section>
  );
}

function Callbacks() {
  const qc = useQueryClient();
  const q = useQuery({ queryKey: ['as-deliveries'], queryFn: () => getJson<{ items: Delivery[]; dead_letters?: number }>('/api/agent-studio/deliveries'), refetchInterval: 10_000 });
  const requeue = useMutation({ mutationFn: (id: string) => sendJson('POST', `/api/agent-studio/deliveries/${id}/requeue`), onSuccess: () => void qc.invalidateQueries({ queryKey: ['as-deliveries'] }) });
  const items = q.data?.items ?? [];
  return (
    <section className="pw-card as-card" aria-labelledby="as-cb-h">

      <div className="as-card-head"><div><h2 id="as-cb-h">Callbacks to Fusion</h2><p>Signed with the client’s key, retried for about half an hour when Fusion does not answer.</p></div></div>

      <ErrorAlert error={q.error || requeue.error} />

      {!!q.data?.dead_letters && <Text size="sm" c="red">{q.data.dead_letters} event(s) could not be delivered after every retry. Send them again once Fusion answers.</Text>}

      {items.length === 0 ? <Text c="dimmed" size="sm">Nothing sent yet.</Text> : (

        <Table className="pw-table" verticalSpacing="xs">

          <Table.Thead><Table.Tr><Table.Th>Event</Table.Th><Table.Th>Cycle</Table.Th><Table.Th>Delivery</Table.Th><Table.Th>When</Table.Th></Table.Tr></Table.Thead>

          <Table.Tbody>{items.map((d) => {

            const s = deliveryState(d);

            return (

              <Table.Tr key={d.id}>

                <Table.Td><b>{d.event.replace(/_/g, ' ')}</b></Table.Td>

                <Table.Td className="as-mono">{d.cycle_id ?? '—'}</Table.Td>

                <Table.Td><Badge variant="light" color={s.tone === 'neutral' ? 'gray' : s.tone}>{s.words}</Badge>

                  {(d.state === 'dead' || !!d.dead_at) && !d.delivered_at && <Button size="compact-xs" variant="default" ml={6} onClick={() => requeue.mutate(d.delivery_id)} loading={requeue.isPending && requeue.variables === d.delivery_id}>Send again</Button>}</Table.Td>

                <Table.Td>{fmtTs(d.delivered_at ?? d.created_at)}</Table.Td>

              </Table.Tr>

            );

          })}</Table.Tbody>

        </Table>

      )}

    </section>
  );
}

function ReleaseWatch() {
  const qc = useQueryClient();
  const q = useQuery({ queryKey: ['as-watch'], queryFn: () => getJson<Watch>('/api/agent-studio/release-watch') });
  const check = useMutation({ mutationFn: () => sendJson('POST', '/api/agent-studio/release-watch/check'), onSuccess: () => void qc.invalidateQueries({ queryKey: ['as-watch'] }) });
  const w = q.data ?? {};
  return (
    <section className="pw-card as-card" aria-labelledby="as-watch-h">

      <div className="as-card-head">

        <div><h2 id="as-watch-h">Release watch</h2><p>Reads Oracle’s What’s New for each test environment’s release; new items go to the Release Watch Agent, which drafts the impact assessment.</p></div>

        <Button variant="default" leftSection={<IconRefresh size={14} />} onClick={() => check.mutate()} loading={check.isPending}>Check now</Button>

      </div>

      <ErrorAlert error={q.error || check.error} />

      <Text size="sm" c="dimmed">{w.checked_at ? `Last checked ${fmtTs(w.checked_at)} · ${w.updates ?? 0} update(s) sent` : 'Not checked yet. It checks every day once a client has a release watch address.'}</Text>

      {!!w.checked?.length && (

        <div className="as-watch">{w.checked.map((c) => (

          <div key={`${c.release}-${c.area}`} className="as-watch-item" data-tone={c.error ? 'red' : c.new ? 'orange' : 'neutral'}>

            <b>{c.area}</b><span>{c.release}</span><span>{c.error ? 'Not published yet' : `${c.changes} items · ${c.new} new`}</span>

          </div>

        ))}</div>

      )}

    </section>
  );
}

/** Plays the Fusion side over the real API: a client of its own whose callbacks come back to this page. For tests and demos. */
function StandIn() {
  const qc = useQueryClient();
  const [creds, setCreds] = useState<{ id: string; secret: string } | null>(() => {
    try { const s = sessionStorage.getItem('pw-standin'); return s ? JSON.parse(s) : null; } catch { return null; }
  });
  const [data, setData] = useState(JSON.stringify({ AP: { business_unit: 'TEST_US_BU', supplier: 'Synthetic Supplier 01', currency: 'USD' } }, null, 2));
  const [who, setWho] = useState('');
  const [msg, setMsg] = useState<string | null>(null);
  const [err, setErr] = useState<string | null>(null);
  const inbox = useQuery({ queryKey: ['as-inbox'], queryFn: () => getJson<{ items: InboxItem[] }>('/api/agent-studio/standin/inbox'), refetchInterval: 5000 });
  useEffect(() => { try { if (creds) sessionStorage.setItem('pw-standin', JSON.stringify(creds)); } catch { /* private window */ } }, [creds]);

  const setup = useMutation({
    mutationFn: () => sendJson<Created>('POST', '/api/agent-studio/clients', { name: 'Stand-in (plays Oracle Fusion)',
      callback_url: `${window.location.origin}/api/agent-studio/standin/inbox`, release_watch_url: `${window.location.origin}/api/agent-studio/standin/inbox` }),
    onSuccess: (c) => { setCreds({ id: c.client_id, secret: c.client_secret }); void qc.invalidateQueries({ queryKey: ['as-clients'] }); },
  });
  const call = async (method: string, url: string, body?: unknown) => {
    if (!creds) throw new Error('Set up the stand-in first');
    const t = await fetch('/oauth/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ grant_type: 'client_credentials', client_id: creds.id, client_secret: creds.secret, scope: 'patchwise.invoke' }) });
    if (!t.ok) throw new Error(`Token refused (${t.status}): set up the stand-in again`);
    const { access_token } = await t.json();
    const r = await fetch(url, { method, headers: { Authorization: `Bearer ${access_token}`, 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined });
    const j = await r.json().catch(() => ({}));
    if (!r.ok) throw new Error(j.detail ?? `HTTP ${r.status}`);
    return j;
  };
  const go = (fn: () => Promise<string>) => { setErr(null); setMsg(null); fn().then(setMsg).catch((e: Error) => setErr(e.message)); };
  const items = inbox.data?.items ?? [];
  const ready = items.find((i) => i.event === 'scripts_ready');

  return (
    <section className="pw-card as-card as-standin" aria-labelledby="as-si-h">

      <div className="as-card-head">

        <div><h2 id="as-si-h">Stand-in for Oracle Fusion</h2><p>Plays the Agent Studio workflow against this Astra, over the same API, so the whole cycle can be tried and shown before the Fusion side is built.</p></div>

        {!creds && <Button onClick={() => setup.mutate()} loading={setup.isPending}>Set up the stand-in</Button>}

      </div>

      <ErrorAlert error={setup.error} />

      {creds && (

        <div className="as-si-grid">

          <div className="as-si-step">

            <h3>Steps 1–3 · Synthetic test data</h3>

            <JsonInput autosize minRows={6} value={data} onChange={setData} formatOnBlur validationError="Not JSON" aria-label="Synthetic test data" />

            <Group gap="xs"><Button variant="default" onClick={() => go(async () => { const r = await call('POST', '/api/agent-studio/v1/test-data/check', { test_data: JSON.parse(data) }); return r.ok ? 'Valid synthetic test data.' : `Refused: ${r.problem}`; })}>Mask and validate</Button></Group>

          </div>

          <div className="as-si-step">

            <h3>Step 4 · A person approves the test data</h3>

            <TextInput label="Approved by" placeholder="Name in Fusion" value={who} onChange={(e) => setWho(e.currentTarget.value)} />

            <Button disabled={!who.trim()} onClick={() => go(async () => { const r = await call('POST', '/api/agent-studio/v1/cycles', { test_data: JSON.parse(data), data_approved_by: who, areas: Object.keys(JSON.parse(data)) }); void qc.invalidateQueries({ queryKey: ['as-cycles'] }); return `Cycle ${r.cycle_id} started. Scripts come back in a few minutes.`; })}>Approve and send to Astra</Button>

          </div>

          <div className="as-si-step">

            <h3>Steps 5–6 · Scripts ready, approve start testing</h3>

            {ready ? (

              <>

                <Text size="sm"><b>{(ready.payload.scenarios ?? []).length} scenarios</b> for cycle {String(ready.payload.cycle_id)}</Text>

                <ul className="as-si-list">{(ready.payload.scenarios ?? []).slice(0, 6).map((s) => <li key={s.id}><span className="as-mono">{s.id}</span> {s.title}</li>)}</ul>

                <Button disabled={!who.trim()} onClick={() => go(async () => { await call('POST', `/api/agent-studio/v1/cycles/${String(ready.payload.cycle_id)}/approval`, { decision: 'approve', approved_by: who }); return 'Approved in "Fusion": testing starts.'; })}>Approve start testing</Button>

              </>

            ) : <Text size="sm" c="dimmed">Waiting for the scripts_ready callback.</Text>}

          </div>

          <div className="as-si-step">

            <h3>Step 7 and the release watch · What Fusion received</h3>

            {items.length === 0 ? <Text size="sm" c="dimmed">Nothing received yet.</Text> : (

              <ul className="as-si-inbox">{items.slice(0, 8).map((i) => (

                <li key={i.id}><b>{i.event.replace(/_/g, ' ')}</b>{i.payload.verdict ? ` · ${String(i.payload.verdict)}` : ''}

                  <span className="as-dim"> · {fmtTs(i.received_at)} · {i.signature_ok ? 'signature checked' : 'signature NOT valid'}</span></li>

              ))}</ul>

            )}

          </div>

        </div>
      )}
      {msg && <Text size="sm" c="teal">{msg}</Text>}
      {err && <Text size="sm" c="red">{err}</Text>}
    </section>
  );
}

export function AgentStudioPage() {
  return (
    <Stack gap="lg" className="adm-wide">

      <PageHeader crumbs={[]} title="Oracle AI Agent Studio"

        extra={<span>Fusion’s AI Agent Studio drives each test cycle: it sends synthetic test data a person approved, approves start testing, and receives the scripts and the results. <a href="https://github.com/SaiPhaniAnirudh/patchwise-agent-studio/blob/main/docs/AGENT_STUDIO.md" target="_blank" rel="noreferrer">Integration guide</a></span>} />

      <ol className="as-flow" aria-label="The workflow">

        {FLOW.map((s) => <li key={s.n} data-who={s.who}><span className="as-flow-n">{s.n}</span><span>{s.text}</span><small>{s.who === 'fusion' ? 'In Fusion' : s.who === 'person' ? 'A person, in Fusion' : 'Astra'}</small></li>)}

      </ol>

      <Clients />

      <Cycles />

      <Callbacks />

      <ReleaseWatch />

      <StandIn />

    </Stack>
  );
}