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

This commit is contained in:
a2a-cloud
2026-07-18 04:46:38 +00:00
parent dfdc926277
commit 3a3c222a8c

View File

@@ -1,66 +1,74 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { import { callSkill, loadAgentConfig, loadSession, signInUrl } from "./a2a.js";
callSkill,
loadAgentConfig, const sampleQuotes = [
loadSession, { vendor: "Acme Bearings", unit_price: 10.75, quantity: 500, delivery_days: 12, warranty_months: 12 },
sampleArgs, { vendor: "Beta Industrial", unit_price: 9.1, quantity: 500, delivery_days: 8, warranty_months: 18 },
signInUrl, ];
} from "./a2a.js";
const defaultWeights = { price: 50, delivery: 30, warranty: 20 };
const maxUploadBytes = 64 * 1024;
const acceptedTypes = ["application/json", "text/csv", "text/plain"];
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 [quotesText, setQuotesText] = useState(JSON.stringify(sampleQuotes, null, 2));
const [weights, setWeights] = useState(defaultWeights);
const [result, setResult] = useState(null); const [result, setResult] = useState(null);
const [history, setHistory] = useState([]);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [notice, setNotice] = useState(null);
const [running, setRunning] = useState(false); const [running, setRunning] = useState(false);
useEffect(() => { useEffect(() => {
loadAgentConfig() loadAgentConfig()
.then((data) => { .then(async (data) => {
setConfig(data); setConfig(data);
const firstSkill = data.skills?.[0]; const sessionData = await loadSession(data).catch(() => ({ authenticated: false }));
if (firstSkill) { setSession(sessionData);
setSelectedSkillName(firstSkill.name); if (!data.auth?.invokeRequiresSession || sessionData?.authenticated) {
setArgsText(JSON.stringify(sampleArgs(firstSkill), null, 2)); refreshHistory(data).catch(() => null);
} }
return loadSession(data).catch(() => null);
}) })
.then((sessionData) => setSession(sessionData))
.catch((err) => setError(err.message || String(err))); .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 needsSignIn = Boolean( async function refreshHistory(activeConfig = config) {
config?.auth?.invokeRequiresSession && session && !session.authenticated, if (!activeConfig) return;
); const data = await callSkill(activeConfig, "list_comparisons", { limit: 10 });
const signInHref = useMemo( if (data?.ok) setHistory(data.comparisons || []);
() => (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 parseQuotes() {
try {
const parsed = JSON.parse(quotesText);
if (!Array.isArray(parsed)) throw new Error("Paste a JSON array of quote objects.");
return parsed;
} catch (err) {
throw new Error(`Quote JSON is invalid: ${err.message || String(err)}`);
}
}
async function compare(event) {
event.preventDefault(); event.preventDefault();
if (!config || !selectedSkill) return; if (!config) return;
setRunning(true); setRunning(true);
setError(null); setError(null);
setResult(null); setNotice(null);
try { try {
const args = JSON.parse(argsText || "{}"); const data = await callSkill(config, "compare_quotes", {
const data = await callSkill(config, selectedSkill.name, args); comparison_id: comparisonId.trim(),
quotes: parseQuotes(),
weights,
});
setResult(data); setResult(data);
if (!data.ok) setNotice(data.message || "Validation failed. Check the highlighted response.");
if (data.ok) await refreshHistory();
} catch (err) { } catch (err) {
setError(err.message || String(err)); setError(err.message || String(err));
} finally { } finally {
@@ -68,91 +76,225 @@ export function App() {
} }
} }
async function reopen(id) {
if (!config) return;
setRunning(true);
setError(null);
setNotice(null);
try {
const data = await callSkill(config, "get_comparison", { comparison_id: id });
setComparisonId(id);
setResult(data);
if (!data.ok) setNotice(data.message || "Comparison not found.");
} catch (err) {
setError(err.message || String(err));
} finally {
setRunning(false);
}
}
async function handleUpload(event) {
const files = Array.from(event.target.files || []);
if (!files.length || !config) return;
setRunning(true);
setError(null);
setNotice(null);
try {
const documents = await Promise.all(files.map(fileToBrowserDocument));
const data = await callSkill(config, "compare_quotes_from_browser_upload", {
comparison_id: comparisonId.trim(),
documents,
weights,
});
setResult(data);
if (!data.ok) setNotice(data.message || "Upload validation failed.");
if (data.ok) await refreshHistory();
} catch (err) {
setError(err.message || String(err));
} finally {
setRunning(false);
event.target.value = "";
}
}
if (!config) { if (!config) {
return ( return <main className="loading"><p>{error || "Loading QuoteJudge Studio..."}</p></main>;
<main className="loading">
<p>{error || "Loading A2A agent contract..."}</p>
</main>
);
} }
return ( return (
<main className="app-shell"> <main className="app-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>Pick the best vendor quote with transparent weighted scoring.</h1>
<p className="agent-meta"> <p className="lede">
{config.agent.name} v{config.agent.version} Upload or paste at least two quotes, tune price/delivery/warranty weights, save the recommendation,
and reopen past runs from your platform-authenticated workspace.
</p> </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?.email || "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>
<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>
{selectedSkill ? ( <section className="grid">
<form className="runner" onSubmit={runSkill}> <form className="card workflow" onSubmit={compare}>
<div className="card-title">
<div>
<p className="eyebrow">Workflow</p>
<h2>Compare quotes</h2>
</div>
<button className="button" disabled={running || needsSignIn} type="submit">
{running ? "Running..." : "Compare & save"}
</button>
</div>
<label> <label>
Arguments JSON Comparison ID
<textarea <input value={comparisonId} onChange={(event) => setComparisonId(event.target.value)} maxLength={120} />
spellCheck="false" </label>
value={argsText}
onChange={(event) => setArgsText(event.target.value)} <fieldset className="weights">
<legend>Weights</legend>
{Object.keys(defaultWeights).map((key) => (
<label key={key}>
{key}
<input
type="number"
min="0"
max="100"
value={weights[key]}
onChange={(event) => setWeights({ ...weights, [key]: Number(event.target.value) })}
/> />
</label> </label>
<button disabled={running} type="submit"> ))}
{running ? "Running..." : `Run ${selectedSkill.name}`} </fieldset>
</button>
</form>
) : (
<p className="empty">Add a `@a2a.tool` to your agent to make it callable here.</p>
)}
<section className="panels"> <label>
<div className="panel"> Paste quote JSON
<h3>Input schema</h3> <textarea
<pre>{JSON.stringify(selectedSkill?.input_schema || {}, null, 2)}</pre> spellCheck="false"
value={quotesText}
onChange={(event) => setQuotesText(event.target.value)}
aria-describedby="quote-help"
/>
</label>
<p id="quote-help" className="help">
Required fields: vendor, unit_price, quantity, delivery_days, warranty_months. The fixture recommends Beta Industrial.
</p>
<div className="upload-box">
<label>
Upload JSON, CSV, or plain text
<input type="file" accept={acceptedTypes.join(",")} multiple onChange={handleUpload} disabled={running || needsSignIn} />
</label>
<small>Browser bridge limit: {Math.round(maxUploadBytes / 1024)}KB per file, 4 files.</small>
</div> </div>
<div className="panel">
<h3>Result</h3> {needsSignIn ? <p className="notice">Sign in with your A2A Cloud session to run tools and persist results.</p> : null}
<pre>{error || JSON.stringify(result, null, 2) || "No run yet."}</pre> {notice ? <p className="notice">{notice}</p> : null}
{error ? <p className="error">{error}</p> : null}
</form>
<section className="card history">
<div className="card-title">
<div>
<p className="eyebrow">Persistence</p>
<h2>Saved comparisons</h2>
</div> </div>
<button className="button secondary" type="button" onClick={() => refreshHistory()} disabled={running || needsSignIn}>Refresh</button>
</div>
{history.length ? (
<ul>
{history.map((item) => (
<li key={item.comparison_id}>
<button type="button" onClick={() => reopen(item.comparison_id)}>
<strong>{item.comparison_id}</strong>
<span>{item.recommendation_vendor} · {item.quote_count || "?"} quotes</span>
</button>
</li>
))}
</ul>
) : (
<p className="empty">No saved comparisons loaded yet. Run the fixture or refresh after signing in.</p>
)}
</section> </section>
</section> </section>
<ResultPanel result={result} />
</main> </main>
); );
} }
function ResultPanel({ result }) {
if (!result) {
return <section className="card result"><p className="empty">Results will appear here after a comparison or reload call.</p></section>;
}
if (!result.ok) {
return (
<section className="card result error-state">
<p className="eyebrow">Validation</p>
<h2>{result.code}</h2>
<p>{result.message}</p>
<pre>{JSON.stringify(result.validation_errors || [], null, 2)}</pre>
</section>
);
}
return (
<section className="card result">
<div className="recommendation">
<p className="eyebrow">Recommendation</p>
<h2>{result.recommendation.vendor}</h2>
<p>{result.recommendation.reason}</p>
{result.receipt?.persisted ? <small>Receipt persisted: {result.receipt.receipt_id}</small> : null}
</div>
<div className="table-wrap">
<table>
<thead>
<tr>
<th>Vendor</th><th>Total</th><th>Unit</th><th>Delivery</th><th>Warranty</th><th>Score</th>
</tr>
</thead>
<tbody>
{(result.comparison_table || []).map((row) => (
<tr key={row.vendor}>
<td>{row.vendor}</td>
<td>{formatCurrency(row.total_price)}</td>
<td>{formatCurrency(row.unit_price)}</td>
<td>{row.delivery_days} days</td>
<td>{row.warranty_months} months</td>
<td>{row.scores.weighted_total}</td>
</tr>
))}
</tbody>
</table>
</div>
</section>
);
}
async function fileToBrowserDocument(file) {
if (file.size > maxUploadBytes) throw new Error(`${file.name} is larger than ${Math.round(maxUploadBytes / 1024)}KB.`);
const mediaType = file.type || guessMediaType(file.name);
if (!acceptedTypes.includes(mediaType)) throw new Error(`${file.name} must be JSON, CSV, or plain text.`);
const dataUrl = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(new Error(`Could not read ${file.name}`));
reader.readAsDataURL(file);
});
return { filename: file.name, media_type: mediaType, data_base64: dataUrl.split(",")[1] || "" };
}
function guessMediaType(filename) {
const lower = filename.toLowerCase();
if (lower.endsWith(".json")) return "application/json";
if (lower.endsWith(".csv")) return "text/csv";
return "text/plain";
}
function formatCurrency(value) {
return new Intl.NumberFormat(undefined, { style: "currency", currency: "BRL" }).format(Number(value || 0));
}