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

This commit is contained in:
a2a-cloud
2026-07-18 05:29:04 +00:00
parent 6e2df560d5
commit 62faab9c37

View File

@@ -1,253 +1,158 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { import {
callSkillWithSession, callSkill,
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 [comparisonId, setComparisonId] = useState("studio-quote-v1"); const [selectedSkillName, setSelectedSkillName] = useState("");
const [quotes, setQuotes] = useState(STARTER_QUOTES); const [argsText, setArgsText] = useState("{}");
const [weights, setWeights] = useState({ price: 50, delivery: 30, warranty: 20 });
const [result, setResult] = useState(null); const [result, setResult] = useState(null);
const [status, setStatus] = useState("Loading QuoteJudge Studio…"); const [error, setError] = useState(null);
const [running, setRunning] = useState(false); const [running, setRunning] = useState(false);
const [files, setFiles] = useState([]);
useEffect(() => { useEffect(() => {
loadAgentConfig() loadAgentConfig()
.then(async (data) => { .then((data) => {
setConfig(data); setConfig(data);
try { const firstSkill = data.skills?.[0];
setSession(await loadSession(data)); if (firstSkill) {
} catch { setSelectedSkillName(firstSkill.name);
setSession({ authenticated: false }); setArgsText(JSON.stringify(sampleArgs(firstSkill), null, 2));
} }
setStatus("Ready to compare vendor quotes."); return loadSession(data).catch(() => null);
}) })
.catch((error) => setStatus(error.message || String(error))); .then((sessionData) => setSession(sessionData))
.catch((err) => setError(err.message || String(err)));
}, []); }, []);
const needsSignIn = Boolean(config?.auth?.invokeRequiresSession && session && !session.authenticated); const selectedSkill = useMemo(
const signInHref = useMemo(() => (config && needsSignIn ? signInUrl(config) : null), [config, needsSignIn]); () => config?.skills?.find((skill) => skill.name === selectedSkillName),
const totalWeight = Number(weights.price || 0) + Number(weights.delivery || 0) + Number(weights.warranty || 0); [config, selectedSkillName],
);
function updateQuote(index, field, value) { const needsSignIn = Boolean(
setQuotes((current) => current.map((quote, i) => (i === index ? { ...quote, [field]: value } : quote))); config?.auth?.invokeRequiresSession && session && !session.authenticated,
);
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);
} }
function addQuote() { async function runSkill(event) {
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) return; if (!config || !selectedSkill) return;
setRunning(true); setRunning(true);
setError(null);
setResult(null); setResult(null);
setStatus("Scoring quotes and saving result…");
try { try {
const data = await callSkillWithSession(config, "compare_quotes", { const args = JSON.parse(argsText || "{}");
comparison_id: comparisonId, const data = await callSkill(config, selectedSkill.name, args);
quotes: normalizeQuotes(),
weights: {
price: Number(weights.price),
delivery: Number(weights.delivery),
warranty: Number(weights.warranty),
},
});
setResult(data); setResult(data);
setStatus(data.ok ? `Saved ${data.comparison_id}. Recommendation: ${data.recommendation.vendor}.` : data.message); } catch (err) {
} catch (error) { setError(err.message || String(err));
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 <main className="loading"><p>{status}</p></main>; return (
<main className="loading">
<p>{error || "Loading A2A agent contract..."}</p>
</main>
);
} }
return ( return (
<main className="studio-shell"> <main className="app-shell">
<header className="hero"> <aside className="sidebar">
<div> <div>
<p className="eyebrow">QuoteJudge Studio</p> <p className="eyebrow">A2A packed app</p>
<h1>Choose the best vendor quote with weighted evidence.</h1> <h1>quote-judge-studio-v1</h1>
<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> <p className="agent-meta">
{config.agent.name} v{config.agent.version}
</p>
</div> </div>
<div className="session-card">
<span>{session?.authenticated ? "Signed in" : "Signed out"}</span> <nav className="skill-list" aria-label="Agent skills">
<strong>{session?.user?.email || session?.org?.slug || "Platform session required"}</strong> {(config.skills || []).map((skill) => (
{needsSignIn && signInHref ? <a className="button secondary" href={signInHref}>Sign in to run</a> : null} <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> </div>
</aside>
<section className="workbench">
<header className="toolbar">
<div>
<p className="eyebrow">Skill runner</p>
<h2>{selectedSkill?.name || "No skills found"}</h2>
</div>
<a href={config.docs.base} rel="noreferrer" target="_blank">
Docs
</a>
</header> </header>
<form className="panel workflow" onSubmit={runCompare}> {selectedSkill ? (
<section className="controls-grid"> <form className="runner" onSubmit={runSkill}>
<label> <label>
Comparison ID Arguments JSON
<input value={comparisonId} onChange={(event) => setComparisonId(event.target.value)} /> <textarea
spellCheck="false"
value={argsText}
onChange={(event) => setArgsText(event.target.value)}
/>
</label> </label>
<label> <button disabled={running} type="submit">
Price weight {running ? "Running..." : `Run ${selectedSkill.name}`}
<input type="number" min="0" max="100" value={weights.price} onChange={(event) => setWeights({ ...weights, price: event.target.value })} /> </button>
</label>
<label>
Delivery weight
<input type="number" min="0" max="100" value={weights.delivery} onChange={(event) => setWeights({ ...weights, delivery: event.target.value })} />
</label>
<label>
Warranty weight
<input type="number" min="0" max="100" value={weights.warranty} onChange={(event) => setWeights({ ...weights, warranty: event.target.value })} />
</label>
</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> </form>
) : (
<p className="empty">Add a `@a2a.tool` to your agent to make it callable here.</p>
)}
<section className="panel upload-panel"> <section className="panels">
<div> <div className="panel">
<h2>Browser upload bridge</h2> <h3>Input schema</h3>
<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> <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> </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>
<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>
);
}