a2a-source-edit: write frontend/src/App.jsx
This commit is contained in:
@@ -1,74 +1,66 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { callSkill, loadAgentConfig, loadSession, signInUrl } from "./a2a.js";
|
||||
|
||||
const sampleQuotes = [
|
||||
{ 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 defaultWeights = { price: 50, delivery: 30, warranty: 20 };
|
||||
const maxUploadBytes = 64 * 1024;
|
||||
const acceptedTypes = ["application/json", "text/csv", "text/plain"];
|
||||
import {
|
||||
callSkill,
|
||||
loadAgentConfig,
|
||||
loadSession,
|
||||
sampleArgs,
|
||||
signInUrl,
|
||||
} from "./a2a.js";
|
||||
|
||||
export function App() {
|
||||
const [config, setConfig] = useState(null);
|
||||
const [session, setSession] = useState(null);
|
||||
const [comparisonId, setComparisonId] = useState("studio-quote-v1");
|
||||
const [quotesText, setQuotesText] = useState(JSON.stringify(sampleQuotes, null, 2));
|
||||
const [weights, setWeights] = useState(defaultWeights);
|
||||
const [selectedSkillName, setSelectedSkillName] = useState("");
|
||||
const [argsText, setArgsText] = useState("{}");
|
||||
const [result, setResult] = useState(null);
|
||||
const [history, setHistory] = useState([]);
|
||||
const [error, setError] = useState(null);
|
||||
const [notice, setNotice] = useState(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadAgentConfig()
|
||||
.then(async (data) => {
|
||||
.then((data) => {
|
||||
setConfig(data);
|
||||
const sessionData = await loadSession(data).catch(() => ({ authenticated: false }));
|
||||
setSession(sessionData);
|
||||
if (!data.auth?.invokeRequiresSession || sessionData?.authenticated) {
|
||||
refreshHistory(data).catch(() => null);
|
||||
const firstSkill = data.skills?.[0];
|
||||
if (firstSkill) {
|
||||
setSelectedSkillName(firstSkill.name);
|
||||
setArgsText(JSON.stringify(sampleArgs(firstSkill), null, 2));
|
||||
}
|
||||
return loadSession(data).catch(() => null);
|
||||
})
|
||||
.then((sessionData) => setSession(sessionData))
|
||||
.catch((err) => setError(err.message || String(err)));
|
||||
}, []);
|
||||
|
||||
const needsSignIn = Boolean(config?.auth?.invokeRequiresSession && session && !session.authenticated);
|
||||
const signInHref = useMemo(() => (config && needsSignIn ? signInUrl(config) : null), [config, needsSignIn]);
|
||||
const selectedSkill = useMemo(
|
||||
() => config?.skills?.find((skill) => skill.name === selectedSkillName),
|
||||
[config, selectedSkillName],
|
||||
);
|
||||
|
||||
async function refreshHistory(activeConfig = config) {
|
||||
if (!activeConfig) return;
|
||||
const data = await callSkill(activeConfig, "list_comparisons", { limit: 10 });
|
||||
if (data?.ok) setHistory(data.comparisons || []);
|
||||
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 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) {
|
||||
async function runSkill(event) {
|
||||
event.preventDefault();
|
||||
if (!config) return;
|
||||
if (!config || !selectedSkill) return;
|
||||
setRunning(true);
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
setResult(null);
|
||||
try {
|
||||
const data = await callSkill(config, "compare_quotes", {
|
||||
comparison_id: comparisonId.trim(),
|
||||
quotes: parseQuotes(),
|
||||
weights,
|
||||
});
|
||||
const args = JSON.parse(argsText || "{}");
|
||||
const data = await callSkill(config, selectedSkill.name, args);
|
||||
setResult(data);
|
||||
if (!data.ok) setNotice(data.message || "Validation failed. Check the highlighted response.");
|
||||
if (data.ok) await refreshHistory();
|
||||
} catch (err) {
|
||||
setError(err.message || String(err));
|
||||
} 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) {
|
||||
return <main className="loading"><p>{error || "Loading QuoteJudge Studio..."}</p></main>;
|
||||
return (
|
||||
<main className="loading">
|
||||
<p>{error || "Loading A2A agent contract..."}</p>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="app-shell">
|
||||
<header className="hero">
|
||||
<aside className="sidebar">
|
||||
<div>
|
||||
<p className="eyebrow">QuoteJudge Studio</p>
|
||||
<h1>Pick the best vendor quote with transparent weighted scoring.</h1>
|
||||
<p className="lede">
|
||||
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 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>
|
||||
<div className="session-card">
|
||||
<span>{session?.authenticated ? "Signed in" : "Signed out"}</span>
|
||||
<strong>{session?.user?.email || session?.email || "Platform session required"}</strong>
|
||||
{needsSignIn && signInHref ? <a className="button secondary" href={signInHref}>Sign in to run</a> : null}
|
||||
|
||||
<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>
|
||||
</div>
|
||||
<a href={config.docs.base} rel="noreferrer" target="_blank">
|
||||
Docs
|
||||
</a>
|
||||
</header>
|
||||
|
||||
<section className="grid">
|
||||
<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>
|
||||
|
||||
{selectedSkill ? (
|
||||
<form className="runner" onSubmit={runSkill}>
|
||||
<label>
|
||||
Comparison ID
|
||||
<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
|
||||
Arguments JSON
|
||||
<textarea
|
||||
spellCheck="false"
|
||||
value={quotesText}
|
||||
onChange={(event) => setQuotesText(event.target.value)}
|
||||
aria-describedby="quote-help"
|
||||
value={argsText}
|
||||
onChange={(event) => setArgsText(event.target.value)}
|
||||
/>
|
||||
</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>
|
||||
|
||||
{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 disabled={running} type="submit">
|
||||
{running ? "Running..." : `Run ${selectedSkill.name}`}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</form>
|
||||
) : (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user