a2a-source-edit: write frontend/src/App.jsx

This commit is contained in:
a2a-cloud
2026-07-18 10:13:25 +00:00
parent 0ab33e06c0
commit 899da272c2

View File

@@ -1,41 +1,39 @@
import { useEffect, useMemo, useState } from "react";
import {
callSkill,
fileToBrowserDocument,
fixtureInvoices,
loadAgentConfig,
loadSession,
sampleArgs,
signInUrl,
} from "./a2a.js";
const defaultCaseId = "studio-invoice-v1";
export function App() {
const [config, setConfig] = useState(null);
const [session, setSession] = useState(null);
const [selectedSkillName, setSelectedSkillName] = useState("");
const [argsText, setArgsText] = useState("{}");
const [caseId, setCaseId] = useState(defaultCaseId);
const [invoiceText, setInvoiceText] = useState(JSON.stringify(fixtureInvoices(), null, 2));
const [documents, setDocuments] = useState([]);
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
const [running, setRunning] = useState(false);
const [decisionNote, setDecisionNote] = useState("Duplicate INV-100 needs AP review; INV-200 total does not match subtotal + tax.");
useEffect(() => {
loadAgentConfig()
.then((data) => {
.then(async (data) => {
setConfig(data);
const firstSkill = data.skills?.[0];
if (firstSkill) {
setSelectedSkillName(firstSkill.name);
setArgsText(JSON.stringify(sampleArgs(firstSkill), null, 2));
try {
setSession(await loadSession(data));
} catch {
setSession({ authenticated: false });
}
return loadSession(data).catch(() => null);
})
.then((sessionData) => setSession(sessionData))
.catch((err) => setError(err.message || String(err)));
}, []);
const selectedSkill = useMemo(
() => config?.skills?.find((skill) => skill.name === selectedSkillName),
[config, selectedSkillName],
);
const needsSignIn = Boolean(
config?.auth?.invokeRequiresSession && session && !session.authenticated,
);
@@ -44,115 +42,160 @@ export function App() {
[config, needsSignIn],
);
function selectSkill(skill) {
setSelectedSkillName(skill.name);
setArgsText(JSON.stringify(sampleArgs(skill), null, 2));
setResult(null);
setError(null);
}
async function runSkill(event) {
event.preventDefault();
if (!config || !selectedSkill) return;
async function invoke(skillName, args) {
if (!config) return null;
setRunning(true);
setError(null);
setResult(null);
try {
const args = JSON.parse(argsText || "{}");
const data = await callSkill(config, selectedSkill.name, args);
const data = await callSkill(config, skillName, args);
setResult(data);
return data;
} catch (err) {
setError(err.message || String(err));
if (err.status === 401 && signInUrl(config)) {
setError("Your session expired. Use Sign in to run, then retry.");
} else {
setError(err.message || String(err));
}
return null;
} finally {
setRunning(false);
}
}
async function reviewPasted(event) {
event.preventDefault();
let invoices;
try {
invoices = JSON.parse(invoiceText);
} catch {
setError("Paste valid JSON: an array of invoice objects.");
return;
}
await invoke("review_invoices", { case_id: caseId, invoices });
}
async function reviewUploads(event) {
event.preventDefault();
if (!documents.length) {
setError("Choose a JSON, CSV, or text invoice file first.");
return;
}
await invoke("review_invoice_uploads", { case_id: caseId, documents });
}
async function reopenCase() {
await invoke("get_invoice_case", { case_id: caseId });
}
async function recordDecision() {
await invoke("record_decision", {
case_id: caseId,
decision: {
decision_id: "ap-review-1",
invoice_number: "INV-100",
decision: "needs_review",
note: decisionNote,
},
});
}
async function onFilesChanged(event) {
setError(null);
const files = Array.from(event.target.files || []);
if (files.length > 5) {
setError("Choose at most five files.");
return;
}
try {
setDocuments(await Promise.all(files.map(fileToBrowserDocument)));
} catch (err) {
setError(err.message || String(err));
}
}
if (!config) {
return (
<main className="loading">
<p>{error || "Loading A2A agent contract..."}</p>
</main>
);
return <main className="loading"><p>{error || "Loading InvoiceGuard..."}</p></main>;
}
return (
<main className="app-shell">
<aside className="sidebar">
<main className="product-shell">
<section className="hero">
<div>
<p className="eyebrow">A2A packed app</p>
<h1>invoice-guard-studio-v1</h1>
<p className="agent-meta">
{config.agent.name} v{config.agent.version}
<p className="eyebrow">InvoiceGuard Studio</p>
<h1>Catch duplicate invoices before payment.</h1>
<p className="lede">
Paste or upload invoices, deterministically flag duplicate invoice numbers and total mismatches,
save the review case to your user-scoped database, then reopen it after refresh.
</p>
</div>
<nav className="skill-list" aria-label="Agent skills">
{(config.skills || []).map((skill) => (
<button
className={skill.name === selectedSkillName ? "skill active" : "skill"}
key={skill.name}
onClick={() => selectSkill(skill)}
type="button"
>
<span>{skill.name}</span>
<small>{skill.stream ? "streaming" : "request"}</small>
</button>
))}
</nav>
<div className="session">
<span>{session?.authenticated ? "Signed in" : needsSignIn ? "Signed out" : "Local session"}</span>
<strong>{session?.user?.email || session?.org?.slug || "dev@example.local"}</strong>
{/* Skills that spend the caller's LLM budget need a signed-in
visitor even when the page itself is public, so offer the way in
rather than failing at the first click. */}
{needsSignIn && signInHref ? (
<a className="signin" href={signInHref}>Sign in to run</a>
) : null}
<div className="session-card" aria-live="polite">
<span>{session?.authenticated ? "Signed in" : "Signed out"}</span>
<strong>{session?.user?.email || session?.org?.slug || "Platform session required"}</strong>
{needsSignIn && signInHref ? <a className="signin" href={signInHref}>Sign in to run</a> : null}
</div>
</aside>
</section>
<section className="workbench">
<header className="toolbar">
<div>
<p className="eyebrow">Skill runner</p>
<h2>{selectedSkill?.name || "No skills found"}</h2>
<section className="grid">
<form className="card input-card" onSubmit={reviewPasted}>
<h2>1. Review invoices</h2>
<label>
Case ID
<input value={caseId} onChange={(event) => setCaseId(event.target.value)} />
</label>
<label>
Invoice JSON
<textarea value={invoiceText} onChange={(event) => setInvoiceText(event.target.value)} spellCheck="false" />
</label>
<div className="button-row">
<button disabled={running || needsSignIn} type="submit">Review pasted invoices</button>
<button disabled={running || needsSignIn} type="button" onClick={reopenCase}>Reopen saved case</button>
</div>
<a href={config.docs.base} rel="noreferrer" target="_blank">
Docs
</a>
</header>
<p className="hint">Failure fixture: remove vendor or total from an invoice to see safe incomplete-invoice validation.</p>
</form>
{selectedSkill ? (
<form className="runner" onSubmit={runSkill}>
<label>
Arguments JSON
<textarea
spellCheck="false"
value={argsText}
onChange={(event) => setArgsText(event.target.value)}
/>
</label>
<button disabled={running} type="submit">
{running ? "Running..." : `Run ${selectedSkill.name}`}
</button>
</form>
) : (
<p className="empty">Add a `@a2a.tool` to your agent to make it callable here.</p>
)}
<form className="card" onSubmit={reviewUploads}>
<h2>2. Upload bridge</h2>
<p className="muted">Browser files are converted to bounded base64 JSON for the packed app. External clients can still use the typed FileUpload tool.</p>
<label>
JSON, CSV, or text invoice file
<input type="file" accept="application/json,text/json,text/csv,text/plain,.json,.csv,.txt" multiple onChange={onFilesChanged} />
</label>
<p className="hint">{documents.length ? `${documents.length} document(s) ready.` : "Max 5 files, 256 KiB each."}</p>
<button disabled={running || needsSignIn || !documents.length} type="submit">Review uploaded invoices</button>
</form>
<section className="panels">
<div className="panel">
<h3>Input schema</h3>
<pre>{JSON.stringify(selectedSkill?.input_schema || {}, null, 2)}</pre>
</div>
<div className="panel">
<h3>Result</h3>
<pre>{error || JSON.stringify(result, null, 2) || "No run yet."}</pre>
</div>
<section className="card">
<h2>3. Decision receipt</h2>
<label>
Decision note
<textarea className="small" value={decisionNote} onChange={(event) => setDecisionNote(event.target.value)} />
</label>
<button disabled={running || needsSignIn} type="button" onClick={recordDecision}>Record AP decision</button>
<p className="hint">Review writes and production execution receipts are committed in one database transaction.</p>
</section>
<ResultPanel result={result} error={error} running={running} />
</section>
</main>
);
}
function ResultPanel({ result, error, running }) {
return (
<section className="card result-card" aria-live="polite">
<h2>Review result</h2>
{running ? <p className="muted">Running deterministic checks...</p> : null}
{error ? <div className="error">{error}</div> : null}
{!error && result?.ok ? (
<div className="summary">
<div><span>Case</span><strong>{result.case_id}</strong></div>
<div><span>Duplicates</span><strong>{result.duplicate_count}</strong></div>
<div><span>Total mismatches</span><strong>{result.total_mismatch_count}</strong></div>
<div><span>Receipt</span><strong>{result.receipt?.receipt_id || "saved"}</strong></div>
</div>
) : null}
{!error && result?.ok === false ? <div className="error">{result.code}: {result.message}</div> : null}
<pre>{result ? JSON.stringify(result, null, 2) : "Run a review or reopen a case to see persisted evidence."}</pre>
</section>
);
}