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

This commit is contained in:
a2a-cloud
2026-07-18 05:11:42 +00:00
parent c042bd847c
commit 6b8b63e26d

View File

@@ -1,158 +1,253 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { import {
callSkill, callSkillWithSession,
fileToBrowserDocument,
loadAgentConfig, loadAgentConfig,
loadSession, loadSession,
sampleArgs,
signInUrl, signInUrl,
} from "./a2a.js"; } from "./a2a.js";
const MAX_UPLOAD_BYTES = 256000;
const STARTER_QUOTES = [
{ vendor: "Acme Bearings", unit_price: 10.75, quantity: 500, delivery_days: 12, warranty_months: 12, currency: "BRL" },
{ vendor: "Beta Industrial", unit_price: 9.1, quantity: 500, delivery_days: 8, warranty_months: 18, currency: "BRL" },
];
export function App() { export function App() {
const [config, setConfig] = useState(null); const [config, setConfig] = useState(null);
const [session, setSession] = useState(null); const [session, setSession] = useState(null);
const [selectedSkillName, setSelectedSkillName] = useState(""); const [comparisonId, setComparisonId] = useState("studio-quote-v1");
const [argsText, setArgsText] = useState("{}"); const [quotes, setQuotes] = useState(STARTER_QUOTES);
const [weights, setWeights] = useState({ price: 50, delivery: 30, warranty: 20 });
const [result, setResult] = useState(null); const [result, setResult] = useState(null);
const [error, setError] = useState(null); const [status, setStatus] = useState("Loading QuoteJudge Studio…");
const [running, setRunning] = useState(false); const [running, setRunning] = useState(false);
const [files, setFiles] = useState([]);
useEffect(() => { useEffect(() => {
loadAgentConfig() loadAgentConfig()
.then((data) => { .then(async (data) => {
setConfig(data); setConfig(data);
const firstSkill = data.skills?.[0]; try {
if (firstSkill) { setSession(await loadSession(data));
setSelectedSkillName(firstSkill.name); } catch {
setArgsText(JSON.stringify(sampleArgs(firstSkill), null, 2)); setSession({ authenticated: false });
} }
return loadSession(data).catch(() => null); setStatus("Ready to compare vendor quotes.");
}) })
.then((sessionData) => setSession(sessionData)) .catch((error) => setStatus(error.message || String(error)));
.catch((err) => setError(err.message || String(err)));
}, []); }, []);
const selectedSkill = useMemo( const needsSignIn = Boolean(config?.auth?.invokeRequiresSession && session && !session.authenticated);
() => config?.skills?.find((skill) => skill.name === selectedSkillName), const signInHref = useMemo(() => (config && needsSignIn ? signInUrl(config) : null), [config, needsSignIn]);
[config, selectedSkillName], const totalWeight = Number(weights.price || 0) + Number(weights.delivery || 0) + Number(weights.warranty || 0);
);
const needsSignIn = Boolean( function updateQuote(index, field, value) {
config?.auth?.invokeRequiresSession && session && !session.authenticated, setQuotes((current) => current.map((quote, i) => (i === index ? { ...quote, [field]: value } : quote)));
);
const signInHref = useMemo(
() => (config && needsSignIn ? signInUrl(config) : null),
[config, needsSignIn],
);
function selectSkill(skill) {
setSelectedSkillName(skill.name);
setArgsText(JSON.stringify(sampleArgs(skill), null, 2));
setResult(null);
setError(null);
} }
async function runSkill(event) { function addQuote() {
setQuotes((current) => [...current, { vendor: "", unit_price: 0, quantity: 1, delivery_days: 0, warranty_months: 0, currency: "BRL" }]);
}
function removeQuote(index) {
setQuotes((current) => current.filter((_, i) => i !== index));
}
function normalizeQuotes() {
return quotes.map((quote) => ({
vendor: String(quote.vendor || "").trim(),
unit_price: Number(quote.unit_price),
quantity: Number(quote.quantity),
delivery_days: Number(quote.delivery_days),
warranty_months: Number(quote.warranty_months),
currency: quote.currency || "BRL",
}));
}
async function runCompare(event) {
event.preventDefault(); event.preventDefault();
if (!config || !selectedSkill) return; if (!config) return;
setRunning(true); setRunning(true);
setError(null);
setResult(null); setResult(null);
setStatus("Scoring quotes and saving result…");
try { try {
const args = JSON.parse(argsText || "{}"); const data = await callSkillWithSession(config, "compare_quotes", {
const data = await callSkill(config, selectedSkill.name, args); comparison_id: comparisonId,
quotes: normalizeQuotes(),
weights: {
price: Number(weights.price),
delivery: Number(weights.delivery),
warranty: Number(weights.warranty),
},
});
setResult(data); setResult(data);
} catch (err) { setStatus(data.ok ? `Saved ${data.comparison_id}. Recommendation: ${data.recommendation.vendor}.` : data.message);
setError(err.message || String(err)); } catch (error) {
setStatus(error.message || String(error));
} finally {
setRunning(false);
}
}
async function reopen() {
if (!config) return;
setRunning(true);
setResult(null);
setStatus("Reopening saved comparison…");
try {
const data = await callSkillWithSession(config, "get_comparison", { comparison_id: comparisonId });
setResult(data);
setStatus(data.ok ? `Reopened ${data.comparison_id}.` : data.message);
} catch (error) {
setStatus(error.message || String(error));
} finally {
setRunning(false);
}
}
async function uploadAndCompare() {
if (!config || !files.length) return;
setRunning(true);
setResult(null);
setStatus("Encoding browser upload and comparing…");
try {
const tooLarge = files.find((file) => file.size > MAX_UPLOAD_BYTES);
if (tooLarge) throw new Error(`${tooLarge.name} exceeds ${MAX_UPLOAD_BYTES} bytes.`);
const documents = await Promise.all(files.map(fileToBrowserDocument));
const data = await callSkillWithSession(config, "compare_uploaded_quotes_browser", {
comparison_id: comparisonId,
documents,
weights: {
price: Number(weights.price),
delivery: Number(weights.delivery),
warranty: Number(weights.warranty),
},
});
setResult(data);
setStatus(data.ok ? `Uploaded and saved ${data.comparison_id}.` : data.message);
} catch (error) {
setStatus(error.message || String(error));
} finally { } finally {
setRunning(false); setRunning(false);
} }
} }
if (!config) { if (!config) {
return ( return <main className="loading"><p>{status}</p></main>;
<main className="loading">
<p>{error || "Loading A2A agent contract..."}</p>
</main>
);
} }
return ( return (
<main className="app-shell"> <main className="studio-shell">
<aside className="sidebar"> <header className="hero">
<div> <div>
<p className="eyebrow">A2A packed app</p> <p className="eyebrow">QuoteJudge Studio</p>
<h1>quote-judge-studio-v1</h1> <h1>Choose the best vendor quote with weighted evidence.</h1>
<p className="agent-meta"> <p className="lede">Paste rows or upload JSON/CSV, weight price, delivery, and warranty, then persist a receipt-backed recommendation you can reopen later.</p>
{config.agent.name} v{config.agent.version}
</p>
</div> </div>
<div className="session-card">
<nav className="skill-list" aria-label="Agent skills"> <span>{session?.authenticated ? "Signed in" : "Signed out"}</span>
{(config.skills || []).map((skill) => ( <strong>{session?.user?.email || session?.org?.slug || "Platform session required"}</strong>
<button {needsSignIn && signInHref ? <a className="button secondary" href={signInHref}>Sign in to run</a> : null}
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> </div>
</aside> </header>
<section className="workbench"> <form className="panel workflow" onSubmit={runCompare}>
<header className="toolbar"> <section className="controls-grid">
<div> <label>
<p className="eyebrow">Skill runner</p> Comparison ID
<h2>{selectedSkill?.name || "No skills found"}</h2> <input value={comparisonId} onChange={(event) => setComparisonId(event.target.value)} />
</div> </label>
<a href={config.docs.base} rel="noreferrer" target="_blank"> <label>
Docs Price weight
</a> <input type="number" min="0" max="100" value={weights.price} onChange={(event) => setWeights({ ...weights, price: event.target.value })} />
</header> </label>
<label>
{selectedSkill ? ( Delivery weight
<form className="runner" onSubmit={runSkill}> <input type="number" min="0" max="100" value={weights.delivery} onChange={(event) => setWeights({ ...weights, delivery: event.target.value })} />
<label> </label>
Arguments JSON <label>
<textarea Warranty weight
spellCheck="false" <input type="number" min="0" max="100" value={weights.warranty} onChange={(event) => setWeights({ ...weights, warranty: event.target.value })} />
value={argsText} </label>
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>
)}
<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> </section>
<p className={totalWeight > 0 ? "hint" : "hint warning"}>Total weight: {totalWeight}. Values are normalized by the backend.</p>
<div className="quote-table" role="table" aria-label="Vendor quotes">
<div className="quote-row quote-head" role="row">
<span>Vendor</span><span>Unit price</span><span>Qty</span><span>Delivery days</span><span>Warranty months</span><span></span>
</div>
{quotes.map((quote, index) => (
<div className="quote-row" role="row" key={index}>
<input aria-label={`Vendor ${index + 1}`} value={quote.vendor} onChange={(event) => updateQuote(index, "vendor", event.target.value)} />
<input aria-label={`Unit price ${index + 1}`} type="number" step="0.01" value={quote.unit_price} onChange={(event) => updateQuote(index, "unit_price", event.target.value)} />
<input aria-label={`Quantity ${index + 1}`} type="number" value={quote.quantity} onChange={(event) => updateQuote(index, "quantity", event.target.value)} />
<input aria-label={`Delivery days ${index + 1}`} type="number" value={quote.delivery_days} onChange={(event) => updateQuote(index, "delivery_days", event.target.value)} />
<input aria-label={`Warranty months ${index + 1}`} type="number" value={quote.warranty_months} onChange={(event) => updateQuote(index, "warranty_months", event.target.value)} />
<button type="button" className="ghost" onClick={() => removeQuote(index)} disabled={quotes.length <= 1}>Remove</button>
</div>
))}
</div>
<div className="actions">
<button type="button" className="button secondary" onClick={addQuote}>Add quote</button>
<button type="submit" className="button" disabled={running || needsSignIn}>{running ? "Working…" : "Compare & save"}</button>
<button type="button" className="button secondary" onClick={reopen} disabled={running || needsSignIn}>Reopen saved</button>
</div>
</form>
<section className="panel upload-panel">
<div>
<h2>Browser upload bridge</h2>
<p>Upload bounded JSON, CSV, or text files. The browser sends base64 JSON to <code>compare_uploaded_quotes_browser</code>; external clients can still use <code>compare_uploaded_quote_file</code>.</p>
</div>
<input type="file" multiple accept=".json,.csv,text/plain,application/json,text/csv" onChange={(event) => setFiles(Array.from(event.target.files || []))} />
<button className="button secondary" type="button" onClick={uploadAndCompare} disabled={running || needsSignIn || files.length === 0}>Upload & compare</button>
</section> </section>
<section className="status" aria-live="polite">{status}</section>
{result ? <ResultPanel result={result} /> : <EmptyState />}
</main> </main>
); );
} }
function EmptyState() {
return (
<section className="panel empty-state">
<h2>No result yet</h2>
<p>Run the success fixture or upload a quote file. Results and production receipts are returned from the live backend, not mocked in the browser.</p>
</section>
);
}
function ResultPanel({ result }) {
if (!result.ok) {
return (
<section className="panel result error-result">
<h2>Validation needed</h2>
<p>{result.message}</p>
<ul>{(result.issues || []).map((issue) => <li key={`${issue.code}-${issue.field}`}>{issue.code}: {issue.action || issue.message}</li>)}</ul>
</section>
);
}
return (
<section className="panel result">
<div className="recommendation">
<p className="eyebrow">Recommendation</p>
<h2>{result.recommendation.vendor}</h2>
<p>{result.recommendation.why}</p>
{result.receipt ? <small>Receipt {result.receipt.receipt_id}</small> : null}
</div>
<div className="ranking">
{(result.quotes_ranked || []).map((quote, index) => (
<article className="rank-card" key={quote.vendor}>
<strong>#{index + 1} {quote.vendor}</strong>
<span>Score {quote.scores.weighted_total}</span>
<span>{quote.currency} {quote.total_price} · {quote.delivery_days} days · {quote.warranty_months} month warranty</span>
</article>
))}
</div>
</section>
);
}