a2a-source-edit: write frontend/src/App.jsx
This commit is contained in:
@@ -1,66 +1,79 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
MAX_CSV_BYTES,
|
||||
callSkill,
|
||||
fileToBrowserUpload,
|
||||
loadAgentConfig,
|
||||
loadSession,
|
||||
sampleArgs,
|
||||
signInUrl,
|
||||
unwrapA2AResult,
|
||||
} from "./a2a.js";
|
||||
|
||||
const SAMPLE_CSV = "month,revenue\nJanuary,100\nFebruary,120\nMarch,150\n";
|
||||
|
||||
export function App() {
|
||||
const [config, setConfig] = useState(null);
|
||||
const [session, setSession] = useState(null);
|
||||
const [selectedSkillName, setSelectedSkillName] = useState("");
|
||||
const [argsText, setArgsText] = useState("{}");
|
||||
const [analysisId, setAnalysisId] = useState("studio-csv-v1");
|
||||
const [question, setQuestion] = useState("Which month has the highest revenue?");
|
||||
const [csvText, setCsvText] = useState(SAMPLE_CSV);
|
||||
const [file, setFile] = useState(null);
|
||||
const [result, setResult] = useState(null);
|
||||
const [history, setHistory] = useState([]);
|
||||
const [status, setStatus] = useState("Loading CSVAnswers...");
|
||||
const [error, setError] = useState(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadAgentConfig()
|
||||
.then((data) => {
|
||||
setConfig(data);
|
||||
const firstSkill = data.skills?.[0];
|
||||
if (firstSkill) {
|
||||
setSelectedSkillName(firstSkill.name);
|
||||
setArgsText(JSON.stringify(sampleArgs(firstSkill), null, 2));
|
||||
.then(async (loaded) => {
|
||||
setConfig(loaded);
|
||||
try {
|
||||
const sessionData = await loadSession(loaded);
|
||||
setSession(sessionData);
|
||||
if (sessionData?.authenticated) await refreshHistory(loaded);
|
||||
} catch {
|
||||
setSession({ authenticated: false });
|
||||
}
|
||||
return loadSession(data).catch(() => null);
|
||||
setStatus(null);
|
||||
})
|
||||
.then((sessionData) => setSession(sessionData))
|
||||
.catch((err) => setError(err.message || String(err)));
|
||||
.catch((err) => {
|
||||
setError(err.message || String(err));
|
||||
setStatus(null);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const selectedSkill = useMemo(
|
||||
() => config?.skills?.find((skill) => skill.name === selectedSkillName),
|
||||
[config, selectedSkillName],
|
||||
);
|
||||
const needsSignIn = Boolean(config?.auth?.invokeRequiresSession && !session?.authenticated);
|
||||
const signInHref = useMemo(() => (config ? signInUrl(config) : null), [config]);
|
||||
const maxKb = Math.round(MAX_CSV_BYTES / 1024);
|
||||
|
||||
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 refreshHistory(activeConfig = config) {
|
||||
if (!activeConfig) return;
|
||||
try {
|
||||
const response = await callSkill(activeConfig, "list_analyses", { limit: 10 });
|
||||
const data = unwrapA2AResult(response);
|
||||
if (data?.ok) setHistory(data.analyses || []);
|
||||
} catch (err) {
|
||||
if (!String(err.message || err).includes("session")) console.warn(err);
|
||||
}
|
||||
}
|
||||
|
||||
async function runSkill(event) {
|
||||
async function runAnalysis(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);
|
||||
const args = { analysis_id: analysisId.trim(), question: question.trim() };
|
||||
const skill = file ? "analyze_csv_upload_base64" : "analyze_csv";
|
||||
if (file) args.upload = await fileToBrowserUpload(file);
|
||||
else args.csv_text = csvText;
|
||||
const response = await callSkill(config, skill, args);
|
||||
const data = unwrapA2AResult(response);
|
||||
setResult(data);
|
||||
if (!data?.ok) setError(data?.message || data?.code || "CSV analysis failed.");
|
||||
else await refreshHistory(config);
|
||||
} catch (err) {
|
||||
setError(err.message || String(err));
|
||||
} finally {
|
||||
@@ -68,91 +81,133 @@ export function App() {
|
||||
}
|
||||
}
|
||||
|
||||
if (!config) {
|
||||
return (
|
||||
<main className="loading">
|
||||
<p>{error || "Loading A2A agent contract..."}</p>
|
||||
</main>
|
||||
);
|
||||
async function reopen(id = analysisId) {
|
||||
if (!config || !id) return;
|
||||
setRunning(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await callSkill(config, "get_analysis", { analysis_id: id.trim() });
|
||||
const data = unwrapA2AResult(response);
|
||||
setResult(data);
|
||||
if (data?.ok) setAnalysisId(data.analysis_id);
|
||||
else setError(data?.message || data?.code || "Analysis was not found.");
|
||||
} catch (err) {
|
||||
setError(err.message || String(err));
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
}
|
||||
|
||||
function onFileChange(event) {
|
||||
const selected = event.target.files?.[0] || null;
|
||||
setError(null);
|
||||
if (selected && selected.size > MAX_CSV_BYTES) {
|
||||
setError(`CSV upload must be at most ${maxKb} KB.`);
|
||||
event.target.value = "";
|
||||
setFile(null);
|
||||
return;
|
||||
}
|
||||
setFile(selected);
|
||||
}
|
||||
|
||||
if (status) return <main className="loading"><p>{status}</p></main>;
|
||||
|
||||
return (
|
||||
<main className="app-shell">
|
||||
<aside className="sidebar">
|
||||
<main className="shell">
|
||||
<section className="hero" aria-labelledby="title">
|
||||
<div>
|
||||
<p className="eyebrow">A2A packed app</p>
|
||||
<h1>csv-answers-studio-v1</h1>
|
||||
<p className="agent-meta">
|
||||
{config.agent.name} v{config.agent.version}
|
||||
<p className="eyebrow">A2A full-stack startup</p>
|
||||
<h1 id="title">CSVAnswers Studio</h1>
|
||||
<p className="lede">
|
||||
Upload or paste a bounded CSV, ask for the highest numeric row, and reopen the saved, grounded answer after refresh.
|
||||
</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="session-card" aria-live="polite">
|
||||
<span>{session?.authenticated ? "Signed in" : "Sign-in required to run"}</span>
|
||||
<strong>{session?.user?.email || session?.email || session?.org?.slug || "A2A Cloud user"}</strong>
|
||||
{needsSignIn && signInHref ? <a href={signInHref}>Sign in securely</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>
|
||||
</div>
|
||||
<a href={config.docs.base} rel="noreferrer" target="_blank">
|
||||
Docs
|
||||
</a>
|
||||
</header>
|
||||
{error ? <div className="alert" role="alert">{error}</div> : null}
|
||||
|
||||
{selectedSkill ? (
|
||||
<form className="runner" onSubmit={runSkill}>
|
||||
<section className="grid">
|
||||
<form className="card workflow" onSubmit={runAnalysis}>
|
||||
<div className="field-row">
|
||||
<label>
|
||||
Arguments JSON
|
||||
<textarea
|
||||
spellCheck="false"
|
||||
value={argsText}
|
||||
onChange={(event) => setArgsText(event.target.value)}
|
||||
/>
|
||||
Analysis ID
|
||||
<input value={analysisId} onChange={(event) => setAnalysisId(event.target.value)} maxLength={128} required />
|
||||
</label>
|
||||
<button disabled={running} type="submit">
|
||||
{running ? "Running..." : `Run ${selectedSkill.name}`}
|
||||
<button type="button" className="secondary" onClick={() => reopen()} disabled={running || needsSignIn}>
|
||||
Reopen saved
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<p className="empty">Add a `@a2a.tool` to your agent to make it callable here.</p>
|
||||
)}
|
||||
</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>
|
||||
<label>
|
||||
Question
|
||||
<input value={question} onChange={(event) => setQuestion(event.target.value)} required />
|
||||
</label>
|
||||
|
||||
<label>
|
||||
Paste CSV text <small>UTF-8, max {maxKb} KB, {"≤"}500 rows</small>
|
||||
<textarea
|
||||
value={csvText}
|
||||
onChange={(event) => { setCsvText(event.target.value); setFile(null); }}
|
||||
disabled={Boolean(file)}
|
||||
spellCheck="false"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="upload">
|
||||
Or choose CSV file
|
||||
<input accept=".csv,text/csv,text/plain" type="file" onChange={onFileChange} />
|
||||
{file ? <span>{file.name} · {Math.ceil(file.size / 1024)} KB · browser base64 bridge</span> : <span>External clients can also use typed FileUpload.</span>}
|
||||
</label>
|
||||
|
||||
<div className="actions">
|
||||
<button type="submit" disabled={running || needsSignIn}>{running ? "Analyzing..." : "Analyze and save"}</button>
|
||||
<button type="button" className="ghost" onClick={() => { setCsvText(SAMPLE_CSV); setFile(null); setQuestion("Which month has the highest revenue?"); }}>
|
||||
Load sample
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<section className="card result" aria-live="polite">
|
||||
<p className="eyebrow">Grounded answer</p>
|
||||
{result?.ok ? (
|
||||
<>
|
||||
<h2>{result.answer}</h2>
|
||||
<dl className="facts">
|
||||
<div><dt>Rows</dt><dd>{result.row_count}</dd></div>
|
||||
<div><dt>Numeric column</dt><dd>{result.numeric_column}</dd></div>
|
||||
<div><dt>Receipt</dt><dd>{result.receipt_id || "pending"}</dd></div>
|
||||
</dl>
|
||||
<h3>Source rows</h3>
|
||||
<div className="table-wrap"><table><tbody>{result.source_rows?.map((row) => Object.entries(row.values || {}).map(([key, value]) => (
|
||||
<tr key={`${row.row_number}-${key}`}><th>{key}</th><td>{String(value)}</td></tr>
|
||||
)))}</tbody></table></div>
|
||||
<h3>Chart-ready data</h3>
|
||||
<div className="bars">
|
||||
{(result.chart_data || []).map((point) => {
|
||||
const max = Math.max(...(result.chart_data || []).map((p) => p.value), 1);
|
||||
return <div className="bar" key={point.label}><span>{point.label}</span><meter min="0" max={max} value={point.value}>{point.value}</meter><strong>{point.value}</strong></div>;
|
||||
})}
|
||||
</div>
|
||||
</>
|
||||
) : result ? (
|
||||
<div className="empty"><h2>{result.code || "Unable to analyze CSV"}</h2><p>{result.message}</p></div>
|
||||
) : (
|
||||
<div className="empty"><h2>No analysis yet</h2><p>Run the sample fixture or upload your own CSV to see the answer, rows, and chart data.</p></div>
|
||||
)}
|
||||
</section>
|
||||
</section>
|
||||
|
||||
<section className="card history">
|
||||
<div className="history-head"><div><p className="eyebrow">Saved analyses</p><h2>Reload-safe history</h2></div><button className="secondary" onClick={() => refreshHistory()} disabled={running || needsSignIn}>Refresh</button></div>
|
||||
{history.length ? (
|
||||
<ul>{history.map((item) => <li key={item.analysis_id}><button type="button" onClick={() => reopen(item.analysis_id)}><strong>{item.analysis_id}</strong><span>{item.answer}</span></button></li>)}</ul>
|
||||
) : <p className="muted">Saved analyses appear here after a successful run for this signed-in user.</p>}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user