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

This commit is contained in:
a2a-cloud
2026-07-19 19:57:50 +00:00
parent 0fbd5145f3
commit fa9d139b4e

View File

@@ -1,66 +1,59 @@
import { useEffect, useMemo, useState } from "react";
import {
callSkill,
loadAgentConfig,
loadSession,
sampleArgs,
signInUrl,
} from "./a2a.js";
import { callSkill, loadAgentConfig, loadSession, signInUrl } from "./a2a.js";
const fixtureUpdates = [
{ account: "Acme Manufacturing", owner: "Priya", stage: "Security review", amount_usd: 84000, forecast_category: "commit", status: "blocked", days_in_stage: 18, update: "Waiting on vendor risk questionnaire." },
{ account: "Northstar Health", owner: "Mateo", stage: "Proposal", amount_usd: 52000, forecast_category: "best_case", status: "at_risk", days_in_stage: 11, update: "Economic buyer asked for ROI proof." },
{ account: "Bluebird Logistics", owner: "Priya", stage: "Discovery", amount_usd: 27000, forecast_category: "pipeline", status: "on_track", days_in_stage: 4, update: "Expansion pain confirmed." },
{ account: "Summit Retail", owner: "Nora", stage: "Procurement", amount_usd: 125000, forecast_category: "commit", status: "slipped", days_in_stage: 31, update: "Legal redlines moved close date." },
];
const defaultRequest = {
dashboard_name: "Weekly Sales Ops Pulse",
segment: "Mid-market",
period_label: "This week",
min_exception_amount_usd: 25000,
updates: fixtureUpdates,
notes: "Paste weekly deal updates here later; the demo fixture is prefilled so the first useful dashboard is one click away.",
};
export function App() {
const [config, setConfig] = useState(null);
const [session, setSession] = useState(null);
const [selectedSkillName, setSelectedSkillName] = useState("");
const [argsText, setArgsText] = useState("{}");
const [requestText, setRequestText] = useState(JSON.stringify(defaultRequest, null, 2));
const [result, setResult] = useState(null);
const [history, setHistory] = useState([]);
const [error, setError] = useState(null);
const [running, setRunning] = useState(false);
useEffect(() => {
loadAgentConfig()
.then((data) => {
.then(async (data) => {
setConfig(data);
const firstSkill = data.skills?.[0];
if (firstSkill) {
setSelectedSkillName(firstSkill.name);
setArgsText(JSON.stringify(sampleArgs(firstSkill), null, 2));
const sessionData = await loadSession(data).catch(() => null);
setSession(sessionData);
if (!data.auth?.invokeRequiresSession || sessionData?.authenticated) {
callSkill(data, "list_dashboard_history", { limit: 5 })
.then((payload) => setHistory(payload.history || []))
.catch(() => setHistory([]));
}
return loadSession(data).catch(() => null);
})
.then((sessionData) => setSession(sessionData))
.catch((err) => setError(err.message || String(err)));
}, []);
const selectedSkill = useMemo(
() => config?.skills?.find((skill) => skill.name === selectedSkillName),
[config, selectedSkillName],
);
const needsSignIn = Boolean(config?.auth?.invokeRequiresSession && session && !session.authenticated);
const signInHref = useMemo(() => (config && needsSignIn ? signInUrl(config) : null), [config, needsSignIn]);
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);
}
async function runSkill(event) {
async function buildDashboard(event) {
event.preventDefault();
if (!config || !selectedSkill) return;
if (!config) return;
setRunning(true);
setError(null);
setResult(null);
try {
const args = JSON.parse(argsText || "{}");
const data = await callSkill(config, selectedSkill.name, args);
setResult(data);
const parsed = JSON.parse(requestText);
const payload = await callSkill(config, "build_dashboard", { request: parsed });
setResult(payload);
setHistory(payload.history || history);
} catch (err) {
setError(err.message || String(err));
} finally {
@@ -68,91 +61,140 @@ export function App() {
}
}
if (!config) {
return (
<main className="loading">
<p>{error || "Loading A2A agent contract..."}</p>
</main>
);
function downloadCsv() {
const artifact = result?.artifact;
if (!artifact?.content) return;
const blob = new Blob([artifact.content], { type: artifact.media_type || "text/csv" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = artifact.name || "sales-ops-dashboard.csv";
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(url);
}
if (!config) {
return <main className="loading" data-testid="agent-app"><p>{error || "Loading dashboard app..."}</p></main>;
}
const rows = result?.["dashboard-data"] || [];
const trends = result?.trends || [];
const exceptions = result?.exceptions || [];
const filters = result?.filters || {};
return (
<main className="app-shell">
<aside className="sidebar">
<main className="dashboard-app" data-testid="agent-app">
<section className="hero">
<div>
<p className="eyebrow">A2A packed app</p>
<h1>production-proof-v116-high-utili-7255-3</h1>
<p className="agent-meta">
{config.agent.name} v{config.agent.version}
</p>
<p className="eyebrow">Production proof v116</p>
<h1>Sales Ops Pulse Dashboard</h1>
<p className="lede">Turn recurring B2B sales updates into filters, trends, exceptions, durable receipts, and a CSV download in under two minutes.</p>
</div>
<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 className="account-card">
<span>{session?.authenticated ? "Signed in" : needsSignIn ? "Sign-in required to run" : "Ready"}</span>
<strong>{session?.user?.email || session?.org?.slug || config.agent?.name}</strong>
{needsSignIn && signInHref ? <a className="signin" href={signInHref}>Sign in to run dashboard</a> : null}
</div>
</aside>
</section>
<section className="workbench">
<header className="toolbar">
<div>
<p className="eyebrow">Skill runner</p>
<h2>{selectedSkill?.name || "No skills found"}</h2>
<section className="grid">
<form className="builder-card" onSubmit={buildDashboard}>
<div className="card-heading">
<p className="eyebrow">One-click fixture</p>
<h2>Build dashboard</h2>
</div>
<a href={config.docs.base} rel="noreferrer" target="_blank">
Docs
</a>
</header>
<label>
Dashboard request JSON
<textarea data-testid="agent-input" value={requestText} onChange={(event) => setRequestText(event.target.value)} spellCheck="false" />
</label>
<button data-testid="agent-submit" disabled={running || needsSignIn} type="submit">
{running ? "Building..." : "Build dashboard"}
</button>
{error ? <p className="error" role="alert">{error}</p> : null}
{needsSignIn ? <p className="hint">The page is public, but platform auth is required for account trial calls and durable history.</p> : null}
</form>
{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="result-card" data-testid="agent-result" aria-live="polite">
{!result ? (
<div className="empty-state">
<p className="eyebrow">Awaiting run</p>
<h2>Dashboard preview will appear here</h2>
<p>The browser journey can run immediately because the fixture is already loaded.</p>
</div>
) : (
<>
<div className="result-header">
<div>
<p className="eyebrow">{result.status}</p>
<h2>{result.summary}</h2>
<p className="receipt">Receipt: {result.receipt_id}</p>
</div>
<button className="download" data-testid="agent-download" type="button" onClick={downloadCsv}>Download CSV</button>
</div>
<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>
<div className="trend-row">
{trends.map((item) => (
<div className="metric" key={item.metric}>
<span>{item.label}</span>
<strong>{typeof item.value === "number" && item.metric.includes("pipeline") ? `$${item.value.toLocaleString()}` : item.value}</strong>
</div>
))}
</div>
<div className="filters">
<strong>Filters</strong>
<span>Segment: {filters.segment}</span>
<span>Owners: {(filters.owners || []).join(", ")}</span>
<span>Stages: {(filters.stages || []).join(", ")}</span>
</div>
<h3>Prioritized exceptions</h3>
<div className="exceptions">
{exceptions.length ? exceptions.map((item) => (
<article key={`${item.account}-${item.reason}`}>
<strong>{item.account}</strong>
<span>{item.reason}</span>
<p>{item.recommended_action}</p>
</article>
)) : <p>No exceptions over the threshold.</p>}
</div>
<h3>Dashboard data</h3>
<div className="table-wrap">
<table>
<thead><tr><th>Account</th><th>Owner</th><th>Stage</th><th>Amount</th><th>Status</th><th>Risk</th></tr></thead>
<tbody>
{rows.map((row) => (
<tr key={`${row.account}-${row.owner}`}>
<td>{row.account}</td><td>{row.owner}</td><td>{row.stage}</td><td>${Number(row.amount_usd).toLocaleString()}</td><td>{row.status}</td><td>{row.risk_score}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
)}
</section>
</section>
<section className="history-card">
<div>
<p className="eyebrow">Durable history</p>
<h2>Recent dashboards</h2>
</div>
{history.length ? (
<div className="history-list">
{history.map((item) => (
<article key={item.dashboard_id}>
<strong>{item.dashboard_name}</strong>
<span>{item.segment} · {item.period_label} · ${Number(item.pipeline_total_usd).toLocaleString()} · {item.exception_count} exceptions</span>
</article>
))}
</div>
) : <p className="hint">Run once to persist the first dashboard and production execution receipt.</p>}
</section>
</main>
);
}