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

This commit is contained in:
a2a-cloud
2026-07-18 02:33:34 +00:00
parent d29538ae51
commit b9d4623bee

View File

@@ -1,157 +1,306 @@
import { useEffect, useMemo, useState } from "react";
import {
callSkill,
loadAgentConfig,
loadSession,
sampleArgs,
signInUrl,
} from "./a2a.js";
import { callSkill, loadAgentConfig, loadSession, signInUrl } from "./a2a.js";
const MAX_UPLOAD_BYTES = 64 * 1024;
const DEFAULT_QUOTES = [
{ vendor: "Acme Bearings", unit_price: 10.75, quantity: 500, delivery_days: 12, warranty_months: 12 },
{ vendor: "Beta Industrial", unit_price: 9.1, quantity: 500, delivery_days: 8, warranty_months: 18 },
];
const DEFAULT_WEIGHTS = { price: 50, delivery: 30, warranty: 20 };
function emptyQuote(index) {
return { vendor: `Vendor ${index + 1}`, unit_price: 0, quantity: 1, delivery_days: 0, warranty_months: 0 };
}
function toNumber(value) {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : 0;
}
function csvToQuotes(text) {
const lines = text.split(/\r?\n/).filter((line) => line.trim());
if (lines.length < 2) throw new Error("CSV needs a header row and at least two quote rows.");
const headers = lines[0].split(",").map((item) => item.trim());
const required = ["vendor", "unit_price", "quantity", "delivery_days", "warranty_months"];
for (const key of required) {
if (!headers.includes(key)) throw new Error(`CSV missing ${key} header.`);
}
return lines.slice(1).map((line) => {
const cells = line.split(",").map((item) => item.trim());
const row = Object.fromEntries(headers.map((header, index) => [header, cells[index] ?? ""]));
return {
vendor: row.vendor,
unit_price: toNumber(row.unit_price),
quantity: Math.trunc(toNumber(row.quantity)),
delivery_days: Math.trunc(toNumber(row.delivery_days)),
warranty_months: Math.trunc(toNumber(row.warranty_months)),
};
});
}
function validateForm(comparisonId, quotes, weights) {
if (!comparisonId.trim()) return "Comparison ID is required.";
if (!/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,79}$/.test(comparisonId.trim())) {
return "Comparison ID must be 1-80 safe characters (letters, numbers, dash, underscore, colon, dot).";
}
if (quotes.length < 2) return "Add at least two quotes.";
if (quotes.length > 25) return "Compare at most 25 quotes.";
const vendors = new Set();
for (const quote of quotes) {
if (!quote.vendor.trim()) return "Every quote needs a vendor name.";
const key = quote.vendor.trim().toLowerCase();
if (vendors.has(key)) return "Vendor names must be unique.";
vendors.add(key);
if (toNumber(quote.unit_price) <= 0) return `${quote.vendor} needs a positive unit price.`;
if (Math.trunc(toNumber(quote.quantity)) <= 0) return `${quote.vendor} needs a positive quantity.`;
if (Math.trunc(toNumber(quote.delivery_days)) < 0) return `${quote.vendor} delivery days cannot be negative.`;
if (Math.trunc(toNumber(quote.warranty_months)) < 0) return `${quote.vendor} warranty cannot be negative.`;
}
if (toNumber(weights.price) + toNumber(weights.delivery) + toNumber(weights.warranty) <= 0) {
return "At least one weight must be greater than zero.";
}
return null;
}
async function fileToBase64(file) {
const buffer = await file.arrayBuffer();
let binary = "";
const bytes = new Uint8Array(buffer);
for (let i = 0; i < bytes.byteLength; i += 1) binary += String.fromCharCode(bytes[i]);
return btoa(binary);
}
function ScoreBar({ label, value }) {
const safe = Math.max(0, Math.min(100, Number(value) || 0));
return (
<div className="scorebar">
<span>{label}</span>
<div><i style={{ width: `${safe}%` }} /></div>
<b>{safe.toFixed(1)}</b>
</div>
);
}
export function App() {
const [config, setConfig] = useState(null);
const [session, setSession] = useState(null);
const [selectedSkillName, setSelectedSkillName] = useState("");
const [argsText, setArgsText] = useState("{}");
const [comparisonId, setComparisonId] = useState("studio-quote-v1");
const [quotes, setQuotes] = useState(DEFAULT_QUOTES);
const [weights, setWeights] = useState(DEFAULT_WEIGHTS);
const [result, setResult] = useState(null);
const [status, setStatus] = useState("Loading QuoteJudge...");
const [error, setError] = useState(null);
const [running, setRunning] = useState(false);
const [uploadFile, setUploadFile] = useState(null);
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));
setStatus(null);
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)));
.catch((err) => {
setError(err.message || String(err));
setStatus(null);
});
}, []);
const selectedSkill = useMemo(
() => config?.skills?.find((skill) => skill.name === selectedSkillName),
[config, selectedSkillName],
);
const needsSignIn = Boolean(config?.auth?.invokeRequiresSession && session && !session.authenticated);
const signInHref = useMemo(() => (config ? signInUrl(config) : null), [config]);
const winner = result?.ok ? result.recommendation : null;
const needsSignIn = Boolean(
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 updateQuote(index, field, value) {
setQuotes((items) => items.map((quote, i) => (i === index ? { ...quote, [field]: value } : quote)));
}
async function runSkill(event) {
function normalizedQuotes() {
return quotes.map((quote) => ({
vendor: quote.vendor.trim(),
unit_price: toNumber(quote.unit_price),
quantity: Math.trunc(toNumber(quote.quantity)),
delivery_days: Math.trunc(toNumber(quote.delivery_days)),
warranty_months: Math.trunc(toNumber(quote.warranty_months)),
}));
}
async function runCompare(event) {
event.preventDefault();
if (!config || !selectedSkill) return;
if (!config) return;
const cleanQuotes = normalizedQuotes();
const validation = validateForm(comparisonId, cleanQuotes, weights);
if (validation) {
setError(validation);
return;
}
setRunning(true);
setError(null);
setResult(null);
setStatus("Comparing quotes and saving recommendation...");
try {
const args = JSON.parse(argsText || "{}");
const data = await callSkill(config, selectedSkill.name, args);
let data;
if (uploadFile) {
if (uploadFile.size > MAX_UPLOAD_BYTES) throw new Error(`Upload must be at most ${MAX_UPLOAD_BYTES} bytes.`);
const mediaType = uploadFile.type || (uploadFile.name.endsWith(".json") ? "application/json" : "text/csv");
if (!["text/csv", "text/plain", "application/json"].includes(mediaType)) {
throw new Error("Upload must be CSV, plain text CSV, or JSON.");
}
data = await callSkill(config, "compare_quotes_upload", {
comparison_id: comparisonId.trim(),
upload: { filename: uploadFile.name, media_type: mediaType, data_base64: await fileToBase64(uploadFile) },
weights: { price: toNumber(weights.price), delivery: toNumber(weights.delivery), warranty: toNumber(weights.warranty) },
});
} else {
data = await callSkill(config, "compare_quotes", {
comparison_id: comparisonId.trim(),
quotes: cleanQuotes,
weights: { price: toNumber(weights.price), delivery: toNumber(weights.delivery), warranty: toNumber(weights.warranty) },
});
}
setResult(data);
if (!data.ok) setError(data.message || data.code || "Comparison failed.");
} catch (err) {
if (/401|sign in/i.test(err.message || "")) setError("Session required or expired. Use Sign in to run, then retry.");
else setError(err.message || String(err));
} finally {
setRunning(false);
setStatus(null);
}
}
async function reloadComparison() {
if (!config) return;
setRunning(true);
setError(null);
setStatus("Reopening saved comparison...");
try {
const data = await callSkill(config, "get_comparison", { comparison_id: comparisonId.trim() });
setResult(data);
if (!data.ok) setError(data.message || data.code || "Not found.");
} catch (err) {
setError(err.message || String(err));
} finally {
setRunning(false);
setStatus(null);
}
}
async function handleUpload(file) {
setUploadFile(file || null);
setError(null);
if (!file) return;
if (file.size > MAX_UPLOAD_BYTES) {
setError(`Upload must be at most ${MAX_UPLOAD_BYTES} bytes.`);
return;
}
const text = await file.text();
try {
let parsed;
if ((file.type || "").includes("json") || file.name.endsWith(".json")) {
const raw = JSON.parse(text);
parsed = Array.isArray(raw) ? raw : raw.quotes;
} else {
parsed = csvToQuotes(text);
}
if (Array.isArray(parsed) && parsed.length) setQuotes(parsed);
} catch (err) {
setError(`Preview parse failed: ${err.message || String(err)}. You can still clear the file and paste rows manually.`);
}
}
if (!config) {
return (
<main className="loading">
<p>{error || "Loading A2A agent contract..."}</p>
</main>
);
return <main className="loading"><p>{status || error || "Loading..."}</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>quote-judge-studio-v1</h1>
<p className="agent-meta">
{config.agent.name} v{config.agent.version}
</p>
<p className="eyebrow">QuoteJudge</p>
<h1>Pick the best vendor quote with transparent weighted scoring.</h1>
<p className="lede">Paste or upload quote rows, weight price/delivery/warranty, save the recommendation, and reopen it later under your A2A Cloud user account.</p>
</div>
<aside className="session-card">
<span>{session?.authenticated ? "Signed in" : "Signed out"}</span>
<strong>{session?.user?.email || session?.email || session?.org?.slug || "A2A Cloud user"}</strong>
{needsSignIn && signInHref ? <a href={signInHref}>Sign in to run</a> : null}
<small>Agent: {config.agent.name} v{config.agent.version} · MCP {config.card?.mcp_endpoint || "/mcp"}</small>
</aside>
</section>
<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>
</aside>
<section className="workbench">
<header className="toolbar">
<div>
<p className="eyebrow">Skill runner</p>
<h2>{selectedSkill?.name || "No skills found"}</h2>
<form className="studio" onSubmit={runCompare}>
<section className="panel inputs">
<div className="section-title">
<div><p className="eyebrow">1 · Input</p><h2>Quotes</h2></div>
<button type="button" onClick={() => setQuotes((items) => [...items, emptyQuote(items.length)])}>Add quote</button>
</div>
<a href={config.docs.base} rel="noreferrer" target="_blank">
Docs
</a>
</header>
{selectedSkill ? (
<form className="runner" onSubmit={runSkill}>
<label>
Arguments JSON
<textarea
spellCheck="false"
value={argsText}
onChange={(event) => setArgsText(event.target.value)}
/>
<label className="field">Comparison ID
<input value={comparisonId} onChange={(event) => setComparisonId(event.target.value)} placeholder="studio-quote-v1" />
</label>
<div className="upload-box">
<label>Upload CSV/JSON (bounded browser bridge, max 64 KiB)
<input accept=".csv,.json,text/csv,text/plain,application/json" type="file" onChange={(event) => handleUpload(event.target.files?.[0])} />
</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>
{uploadFile ? <button type="button" onClick={() => setUploadFile(null)}>Use pasted rows instead</button> : null}
</div>
<div className="panel">
<h3>Result</h3>
<pre>{error || JSON.stringify(result, null, 2) || "No run yet."}</pre>
<div className="quotes-table" role="table" aria-label="Vendor quotes">
<div className="quote-row header" role="row">
<span>Vendor</span><span>Unit price</span><span>Qty</span><span>Delivery days</span><span>Warranty months</span><span />
</div>
{quotes.map((quote, index) => (
<div className="quote-row" role="row" key={`${quote.vendor}-${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" min="0" step="0.01" value={quote.unit_price} onChange={(event) => updateQuote(index, "unit_price", event.target.value)} />
<input aria-label={`Quantity ${index + 1}`} type="number" min="1" step="1" value={quote.quantity} onChange={(event) => updateQuote(index, "quantity", event.target.value)} />
<input aria-label={`Delivery days ${index + 1}`} type="number" min="0" step="1" value={quote.delivery_days} onChange={(event) => updateQuote(index, "delivery_days", event.target.value)} />
<input aria-label={`Warranty months ${index + 1}`} type="number" min="0" step="1" value={quote.warranty_months} onChange={(event) => updateQuote(index, "warranty_months", event.target.value)} />
<button type="button" disabled={quotes.length <= 1} onClick={() => setQuotes((items) => items.filter((_, i) => i !== index))}>Remove</button>
</div>
))}
</div>
</section>
<section className="panel weights">
<div><p className="eyebrow">2 · Priorities</p><h2>Weights</h2></div>
{Object.keys(weights).map((key) => (
<label className="slider" key={key}>{key}
<input type="range" min="0" max="100" value={weights[key]} onChange={(event) => setWeights((value) => ({ ...value, [key]: Number(event.target.value) }))} />
<output>{weights[key]}</output>
</label>
))}
<div className="actions">
<button disabled={running || needsSignIn} type="submit">{running ? "Working..." : "Compare & save"}</button>
<button disabled={running || needsSignIn} type="button" onClick={reloadComparison}>Reopen saved</button>
</div>
{needsSignIn ? <p className="notice">Sign in with A2A Cloud to run tools and access your user-scoped database records.</p> : null}
{status ? <p className="notice">{status}</p> : null}
{error ? <p className="error" role="alert">{error}</p> : null}
</section>
</form>
<section className="panel result-panel">
<div className="section-title"><div><p className="eyebrow">3 · Recommendation</p><h2>{winner ? winner.vendor : "No comparison yet"}</h2></div>{result?.reloaded ? <span className="pill">Reloaded from Postgres</span> : null}</div>
{result?.ok ? (
<div className="result-grid">
<div className="winner-card"><strong>{winner.vendor}</strong><span>{winner.weighted_score.toFixed(1)} weighted score</span><p>{winner.rationale}</p></div>
<div className="scores">
{result.quotes.map((quote) => <ScoreBar key={quote.vendor} label={quote.vendor} value={quote.weighted_score} />)}
</div>
<table>
<thead><tr><th>Vendor</th><th>Total price</th><th>Delivery</th><th>Warranty</th><th>Weighted</th></tr></thead>
<tbody>{result.quotes.map((quote) => <tr key={quote.vendor}><td>{quote.vendor}</td><td>{quote.total_price.toLocaleString(undefined, { style: "currency", currency: "BRL" })}</td><td>{quote.delivery_days} days</td><td>{quote.warranty_months} mo</td><td>{quote.weighted_score.toFixed(1)}</td></tr>)}</tbody>
</table>
<p className="receipt">Receipt persisted: {String(result.receipt?.persisted)} · comparison_id={result.comparison_id}</p>
</div>
) : (
<p className="empty">Run the success fixture or upload your own CSV/JSON to see a saved recommendation here.</p>
)}
</section>
</main>
);