a2a-source-edit: write frontend/src/App.jsx
This commit is contained in:
@@ -1,277 +1,158 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
callSkill,
|
||||
fileToBrowserDocument,
|
||||
loadAgentConfig,
|
||||
loadSession,
|
||||
maybeAuthorize,
|
||||
sampleArgs,
|
||||
signInUrl,
|
||||
} 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() {
|
||||
const [config, setConfig] = useState(null);
|
||||
const [session, setSession] = useState(null);
|
||||
const [loadError, setLoadError] = useState(null);
|
||||
const [comparisonId, setComparisonId] = useState("studio-quote-v1");
|
||||
const [quotes, setQuotes] = useState(SUCCESS_FIXTURE);
|
||||
const [weights, setWeights] = useState(DEFAULT_WEIGHTS);
|
||||
const [files, setFiles] = useState([]);
|
||||
const [selectedSkillName, setSelectedSkillName] = useState("");
|
||||
const [argsText, setArgsText] = useState("{}");
|
||||
const [result, setResult] = useState(null);
|
||||
const [historyResult, setHistoryResult] = useState(null);
|
||||
const [error, setError] = useState(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadAgentConfig()
|
||||
.then(async (data) => {
|
||||
.then((data) => {
|
||||
setConfig(data);
|
||||
try {
|
||||
setSession(await loadSession(data));
|
||||
} catch {
|
||||
setSession({ authenticated: false });
|
||||
const firstSkill = data.skills?.[0];
|
||||
if (firstSkill) {
|
||||
setSelectedSkillName(firstSkill.name);
|
||||
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 signInHref = useMemo(() => (config ? signInUrl(config) : null), [config]);
|
||||
const totalWeight = Number(weights.price || 0) + Number(weights.delivery || 0) + Number(weights.warranty || 0);
|
||||
const selectedSkill = useMemo(
|
||||
() => config?.skills?.find((skill) => skill.name === selectedSkillName),
|
||||
[config, selectedSkillName],
|
||||
);
|
||||
|
||||
function updateQuote(index, field, value) {
|
||||
setQuotes((current) => current.map((quote, i) => (i === index ? { ...quote, [field]: value } : quote)));
|
||||
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 addQuote() {
|
||||
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) {
|
||||
async function runSkill(event) {
|
||||
event.preventDefault();
|
||||
if (!config) return;
|
||||
if (needsSignIn) return maybeAuthorize(config);
|
||||
if (!config || !selectedSkill) return;
|
||||
setRunning(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
try {
|
||||
let data;
|
||||
if (files.length) {
|
||||
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.");
|
||||
const args = JSON.parse(argsText || "{}");
|
||||
const data = await callSkill(config, selectedSkill.name, args);
|
||||
setResult(data);
|
||||
} catch (err) {
|
||||
if (err.status === 401) return maybeAuthorize(config);
|
||||
setError(err.message || String(err));
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadComparison() {
|
||||
if (!config) return;
|
||||
if (needsSignIn) return maybeAuthorize(config);
|
||||
setRunning(true);
|
||||
setError(null);
|
||||
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);
|
||||
}
|
||||
if (!config) {
|
||||
return (
|
||||
<main className="loading">
|
||||
<p>{error || "Loading A2A agent contract..."}</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<main className="app-shell">
|
||||
<header className="hero">
|
||||
<nav className="topbar" aria-label="QuoteJudge status">
|
||||
<div>
|
||||
<span className="logo">QJ</span>
|
||||
<strong>QuoteJudge Studio</strong>
|
||||
</div>
|
||||
<div className="session-pill">
|
||||
{session?.authenticated ? "Signed in" : "Signed out"}
|
||||
{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>
|
||||
<aside className="sidebar">
|
||||
<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>
|
||||
</div>
|
||||
|
||||
<form className="studio" onSubmit={runCompare}>
|
||||
<section className="panel inputs-panel">
|
||||
<div className="section-title">
|
||||
<div>
|
||||
<p className="eyebrow">1. Quote data</p>
|
||||
<h2>Paste quotes or upload a file</h2>
|
||||
</div>
|
||||
<label className="id-label">
|
||||
Comparison ID
|
||||
<input value={comparisonId} onChange={(event) => setComparisonId(event.target.value)} />
|
||||
</label>
|
||||
</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>
|
||||
<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>
|
||||
))}
|
||||
<p className={totalWeight > 0 ? "hint" : "hint danger"}>Total weight: {totalWeight}. At least one priority must be non-zero.</p>
|
||||
{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>
|
||||
</nav>
|
||||
|
||||
{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">
|
||||
<ResultPanel result={result} />
|
||||
<section className="panel">
|
||||
<p className="eyebrow">Durable reload</p>
|
||||
<h2>Saved comparison</h2>
|
||||
<button type="button" className="secondary" onClick={reloadComparison} disabled={running}>Get {comparisonId}</button>
|
||||
<pre>{JSON.stringify(historyResult || { message: "Run compare, then reopen the same ID in a later invocation." }, null, 2)}</pre>
|
||||
<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>
|
||||
|
||||
{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>
|
||||
</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),
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user