patchwise-agent-studio / web /src /pages /run /SignInPanel.tsx
EnergyVenom's picture
Astra: PO/GL actions, usage coverage, assisted sign-in, self-healing, recorder, new top navigation and theme (172a4e22a2bf)
fb62a97 verified
Raw History Blame Contribute Delete
8.55 kB
import { Alert, Button, Group, Stack, Text, TextInput } from '@mantine/core';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useRef, useState, type KeyboardEvent, type MouseEvent } from 'react';
import { api, unwrap, type Schemas } from '../../api/client';
import { Can, ErrorAlert } from '../../components/common';
// Assisted sign-in (coworker/platform/assisted_signin.py): the run's pod signs in through the company's identity provider,
// so a person signs in here, in a browser Astra runs on the pod (on the browser runner when there is one). The picture is
// that browser; clicks and keys go to it. Once the Fusion home page opens Astra keeps the session and the run goes on.
type SignInEvent = Schemas['SignInEvent'];
type Status = Schemas['SignInStatusOut'];
/** The sign-in browser's own size: clicks are sent in its pixels, whatever size the picture is shown at. */
export const BROWSER = { width: 1280, height: 800 };
/** Where a click on the picture lands in the browser (the picture is scaled to fit the page). */
export function toBrowser(clientX: number, clientY: number, rect: { left: number; top: number; width: number; height: number }) {
const x = ((clientX - rect.left) / Math.max(1, rect.width)) * BROWSER.width;
const y = ((clientY - rect.top) / Math.max(1, rect.height)) * BROWSER.height;
return { x: Math.round(Math.max(0, Math.min(BROWSER.width, x))), y: Math.round(Math.max(0, Math.min(BROWSER.height, y))) };
}
const SPECIAL = new Set(['Enter', 'Tab', 'Backspace', 'Delete', 'Escape', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown']);
/** A key pressed on the picture as the browser's event: a printable character is text, a named key is a key press. */
export function keyEvent(e: { key: string; ctrlKey?: boolean; metaKey?: boolean; altKey?: boolean }): SignInEvent | null {
if (e.ctrlKey || e.metaKey || e.altKey) return /^[A-Za-z0-9]$/.test(e.key) ? { type: 'press', key: `${e.ctrlKey ? 'Control+' : e.metaKey ? 'Meta+' : 'Alt+'}${e.key}` } : null;
if (e.key.length === 1) return { type: 'type', text: e.key };
return SPECIAL.has(e.key) ? { type: 'press', key: e.key } : null;
}
const PAGE_WORDS: Record<string, string> = { pod: 'the Oracle Fusion pod', 'identity provider': "your company's sign-in page", blank: 'opening…' };
export function SignInPanel({ runId }: { runId: string }) {
const qc = useQueryClient();
const [sid, setSid] = useState<string | null>(null);
const [text, setText] = useState('');
const [tick, setTick] = useState(0);
const img = useRef<HTMLImageElement>(null);
const status = useQuery({
queryKey: ['run', runId, 'sign-in'],
queryFn: () => unwrap(api.GET('/api/runs/{run_id}/sign-in', { params: { path: { run_id: runId } } })),
refetchInterval: 2000,
});
const s: Status | undefined = status.data;
const open = !!s?.active && !!s?.mine && !!sid;
// the picture refreshes about twice a second while the person's own session is open
useEffect(() => {
if (!open) return;
const t = window.setInterval(() => setTick((n) => n + 1), 600);
return () => window.clearInterval(t);
}, [open]);
useEffect(() => { // the run went on (signed in) or the session closed: the page follows
if (s && !s.waiting) qc.invalidateQueries({ queryKey: ['run', runId] });
if (s && !s.active) setSid(null);
}, [s?.waiting, s?.active]); // eslint-disable-line react-hooks/exhaustive-deps
const path = { params: { path: { run_id: runId } } };
const start = useMutation({
mutationFn: () => unwrap(api.POST('/api/runs/{run_id}/sign-in/session', path)),
onSuccess: (d) => { setSid(d.session_id ?? null); qc.setQueryData(['run', runId, 'sign-in'], d); },
});
const send = useMutation({
mutationFn: (events: SignInEvent[]) => unwrap(api.POST('/api/runs/{run_id}/sign-in/input', { ...path, body: { session_id: sid ?? '', events } })),
});
const finish = useMutation({
mutationFn: () => unwrap(api.POST('/api/runs/{run_id}/sign-in/finish', { ...path, body: { session_id: sid ?? '' } })),
onSuccess: (d) => { qc.setQueryData(['run', runId, 'sign-in'], d); qc.invalidateQueries({ queryKey: ['run', runId] }); },
});
const cancel = useMutation({
mutationFn: () => unwrap(api.POST('/api/runs/{run_id}/sign-in/cancel', { ...path, body: { session_id: sid ?? '' } })),
onSuccess: (d) => { setSid(null); qc.setQueryData(['run', runId, 'sign-in'], d); },
});
const click = (e: MouseEvent<HTMLImageElement>) => {
const r = e.currentTarget.getBoundingClientRect();
e.currentTarget.parentElement?.focus();
send.mutate([{ type: 'click', ...toBrowser(e.clientX, e.clientY, r) }]);
};
const key = (e: KeyboardEvent<HTMLDivElement>) => {
const ev = keyEvent(e);
if (!ev) return;
e.preventDefault();
send.mutate([ev]);
};
const typeText = () => {
if (!text) return;
send.mutate([{ type: 'type', text }]);
setText('');
};
const gate = s?.gate;
const expired = gate?.reason === 'expired';
return (
<Stack gap="sm" data-testid="sign-in-panel">
<h3 className="trio-card-h">Sign-in needed</h3>
<Text size="sm">
{gate?.pod ?? 'This pod'} signs in through your company&apos;s identity provider, so a person signs in before the tests run.
{expired ? ` The earlier session expired: ${gate?.remaining ?? 'some'} scenario(s) wait for a new sign-in.` : ''}
{' '}Astra keeps the session only for this run, encrypted, and deletes it when the run ends. What you type is never recorded.
</Text>
{s?.active && !s.mine && <Alert color="gray" p={8}>{s.owner} is signing in to the pod for this run right now.</Alert>}
{!open && (!s?.active || s.mine) && (
<Can perm="gate.sign_in" fallback={<Alert color="gray" p={8}>Signing in needs the consultant, QA approver or admin role.</Alert>}>
<Group>
<Button onClick={() => start.mutate()} loading={start.isPending} data-testid="sign-in-open">{s?.active ? 'Continue signing in' : 'Sign in to the pod'}</Button>
{s?.state === 'expired' && <Text size="sm" c="dimmed">The last sign-in browser closed after a while without input.</Text>}
{s?.state === 'failed' && <Text size="sm" c="dimmed">The last sign-in browser stopped{s.error ? `: ${s.error}` : ''}.</Text>}
</Group>
</Can>
)}
{open && (
<>
<Text size="xs" c="dimmed" data-testid="sign-in-where">
Showing {PAGE_WORDS[s?.page ?? 'blank'] ?? 'the page'}. Click in the picture, then type. It closes after {Math.ceil((s?.idle_left_s ?? 900) / 60)} minute(s) without input.
</Text>
<div tabIndex={0} onKeyDown={key} role="application" aria-label="The sign-in browser: click to focus, then type" className="fpt-card"
style={{ padding: 0, overflow: 'hidden', outlineOffset: 2, cursor: 'pointer', maxWidth: 960 }}>
<img ref={img} src={`/api/runs/${encodeURIComponent(runId)}/sign-in/frame?t=${tick}`} alt="The sign-in browser on the pod"
onClick={click} style={{ display: 'block', width: '100%', aspectRatio: `${BROWSER.width} / ${BROWSER.height}`, background: 'var(--fpt-surface-2)' }} />
</div>
<Group gap="xs" wrap="wrap">
<TextInput size="xs" aria-label="Text to type into the sign-in browser" placeholder="Type text, then Send (or click the picture and type)" type="password"
value={text} onChange={(e) => setText(e.currentTarget.value)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); typeText(); } }}
style={{ flex: '1 1 260px' }} autoComplete="off" />
<Button size="xs" variant="default" onClick={typeText} disabled={!text}>Send</Button>
{['Enter', 'Tab', 'Backspace'].map((k) => <Button key={k} size="xs" variant="subtle" onClick={() => send.mutate([{ type: 'press', key: k }])}>{k}</Button>)}
</Group>
<Group gap="xs">
<Button size="xs" onClick={() => finish.mutate()} loading={finish.isPending} title="Use this when you see the Fusion home page and Astra has not gone on by itself">I have signed in</Button>
<Button size="xs" variant="subtle" color="red" onClick={() => cancel.mutate()} loading={cancel.isPending}>Close the sign-in browser</Button>
</Group>
</>
)}
<ErrorAlert error={start.error ?? send.error ?? finish.error ?? cancel.error ?? status.error} />
</Stack>
);
}