File size: 28,447 Bytes
af1bee9
 
 
 
fb43301
af1bee9
 
 
fb43301
 
 
 
 
 
af1bee9
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0d811c3
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
 
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea59f21
af1bee9
 
 
ea59f21
 
af1bee9
ea59f21
af1bee9
ea59f21
af1bee9
 
ea59f21
af1bee9
 
ea59f21
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
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
import { Anchor, Button, CopyButton, Drawer, Group, PasswordInput, Stack, Text } from '@mantine/core';
import {
  IconBrandDiscord, IconBrandGithubCopilot, IconBrandGoogle, IconBrandJira, IconBrandOpenai, IconBrandSlack, IconBrandTeams, IconBrandTelegram,
  IconAffiliate, IconCheck, IconCode, IconCopy, IconKey, IconMessageChatbot, IconSend, IconSparkles, IconTicket, IconWebhook,
} from '@/components/icons';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState, type FormEvent, type ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { getJson, sendJson } from '../../api/client';
import { ErrorAlert, fmtTs, PageHeader } from '../../components/common';
import type { NotifySettings } from '../../notify/NotificationsSettings';
import { BotStatusLine, TelegramCard } from '../../notify/TelegramCard';
import { recentlyUsed, useAccessTokens } from '../../account/useAccessTokens';
import '../../notify/notify.css';
import './integrations.css';

type Delivery = { at: string; ok: boolean; status: number | null; error: string | null } | null;
export interface HookIntegration { configured: boolean; host: string | null; last_delivery: Delivery }
/** Messaging tools that receive notifications through an incoming webhook (one-way). */
export type HookKey = 'slack' | 'teams' | 'google_chat' | 'discord';
export type IntegrationsState = Record<HookKey, HookIntegration>;
/** AI assistants that use Astra through the MCP connector (/mcp, with a personal access token). */
type AssistantKey = 'copilot' | 'chatgpt' | 'claude' | 'github' | 'cursor';
type Key = 'telegram' | HookKey | AssistantKey | 'a2a' | 'webhook' | 'jira' | 'servicenow';
type Status = { tone: 'green' | 'neutral' | 'red'; words: string; planned?: boolean; outline?: boolean };

const PLANNED: Status = { tone: 'neutral', words: 'Planned', planned: true, outline: true };
const COMING_NEXT: Status = { tone: 'neutral', words: 'Coming next', planned: true, outline: true };
const AVAILABLE: Status = { tone: 'neutral', words: 'Available', outline: true };
const status = (configured: boolean, last: Delivery | undefined): Status =>
  !configured ? { tone: 'neutral', words: 'Not set up' }
    : last && !last.ok ? { tone: 'red', words: 'Needs attention' } : { tone: 'green', words: 'Connected' };

const useNotifySettings = () => useQuery({ queryKey: ['notify-settings'], queryFn: () => getJson<NotifySettings>('/api/notifications/settings'), retry: false });
const useIntegrations = () => useQuery({ queryKey: ['integrations'], queryFn: () => getJson<IntegrationsState>('/api/integrations'), retry: false });

interface CardDef { id: Key; icon: ReactNode; name: string; description: string; caps: string[]; st: Status }

/** One integration: its mark, what it does, whether it is connected (or planned), and the way to set it up. */
function IntegrationCard({ id, icon, name, description, caps, st, onOpen }: CardDef & { onOpen: () => void }) {
  const verb = st.planned ? 'Learn more' : st.tone === 'neutral' ? 'Set up' : 'Manage';
  return (
    <article className="pw-card int-card" aria-labelledby={`int-${id}-h`} data-testid={`integration-${id}`}>

      <div className="int-card-top">

        <span className="int-tile" data-brand={id} aria-hidden>{icon}</span>

        <span className="pw-status" data-tone={st.tone} data-variant={st.outline ? 'outline' : undefined} data-testid={`integration-${id}-status`}>{st.words}</span>

      </div>

      <h3 id={`int-${id}-h`} className="int-name">{name}</h3>

      <p className="int-desc">{description}</p>

      <ul className="int-caps" aria-label={`What ${name} can do`}>{caps.map((c) => <li key={c}>{c}</li>)}</ul>

      <Button variant="default" onClick={onOpen} aria-label={`${verb}: ${name}`}>{verb}</Button>

    </article>
  );
}

const HOOKS: Record<HookKey, { name: string; steps: string[]; help: string; helpLabel: string; host: string }> = {
  slack: {
    name: 'Slack', host: 'hooks.slack.com',
    steps: ['Create a Slack app for your workspace.', 'Open Incoming Webhooks and switch them on.', 'Choose Add New Webhook to Workspace and pick the channel.', 'Copy the webhook URL and paste it below.'],
    help: 'https://api.slack.com/messaging/webhooks', helpLabel: 'Slack: sending messages using incoming webhooks',
  },
  teams: {
    name: 'Microsoft Teams', host: 'your Teams workflow',
    steps: ['In Microsoft Teams, open the Workflows app.', 'Start from the template "Post to a channel when a webhook request is received".', 'Choose the team and channel, then finish the workflow.', 'Copy the webhook URL it shows and paste it below.'],
    help: 'https://support.microsoft.com/office/create-incoming-webhooks-with-workflows-for-microsoft-teams-8ae491c7-0394-4861-ba59-055e33f75498',
    helpLabel: 'Microsoft: create incoming webhooks with Workflows',
  },
  google_chat: {
    name: 'Google Chat', host: 'chat.googleapis.com',
    steps: ['In Google Chat, open the space that should get the messages.', 'Open Apps & integrations, then Webhooks.', 'Choose Add webhook, give it a name and save.', 'Copy the webhook URL and paste it below.'],
    help: 'https://developers.google.com/workspace/chat/quickstart/webhooks', helpLabel: 'Google: send messages to Google Chat with incoming webhooks',
  },
  discord: {
    name: 'Discord', host: 'discord.com',
    steps: ['In Discord, open the settings of the channel that should get the messages.', 'Open Integrations, then Webhooks.', 'Choose New Webhook.', 'Choose Copy Webhook URL and paste it below.'],
    help: 'https://support.discord.com/hc/en-us/articles/228383668', helpLabel: 'Discord: intro to webhooks',
  },
};

const lastLine = (last: Delivery | undefined) => last
  ? `Last delivery ${fmtTs(last.at)}: ${last.ok ? 'delivered' : `failed${last.error ? ` (${last.error})` : ''}`}.` : null;

/** A messaging tool with an incoming webhook: paste the URL once (a secret, never shown back), test, disconnect. */
function HookSetup({ kind, state }: { kind: HookKey; state: HookIntegration | undefined }) {
  const qc = useQueryClient();
  const [url, setUrl] = useState('');
  const [sure, setSure] = useState(false);
  const h = HOOKS[kind];
  const refresh = () => void qc.invalidateQueries({ queryKey: ['integrations'] });
  const save = useMutation({ mutationFn: () => sendJson<null>('PUT', `/api/integrations/${kind}`, { webhook_url: url.trim() }), onSuccess: () => { setUrl(''); refresh(); } });
  const test = useMutation({ mutationFn: () => sendJson<{ queued: boolean; id: number }>('POST', `/api/integrations/${kind}/test`), onSuccess: refresh });
  const remove = useMutation({ mutationFn: () => sendJson<null>('DELETE', `/api/integrations/${kind}`), onSuccess: () => { setSure(false); refresh(); } });
  const last = state?.last_delivery;
  const onSubmit = (e: FormEvent) => { e.preventDefault(); if (url.trim()) save.mutate(); };
  return (
    <Stack gap="md">

      {state?.configured ? (

        <p className="int-state" data-testid={`${kind}-connected`}>Connected ({state.host ?? h.host}). New notifications go there.</p>

      ) : (

        <>

          <ol className="int-steps">{h.steps.map((t) => <li key={t}>{t}</li>)}</ol>

          <Anchor href={h.help} target="_blank" rel="noreferrer">{h.helpLabel}</Anchor>

        </>
      )}
      <form onSubmit={onSubmit} aria-label={`Connect ${h.name}`}>
        <Stack gap="xs">

          <PasswordInput label="Webhook URL" autoComplete="off" spellCheck={false} value={url} onChange={(e) => setUrl(e.currentTarget.value)}

            description={state?.configured ? 'Paste a new URL to replace the current one. It is stored as a secret and never shown again.' : 'Stored as a secret and never shown again.'} />

          <Group gap="xs"><Button type="submit" variant="filled" disabled={!url.trim()} loading={save.isPending}>Save</Button></Group>

        </Stack>
      </form>
      <ErrorAlert error={save.error} title="That URL was not saved" />
      {state?.configured && (
        <>

          <Group gap="xs">

            <Button leftSection={<IconSend size={15} aria-hidden />} onClick={() => test.mutate()} loading={test.isPending}>Send a test message</Button>

            {!sure ? <Button variant="subtle" color="red" onClick={() => setSure(true)}>Disconnect</Button> : (

              <Group gap="xs" role="group" aria-label={`Disconnect ${h.name}?`}>

                <Text size="sm">Stop sending to {h.name}?</Text>

                <Button color="red" variant="filled" onClick={() => remove.mutate()} loading={remove.isPending}>Yes, disconnect</Button>

                <Button variant="default" onClick={() => setSure(false)}>Keep it</Button>

              </Group>

            )}

          </Group>

          {test.isSuccess && <Text size="sm" role="status">Test message queued. It should arrive within a few seconds.</Text>}

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

        </>
      )}
      {last && <Text size="sm" c={last.ok ? undefined : 'red'} data-testid={`${kind}-last`}>{lastLine(last)}</Text>}
    </Stack>
  );
}

/** The generic signed webhook (n8n and other tools): configured on the server, shown here read-only. */
function WebhookSetup({ s }: { s: NotifySettings | undefined }) {
  const last = s?.last_delivery;
  return (
    <Stack gap="sm">

      <p className="int-state">{s?.webhook_configured ? `Connected (${s.webhook_host ?? 'webhook'}), ${s.signing ? 'signed' : 'not signed'}.` : 'Not set up.'}</p>

      <ol className="int-steps">

        <li>Set <code>FPT_NOTIFY_WEBHOOK_URL</code> to the address that should receive the events (for example an n8n webhook).</li>

        <li>Set <code>FPT_NOTIFY_SECRET</code> to a long random value; every event is signed with it (<code>X-Patchwise-Signature</code>).</li>

        <li>For n8n, import <code>integrations/n8n/patchwise-telegram.json</code> and follow its README.</li>

      </ol>

      {last && <Text size="sm" c={last.ok ? undefined : 'red'}>{lastLine(last)}</Text>}

    </Stack>
  );
}

/** An integration that is planned: what it will do, in plain words, and a Connect button that is not available yet. */
function PlannedSetup({ intro, lists, note }: { intro: string; lists: { title: string; items: string[] }[]; note?: string }) {
  return (
    <Stack gap="sm" data-testid="planned-setup">

      <Text size="sm">{intro}</Text>

      {lists.map((l) => (

        <div key={l.title}>

          <h3 className="int-subh">{l.title}</h3>

          <ul className="int-steps int-bullets">{l.items.map((t) => <li key={t}>{t}</li>)}</ul>

        </div>

      ))}

      {note && <Text size="sm" c="dimmed">{note}</Text>}

      <Group gap="xs"><Button disabled>Connect</Button><Text size="sm" c="dimmed">Coming next</Text></Group>

    </Stack>
  );
}

/** A block of settings to paste, with a Copy button. Never holds a real token: placeholders and environment variables only. */
function Snippet({ title, code, label }: { title: string; code: string; label: string }) {
  return (
    <div className="int-snippet">

      <div className="int-snippet-head">

        <h3 className="int-subh">{title}</h3>

        <CopyButton value={code} timeout={2000}>

          {({ copied, copy }) => (

            <Button size="compact-sm" variant="default" onClick={copy} aria-label={`Copy ${label}`}

              leftSection={copied ? <IconCheck size={14} aria-hidden /> : <IconCopy size={14} aria-hidden />}>{copied ? 'Copied' : 'Copy'}</Button>

          )}

        </CopyButton>

      </div>

      <pre className="int-code"><code>{code}</code></pre>

    </div>
  );
}

const ASSISTANT_CAN = [
  { title: 'It can read', items: ['Patch readiness by business area', 'What is waiting for you', 'Test run status and reports'] },
  { title: 'It can act, each step confirmed by you', items: ['Start a test run', 'Approve scenarios'] },
];

/** The settings each assistant needs, for the given /mcp address. */
function clientSetup(kind: AssistantKey, url: string): ReactNode {
  const claudeDesktop = JSON.stringify({ mcpServers: { patchwise: {
    command: 'npx', args: ['-y', 'mcp-remote', url, '--header', 'Authorization:${PATCHWISE_AUTH}'],
    env: { PATCHWISE_AUTH: 'Bearer <paste your Astra token>' } } } }, null, 2);
  const claudeCode = `claude mcp add --transport http patchwise ${url} --header "Authorization: Bearer $PATCHWISE_TOKEN"`;
  const vscode = JSON.stringify({ servers: { patchwise: { type: 'http', url, headers: { Authorization: 'Bearer ${input:patchwise-token}' } } },
    inputs: [{ type: 'promptString', id: 'patchwise-token', description: 'Astra token', password: true }] }, null, 2);
  const cursor = JSON.stringify({ mcpServers: { patchwise: { url, headers: { Authorization: 'Bearer ${env:PATCHWISE_TOKEN}' } } } }, null, 2);
  if (kind === 'claude') return (
    <>

      <Snippet title="Claude Desktop: claude_desktop_config.json" label="the Claude Desktop settings" code={claudeDesktop} />

      <Snippet title="Claude Code: in a terminal" label="the Claude Code command" code={claudeCode} />

      <Text size="sm" c="dimmed">Set <code>PATCHWISE_TOKEN</code> in your terminal first. Claude.ai on the web needs sign-in with OAuth: coming next.</Text>

    </>
  );
  if (kind === 'github') return (
    <>

      <Snippet title="VS Code: .vscode/mcp.json" label="the VS Code settings" code={vscode} />

      <Text size="sm" c="dimmed">VS Code asks for the token the first time GitHub Copilot uses Astra, and keeps it in its secret storage.</Text>

    </>
  );
  if (kind === 'cursor') return (
    <>

      <Snippet title="Cursor: ~/.cursor/mcp.json" label="the Cursor settings" code={cursor} />

      <Text size="sm" c="dimmed">Set <code>PATCHWISE_TOKEN</code> in your environment, then restart Cursor.</Text>

    </>
  );
  if (kind === 'copilot') return (
    <div>

      <h3 className="int-subh">Microsoft Copilot (Copilot Studio)</h3>

      <ol className="int-steps">

        <li>In Copilot Studio, open your agent, then <b>Tools</b>, <b>Add a tool</b>, <b>Model Context Protocol</b>.</li>

        <li>Server URL: the address above.</li>

        <li>Authentication: <b>API key</b>, sent in the header <code>Authorization</code>, with the value <code>Bearer &lt;your token&gt;</code>.</li>

        <li>Save, then try: "What is waiting for me in Astra?"</li>

      </ol>

    </div>
  );
  return null;
}

/** An address to paste into another tool, with a Copy button. */
function AddressRow({ title, label, value, testId }: { title: string; label: string; value: string; testId: string }) {
  return (
    <div className="int-snippet">

      <div className="int-snippet-head">

        <h3 className="int-subh">{title}</h3>

        <CopyButton value={value} timeout={2000}>

          {({ copied, copy }) => (

            <Button size="compact-sm" variant="default" onClick={copy} aria-label={`Copy ${label}`}

              leftSection={copied ? <IconCheck size={14} aria-hidden /> : <IconCopy size={14} aria-hidden />}>{copied ? 'Copied' : 'Copy'}</Button>

          )}

        </CopyButton>

      </div>

      <code className="int-url" data-testid={testId}>{value}</code>

    </div>
  );
}

/** What another agent can ask Astra for over A2A, one line each (the skills on the Agent Card). */
const A2A_SKILLS: { id: string; words: string }[] = [
  { id: 'assess-readiness', words: 'How ready each business area is for a patch, with the numbers behind it.' },
  { id: 'design-tests', words: 'Design scenarios from the pod and patch facts your agent sends.' },
  { id: 'test-these-cases', words: 'Turn your own test cases into scripts and try them on a pod.' },
  { id: 'run-tests', words: 'Start a test run; it waits until a person approves in Astra.' },
  { id: 'get-report', words: 'Fetch the verdict, counts and the report of a finished run.' },
];

/** A short client for the A2A endpoint: send cases, then follow the task. The token comes from an environment variable. */
function a2aExample(base: string): string {
  return `import os, time, httpx



BASE = "${base}"

HEADERS = {"Authorization": "Bearer " + os.environ["PATCHWISE_TOKEN"]}



send = {

    "jsonrpc": "2.0", "id": 1, "method": "message/send",

    "params": {"message": {

        "role": "user", "messageId": "msg-1",

        "metadata": {"skill": "test-these-cases"},

        "parts": [{"kind": "data", "data": {"cases": [{

            "title": "Approve a requisition under the limit", "area": "P2P",

            "steps": [{"action": "Open Procurement > Requisitions > Manage Requisitions",

                       "expected": "The requisitions list opens"}],

        }]}}],

    }},

}

task = httpx.post(BASE + "/a2a", json=send, headers=HEADERS).json()["result"]



# follow the task: it stops at input-required until a person approves in Astra

while task["status"]["state"] not in ("completed", "failed", "canceled", "input-required"):

    time.sleep(10)

    get = {"jsonrpc": "2.0", "id": 2, "method": "tasks/get", "params": {"id": task["id"]}}

    task = httpx.post(BASE + "/a2a", json=get, headers=HEADERS).json()["result"]

print(task["status"]["state"])

`;
}

/** Your own agent talking to Astra over A2A: what it can ask for, the addresses, the token, and an example. */
function A2ASetup() {
  const origin = typeof window !== 'undefined' ? window.location.origin : '';
  return (
    <Stack gap="md" data-testid="a2a-setup">

      <Text size="sm">

        Your own agent, for example one that reads your pod and its patch updates, can ask Astra to design tests,

        test your own cases, start test runs and fetch the report. It acts as the person whose token it uses, with their permissions.

      </Text>

      <div>

        <h3 className="int-subh">What it can ask for</h3>

        <ul className="int-steps int-bullets">

          {A2A_SKILLS.map((s) => <li key={s.id}><code>{s.id}</code>: {s.words}</li>)}

        </ul>

      </div>

      <Text size="sm" className="int-rule" data-testid="a2a-rule">

        A person always approves in Astra before anything runs as a real test. Sign-off is never available through A2A.

      </Text>

      <Group gap="xs">

        <Button component={Link} to="/account#tokens" variant="filled" leftSection={<IconKey size={15} aria-hidden />}>Create a token</Button>

        <Text size="sm" c="dimmed">Choose “read and act” so the agent can start runs (you still approve each one).</Text>

      </Group>

      <AddressRow title="Agent Card" label="the Agent Card address" value={`${origin}/.well-known/agent-card.json`} testId="a2a-card-url" />

      <AddressRow title="Endpoint" label="the A2A endpoint" value={`${origin}/a2a`} testId="a2a-endpoint" />

      <Snippet title="Example (Python, httpx)" code={a2aExample(origin)} label="the A2A example" />

    </Stack>
  );
}

/** An AI assistant: what it can do through Astra, the token it needs, the /mcp address and its own settings. */
function AssistantSetup({ kind }: { kind: AssistantKey }) {
  const url = `${typeof window !== 'undefined' ? window.location.origin : ''}/mcp`;
  const web = kind === 'chatgpt';
  return (
    <Stack gap="md" data-testid={`assistant-setup-${kind}`}>

      <Text size="sm">It uses Astra as you, with your permissions, through one MCP connector (Model Context Protocol). Sign-off and failure verdicts stay in Astra.</Text>

      {ASSISTANT_CAN.map((l) => (

        <div key={l.title}><h3 className="int-subh">{l.title}</h3><ul className="int-steps int-bullets">{l.items.map((t) => <li key={t}>{t}</li>)}</ul></div>

      ))}

      {web ? (

        <Text size="sm" data-testid="needs-oauth">Needs sign-in with OAuth: coming next. Until then use Claude Desktop or Claude Code, VS Code with GitHub Copilot, or Cursor.</Text>

      ) : (

        <>

          <Group gap="xs">

            <Button component={Link} to="/account#tokens" variant="filled" leftSection={<IconKey size={15} aria-hidden />}>Create a token</Button>

            <Text size="sm" c="dimmed">On your Account page; it is shown once.</Text>

          </Group>

          <AddressRow title="Server address" label="the server address" value={url} testId="mcp-url" />

          {clientSetup(kind, url)}

        </>
      )}
    </Stack>
  );
}

const ASSISTANTS: AssistantKey[] = ['copilot', 'chatgpt', 'claude', 'github', 'cursor'];

const PLANNED_DRAWER: Partial<Record<Key, ReactNode>> = {
  jira: (
    <PlannedSetup intro="Defects a person confirms in Astra will be raised as Jira issues in the project you choose, with the evidence attached."

      lists={[{ title: 'It will', items: ['Create a Jira issue for each confirmed defect, with the failed step, expected and actual result, and screenshots', 'Link the issue back to the test run and the scenario', 'Show the Jira status next to the defect in Astra'] }]}

      note="It will use a Jira account with the least rights it needs: create and comment on issues in that one project." />
  ),
  servicenow: (
    <PlannedSetup intro="Attach the readiness verdict and sign-off evidence to the patch's change request, and raise confirmed defects as incidents."

      lists={[{ title: 'It will', items: [

        'Link a test run to a change request number',

        'On sign-off, add the report and the verdict to the change request as a work note and an attachment',

        'Turn each confirmed defect into an incident, with the evidence',

      ] }]}

      note="It will use a ServiceNow integration user with the least rights it needs." />
  ),
};

/** Integrations: where Astra reaches people (messaging), the AI assistants that will ask it, and the tools it feeds. */
export function IntegrationsPage() {
  const ns = useNotifySettings();
  const ints = useIntegrations();
  const tokens = useAccessTokens();
  const [open, setOpen] = useState<Key | null>(null);
  const assistant: Status = recentlyUsed(tokens.data?.items) ? { tone: 'green', words: 'Connected' } : AVAILABLE;
  const tg = ns.data?.telegram;
  const hook = (k: HookKey) => status(!!ints.data?.[k]?.configured, ints.data?.[k]?.last_delivery);
  const mcpCaps = ['Ask about readiness and runs', 'Start runs with confirmation'];
  const ide = ['Ask about readiness and runs', 'From your editor'];
  const sections: { id: string; title: string; lede: string; cards: CardDef[] }[] = [
    { id: 'messaging', title: 'Messaging', lede: 'Coworkers tell people here when a test run needs them.', cards: [
      { id: 'telegram', icon: <IconBrandTelegram size={22} stroke={1.7} />, name: 'Telegram', description: 'Coworkers message you, and you can start runs and approve from the chat.',
        caps: ['Notifications', 'Two-way: start runs, approve'], st: status(!!tg?.token_set && !!tg?.chat, tg?.last_delivery) },
      { id: 'teams', icon: <IconBrandTeams size={22} stroke={1.7} />, name: 'Microsoft Teams', description: 'Notifications in a Teams channel, through a Workflows webhook.',
        caps: ['Notifications', 'Two-way bot: planned'], st: hook('teams') },
      { id: 'slack', icon: <IconBrandSlack size={22} stroke={1.7} />, name: 'Slack', description: 'Notifications in a Slack channel, through an incoming webhook.',
        caps: ['Notifications', 'Two-way bot: planned'], st: hook('slack') },
      { id: 'google_chat', icon: <IconBrandGoogle size={22} stroke={1.7} />, name: 'Google Chat', description: 'Notifications in a Google Chat space, through an incoming webhook.',
        caps: ['Notifications'], st: hook('google_chat') },
      { id: 'discord', icon: <IconBrandDiscord size={22} stroke={1.7} />, name: 'Discord', description: 'Notifications in a Discord channel, through a channel webhook.',
        caps: ['Notifications'], st: hook('discord') },
    ] },
    { id: 'assistants', title: 'AI assistants', lede: 'Ask Astra from the assistant you already use.', cards: [
      { id: 'copilot', icon: <IconSparkles size={22} stroke={1.7} />, name: 'Microsoft Copilot', description: 'Ask about readiness and start runs from a Copilot Studio agent.', caps: mcpCaps, st: assistant },
      { id: 'chatgpt', icon: <IconBrandOpenai size={22} stroke={1.7} />, name: 'ChatGPT', description: 'Ask about readiness and start runs from ChatGPT.', caps: mcpCaps, st: COMING_NEXT },
      { id: 'claude', icon: <IconMessageChatbot size={22} stroke={1.7} />, name: 'Claude', description: 'Ask about readiness and start runs from Claude Desktop or Claude Code.', caps: mcpCaps, st: assistant },
      { id: 'github', icon: <IconBrandGithubCopilot size={22} stroke={1.7} />, name: 'GitHub Copilot (VS Code)', description: 'Ask Astra from GitHub Copilot chat in VS Code.', caps: ide, st: assistant },
      { id: 'cursor', icon: <IconCode size={22} stroke={1.7} />, name: 'Cursor', description: "Ask Astra from Cursor's assistant.", caps: ide, st: assistant },
    ] },
    { id: 'agents', title: 'Your own agents', lede: 'Agents you build can work with Astra through Agent2Agent (A2A).', cards: [
      { id: 'a2a', icon: <IconAffiliate size={22} stroke={1.7} />, name: 'Agent2Agent (A2A)',
        description: 'Your agent sends pod and patch facts or your own test cases; Astra designs and runs the tests and returns the report.',
        caps: ['Send pod and patch facts', 'Your test cases', 'Follow runs', 'Get reports'], st: AVAILABLE },
    ] },
    { id: 'tools', title: 'Tools', lede: 'Systems that receive Astra events and results.', cards: [
      { id: 'webhook', icon: <IconWebhook size={22} stroke={1.7} />, name: 'Webhook (n8n and other tools)', description: 'Signed events for automation tools such as n8n.',
        caps: ['Notifications', 'Signed (HMAC)'], st: status(!!ns.data?.webhook_configured, ns.data?.last_delivery) },
      { id: 'jira', icon: <IconBrandJira size={22} stroke={1.7} />, name: 'Jira', description: 'Planned: defects confirmed in Astra raised as Jira issues.', caps: ['Defects'], st: PLANNED },
      { id: 'servicenow', icon: <IconTicket size={22} stroke={1.7} />, name: 'ServiceNow',
        description: "Attach the readiness verdict and sign-off evidence to the patch's change request, and raise confirmed defects as incidents.",
        caps: ['Change requests', 'Incidents'], st: PLANNED },
    ] },
  ];
  const current = sections.flatMap((s) => s.cards).find((c) => c.id === open);
  return (
    <Stack className="adm-wide">

      <PageHeader crumbs={[{ label: 'Home', to: '/' }, { label: 'Setup' }, { label: 'Integrations' }]} title="Integrations"

        extra={<span className="fpt-pagedesc">Where Astra reaches you, and the AI assistants that can work with it. Notifications go to every connected place; Telegram also lets people start runs and approve from the chat.</span>} />

      <ErrorAlert error={ns.error || ints.error || tokens.error} title="Some integrations could not be loaded" />

      {sections.map((s) => (

        <section key={s.id} className="int-section" aria-labelledby={`int-sec-${s.id}`}>

          <h2 id={`int-sec-${s.id}`} className="int-sect-h">{s.title}</h2>

          <p className="int-sect-lede">{s.lede}</p>

          <div className="int-grid">{s.cards.map((c) => <IntegrationCard key={c.id} {...c} onOpen={() => setOpen(c.id)} />)}</div>

        </section>

      ))}

      <Drawer opened={!!open} onClose={() => setOpen(null)} position="right" size="md" title={current ? current.name : ''}

        closeButtonProps={{ 'aria-label': 'Close the setup' }}>

        {open === 'telegram' && (

          <Stack gap="md">

            <BotStatusLine />

            <TelegramCard tg={tg} />

            <Text size="sm">Each person links their own chat from <Anchor component={Link} to="/account">their Account page</Anchor>; their chat then acts as them, with their permissions.</Text>

          </Stack>

        )}

        {open && open in HOOKS && <HookSetup kind={open as HookKey} state={ints.data?.[open as HookKey]} />}

        {open === 'webhook' && <WebhookSetup s={ns.data} />}

        {open && (ASSISTANTS as Key[]).includes(open) && <AssistantSetup kind={open as AssistantKey} />}

        {open === 'a2a' && <A2ASetup />}

        {open && PLANNED_DRAWER[open]}

      </Drawer>

    </Stack>
  );
}