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

This commit is contained in:
a2a-cloud
2026-07-18 05:08:49 +00:00
parent 2f63fa4e24
commit cbccfce732

View File

@@ -1,74 +1,66 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { callSkill, loadAgentConfig, loadSession, signInUrl } from "./a2a.js"; import {
callSkill,
const sampleQuotes = [ loadAgentConfig,
{ vendor: "Acme Bearings", unit_price: 10.75, quantity: 500, delivery_days: 12, warranty_months: 12 }, loadSession,
{ vendor: "Beta Industrial", unit_price: 9.1, quantity: 500, delivery_days: 8, warranty_months: 18 }, sampleArgs,
]; 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 [comparisonId, setComparisonId] = useState("studio-quote-v1"); const [selectedSkillName, setSelectedSkillName] = useState("");
const [quotesText, setQuotesText] = useState(JSON.stringify(sampleQuotes, null, 2)); const [argsText, setArgsText] = useState("{}");
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(async (data) => { .then((data) => {
setConfig(data); setConfig(data);
const sessionData = await loadSession(data).catch(() => ({ authenticated: false })); const firstSkill = data.skills?.[0];
setSession(sessionData); if (firstSkill) {
if (!data.auth?.invokeRequiresSession || sessionData?.authenticated) { setSelectedSkillName(firstSkill.name);
refreshHistory(data).catch(() => null); setArgsText(JSON.stringify(sampleArgs(firstSkill), null, 2));
} }
return loadSession(data).catch(() => null);
}) })
.then((sessionData) => setSession(sessionData))
.catch((err) => setError(err.message || String(err))); .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),
[config, selectedSkillName],
);
async function refreshHistory(activeConfig = config) { const needsSignIn = Boolean(
if (!activeConfig) return; config?.auth?.invokeRequiresSession && session && !session.authenticated,
const data = await callSkill(activeConfig, "list_comparisons", { limit: 10 }); );
if (data?.ok) setHistory(data.comparisons || []); 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 parseQuotes() { async function runSkill(event) {
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) return; if (!config || !selectedSkill) return;
setRunning(true); setRunning(true);
setError(null); setError(null);
setNotice(null); setResult(null);
try { try {
const data = await callSkill(config, "compare_quotes", { const args = JSON.parse(argsText || "{}");
comparison_id: comparisonId.trim(), const data = await callSkill(config, selectedSkill.name, args);
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 {
@@ -76,225 +68,91 @@ 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 <main className="loading"><p>{error || "Loading QuoteJudge Studio..."}</p></main>; return (
<main className="loading">
<p>{error || "Loading A2A agent contract..."}</p>
</main>
);
} }
return ( return (
<main className="app-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>Pick the best vendor quote with transparent weighted scoring.</h1> <h1>quote-judge-studio-v1</h1>
<p className="lede"> <p className="agent-meta">
Upload or paste at least two quotes, tune price/delivery/warranty weights, save the recommendation, {config.agent.name} v{config.agent.version}
and reopen past runs from your platform-authenticated workspace.
</p> </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?.email || "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>
<section className="grid"> {selectedSkill ? (
<form className="card workflow" onSubmit={compare}> <form className="runner" onSubmit={runSkill}>
<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>
Comparison ID Arguments JSON
<input value={comparisonId} onChange={(event) => setComparisonId(event.target.value)} maxLength={120} />
</label>
<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>
))}
</fieldset>
<label>
Paste quote JSON
<textarea <textarea
spellCheck="false" spellCheck="false"
value={quotesText} value={argsText}
onChange={(event) => setQuotesText(event.target.value)} onChange={(event) => setArgsText(event.target.value)}
aria-describedby="quote-help"
/> />
</label> </label>
<p id="quote-help" className="help"> <button disabled={running} type="submit">
Required fields: vendor, unit_price, quantity, delivery_days, warranty_months. The fixture recommends Beta Industrial. {running ? "Running..." : `Run ${selectedSkill.name}`}
</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>
{needsSignIn ? <p className="notice">Sign in with your A2A Cloud session to run tools and persist results.</p> : null}
{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>
<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> </button>
</li> </form>
))}
</ul>
) : ( ) : (
<p className="empty">No saved comparisons loaded yet. Run the fixture or refresh after signing in.</p> <p className="empty">Add a `@a2a.tool` to your agent to make it callable here.</p>
)} )}
</section>
</section>
<ResultPanel result={result} /> <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>
</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));
}