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

This commit is contained in:
a2a-cloud
2026-07-18 06:46:07 +00:00
parent fd39e359b7
commit 4822e496ac

View File

@@ -1,277 +1,158 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { import {
callSkill, callSkill,
fileToBrowserDocument,
loadAgentConfig, loadAgentConfig,
loadSession, loadSession,
maybeAuthorize, sampleArgs,
signInUrl, signInUrl,
} from "./a2a.js"; } from "./a2a.js";
const MAX_FILE_BYTES = 64 * 1024;
const MAX_FILES = 4;
const ACCEPT = ".json,.csv,.txt,application/json,text/csv,text/plain";
const SUCCESS_FIXTURE = [
{ vendor: "Acme Bearings", quantity: 500, unit_price: 10.75, delivery_days: 12, warranty_months: 12 },
{ vendor: "Beta Industrial", quantity: 500, unit_price: 9.1, delivery_days: 8, warranty_months: 18 },
];
const EMPTY_QUOTE = { vendor: "", quantity: 1, unit_price: 0, delivery_days: 0, warranty_months: 0 };
const DEFAULT_WEIGHTS = { price: 50, delivery: 30, warranty: 20 };
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 [loadError, setLoadError] = useState(null); const [selectedSkillName, setSelectedSkillName] = useState("");
const [comparisonId, setComparisonId] = useState("studio-quote-v1"); const [argsText, setArgsText] = useState("{}");
const [quotes, setQuotes] = useState(SUCCESS_FIXTURE);
const [weights, setWeights] = useState(DEFAULT_WEIGHTS);
const [files, setFiles] = useState([]);
const [result, setResult] = useState(null); const [result, setResult] = useState(null);
const [historyResult, setHistoryResult] = useState(null);
const [error, setError] = useState(null); const [error, setError] = 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);
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));
} }
return loadSession(data).catch(() => null);
}) })
.catch((err) => setLoadError(err.message || String(err))); .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 ? signInUrl(config) : null), [config]); () => 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) {
if (quotes.length < 10) setQuotes((current) => [...current, { ...EMPTY_QUOTE }]);
}
function removeQuote(index) {
setQuotes((current) => current.filter((_, i) => i !== index));
}
function normalizeQuotes() {
return quotes.map((quote) => ({
vendor: String(quote.vendor || "").trim(),
quantity: Number(quote.quantity),
unit_price: Number(quote.unit_price),
delivery_days: Number(quote.delivery_days),
warranty_months: Number(quote.warranty_months),
}));
}
async function runCompare(event) {
event.preventDefault(); event.preventDefault();
if (!config) return; if (!config || !selectedSkill) return;
if (needsSignIn) return maybeAuthorize(config);
setRunning(true); setRunning(true);
setError(null); setError(null);
setResult(null); setResult(null);
try { try {
let data; const args = JSON.parse(argsText || "{}");
if (files.length) { const data = await callSkill(config, selectedSkill.name, args);
const docs = await Promise.all(files.map(fileToBrowserDocument));
data = await callSkill(config, "compare_quotes_from_browser_upload", {
comparison_id: comparisonId,
documents: docs,
weights: coerceWeights(weights),
});
} else {
data = await callSkill(config, "compare_quotes", {
comparison_id: comparisonId,
quotes: normalizeQuotes(),
weights: coerceWeights(weights),
});
}
if (!data.ok) setError(data.code || "Quote comparison failed validation.");
setResult(data); setResult(data);
} catch (err) { } catch (err) {
if (err.status === 401) return maybeAuthorize(config);
setError(err.message || String(err)); setError(err.message || String(err));
} finally { } finally {
setRunning(false); setRunning(false);
} }
} }
async function reloadComparison() { if (!config) {
if (!config) return; return (
if (needsSignIn) return maybeAuthorize(config); <main className="loading">
setRunning(true); <p>{error || "Loading A2A agent contract..."}</p>
setError(null); </main>
try { );
const data = await callSkill(config, "get_comparison", { comparison_id: comparisonId });
if (!data.ok) setError(data.code || "Comparison not found.");
setHistoryResult(data);
if (data.ok) setResult(data);
} catch (err) {
if (err.status === 401) return maybeAuthorize(config);
setError(err.message || String(err));
} finally {
setRunning(false);
}
} }
function useFixture(kind) {
setFiles([]);
setComparisonId(kind === "failure" ? "studio-quote-invalid" : "studio-quote-v1");
setQuotes(kind === "failure" ? [
{ vendor: "Only Vendor", quantity: 1, unit_price: 10, delivery_days: 5, warranty_months: 6 },
] : SUCCESS_FIXTURE);
setWeights(DEFAULT_WEIGHTS);
setResult(null);
setHistoryResult(null);
setError(null);
}
function onFilesSelected(event) {
const picked = Array.from(event.target.files || []);
const tooLarge = picked.find((file) => file.size > MAX_FILE_BYTES);
if (picked.length > MAX_FILES) return setError(`Upload at most ${MAX_FILES} files.`);
if (tooLarge) return setError(`${tooLarge.name} exceeds 64 KiB.`);
setFiles(picked);
setError(null);
}
if (loadError) return <main className="loading"><p>{loadError}</p></main>;
if (!config) return <main className="loading"><p>Loading QuoteJudge...</p></main>;
return ( return (
<main className="app-shell"> <main className="app-shell">
<header className="hero"> <aside className="sidebar">
<nav className="topbar" aria-label="QuoteJudge status"> <div>
<div> <p className="eyebrow">A2A packed app</p>
<span className="logo">QJ</span> <h1>quote-judge-studio-v1</h1>
<strong>QuoteJudge Studio</strong> <p className="agent-meta">
</div> {config.agent.name} v{config.agent.version}
<div className="session-pill"> </p>
{session?.authenticated ? "Signed in" : "Signed out"} </div>
{needsSignIn && signInHref ? <a href={signInHref}>Sign in to run</a> : null}
</div>
</nav>
<section className="hero-grid">
<div>
<p className="eyebrow">Weighted vendor quote decisions</p>
<h1>Pick the best quote, save the evidence, reopen it later.</h1>
<p className="lede">
Upload or paste supplier quotes, tune price/delivery/warranty weights, and persist a per-user production receipt without sending secrets to the browser.
</p>
<div className="actions">
<button type="button" onClick={() => useFixture("success")}>Load success fixture</button>
<button type="button" className="secondary" onClick={() => useFixture("failure")}>Load failure fixture</button>
<button type="button" className="secondary" onClick={reloadComparison} disabled={running}>Reopen saved</button>
</div>
</div>
<div className="score-card" aria-live="polite">
<span>Current recommendation</span>
<strong>{result?.recommendation?.vendor || "Run a comparison"}</strong>
<p>{result?.recommendation?.rationale || "Beta wins the bundled fixture because it is cheaper, faster, and has a longer warranty."}</p>
</div>
</section>
</header>
<form className="studio" onSubmit={runCompare}> <nav className="skill-list" aria-label="Agent skills">
<section className="panel inputs-panel"> {(config.skills || []).map((skill) => (
<div className="section-title"> <button
<div> className={skill.name === selectedSkillName ? "skill active" : "skill"}
<p className="eyebrow">1. Quote data</p> key={skill.name}
<h2>Paste quotes or upload a file</h2> onClick={() => selectSkill(skill)}
</div> type="button"
<label className="id-label"> >
Comparison ID <span>{skill.name}</span>
<input value={comparisonId} onChange={(event) => setComparisonId(event.target.value)} /> <small>{skill.stream ? "streaming" : "request"}</small>
</label> </button>
</div>
<div className="upload-box">
<label>
Browser upload bridge (JSON/CSV/text, 64 KiB each)
<input type="file" accept={ACCEPT} multiple onChange={onFilesSelected} />
</label>
<small>{files.length ? files.map((file) => file.name).join(", ") : "No file selected; form rows below will be used."}</small>
</div>
<div className="quotes-table" role="group" aria-label="Vendor quotes">
{quotes.map((quote, index) => (
<div className="quote-row" key={index}>
<label>Vendor<input value={quote.vendor} onChange={(e) => updateQuote(index, "vendor", e.target.value)} /></label>
<label>Qty<input type="number" min="1" value={quote.quantity} onChange={(e) => updateQuote(index, "quantity", e.target.value)} /></label>
<label>Unit price<input type="number" min="0" step="0.01" value={quote.unit_price} onChange={(e) => updateQuote(index, "unit_price", e.target.value)} /></label>
<label>Days<input type="number" min="0" value={quote.delivery_days} onChange={(e) => updateQuote(index, "delivery_days", e.target.value)} /></label>
<label>Warranty<input type="number" min="0" value={quote.warranty_months} onChange={(e) => updateQuote(index, "warranty_months", e.target.value)} /></label>
<button type="button" className="icon" onClick={() => removeQuote(index)} aria-label={`Remove quote ${index + 1}`}>×</button>
</div>
))}
</div>
<button type="button" className="secondary" onClick={addQuote} disabled={quotes.length >= 10}>Add quote</button>
</section>
<section className="panel weights-panel">
<p className="eyebrow">2. Decision weights</p>
<h2>Score priorities</h2>
{Object.keys(DEFAULT_WEIGHTS).map((key) => (
<label className="slider" key={key}>
<span>{key} <strong>{weights[key]}</strong></span>
<input type="range" min="0" max="100" value={weights[key]} onChange={(e) => setWeights((w) => ({ ...w, [key]: Number(e.target.value) }))} />
</label>
))} ))}
<p className={totalWeight > 0 ? "hint" : "hint danger"}>Total weight: {totalWeight}. At least one priority must be non-zero.</p> </nav>
{needsSignIn ? <a className="primary-link" href={signInHref || "#"}>Sign in to run comparisons</a> : (
<button className="primary" type="submit" disabled={running || totalWeight <= 0}>{running ? "Comparing..." : "Compare and save"}</button>
)}
</section>
</form>
{error ? <section className="alert" role="alert">{error}</section> : null} <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="results-grid"> <section className="workbench">
<ResultPanel result={result} /> <header className="toolbar">
<section className="panel"> <div>
<p className="eyebrow">Durable reload</p> <p className="eyebrow">Skill runner</p>
<h2>Saved comparison</h2> <h2>{selectedSkill?.name || "No skills found"}</h2>
<button type="button" className="secondary" onClick={reloadComparison} disabled={running}>Get {comparisonId}</button> </div>
<pre>{JSON.stringify(historyResult || { message: "Run compare, then reopen the same ID in a later invocation." }, null, 2)}</pre> <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>
<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>
</section> </section>
</main> </main>
); );
} }
function ResultPanel({ result }) {
return (
<section className="panel">
<p className="eyebrow">3. Result and receipt</p>
<h2>{result?.ok ? "Comparison saved" : "No saved result yet"}</h2>
{result?.rankings?.length ? (
<ol className="rankings">
{result.rankings.map((row) => (
<li key={row.vendor}>
<strong>#{row.rank} {row.vendor}</strong>
<span>Score {row.score} · BRL {row.total_price} · {row.delivery_days} days · {row.warranty_months} mo warranty</span>
</li>
))}
</ol>
) : null}
<pre>{JSON.stringify(result || { message: "Results from the live backend appear here." }, null, 2)}</pre>
</section>
);
}
function coerceWeights(weights) {
return {
price: Number(weights.price),
delivery: Number(weights.delivery),
warranty: Number(weights.warranty),
};
}