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

This commit is contained in:
a2a-cloud
2026-07-19 18:58:32 +00:00
parent ba0edb976e
commit ce0b40c902

View File

@@ -1,17 +1,58 @@
import { useEffect, useMemo, useState } from "react";
import {
callSkill,
loadAgentConfig,
loadSession,
sampleArgs,
signInUrl,
} from "./a2a.js";
import { callSkill, loadAgentConfig, loadSession, signInUrl } from "./a2a.js";
const FIXTURE = {
client_name: "Northstar Property Group",
property_name: "Maple Ridge Apartments",
property_type: "multifamily",
city: "Austin",
goal: "owner update",
tone: "professional",
include_next_steps: true,
intake:
"Owner wants a concise update on leasing momentum, two delayed make-readies, and how the team will prevent renewal friction this month. Traffic is steady but follow-up is inconsistent. Maintenance has three open turns, one vendor delay, and residents are asking for clearer completion dates.",
uploaded_documents: [],
};
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const value = String(reader.result || "");
resolve(value.includes(",") ? value.split(",").pop() : value);
};
reader.onerror = () => reject(reader.error || new Error("Unable to read file"));
reader.readAsDataURL(file);
});
}
function downloadDescriptor(descriptor, fallbackText) {
const filename = descriptor?.filename || "high-utility-one-page-startups-w-e3c7-3-output.md";
const mediaType = descriptor?.media_type || "text/markdown";
let bytes;
if (descriptor?.content_base64) {
const binary = atob(descriptor.content_base64);
bytes = new Uint8Array(binary.length);
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
} else {
bytes = new TextEncoder().encode(fallbackText || "");
}
const blob = new Blob([bytes], { type: mediaType });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
URL.revokeObjectURL(url);
}
export function App() {
const [config, setConfig] = useState(null);
const [session, setSession] = useState(null);
const [selectedSkillName, setSelectedSkillName] = useState("");
const [argsText, setArgsText] = useState("{}");
const [form, setForm] = useState(FIXTURE);
const [files, setFiles] = useState([]);
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
const [running, setRunning] = useState(false);
@@ -20,46 +61,43 @@ export function App() {
loadAgentConfig()
.then((data) => {
setConfig(data);
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 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);
function updateField(field, value) {
setForm((current) => ({ ...current, [field]: value }));
}
async function runSkill(event) {
async function buildUploadedDocuments() {
const selected = Array.from(files).slice(0, 2);
const docs = [];
for (const file of selected) {
if (file.size > 256000) throw new Error(`${file.name} is larger than 256 KB.`);
const mediaType = file.type || "text/plain";
if (!["text/plain", "text/markdown", "application/json", "text/csv"].includes(mediaType)) {
throw new Error(`${file.name} must be a text, markdown, JSON, or CSV file.`);
}
docs.push({ filename: file.name, media_type: mediaType, data_base64: await fileToBase64(file) });
}
return docs;
}
async function submit(event) {
event.preventDefault();
if (!config || !selectedSkill) return;
if (!config || needsSignIn) return;
setRunning(true);
setError(null);
setResult(null);
try {
const args = JSON.parse(argsText || "{}");
const data = await callSkill(config, selectedSkill.name, args);
const uploaded_documents = await buildUploadedDocuments();
const data = await callSkill(config, "generate_document", { request: { ...form, uploaded_documents } });
if (data?.status === "validation_error") throw new Error(data.warnings?.[0] || "Validation failed");
setResult(data);
} catch (err) {
setError(err.message || String(err));
@@ -69,90 +107,110 @@ export function App() {
}
if (!config) {
return (
<main className="loading">
<p>{error || "Loading A2A agent contract..."}</p>
</main>
);
return <main className="loading"><p>{error || "Loading product app..."}</p></main>;
}
return (
<main className="app-shell">
<aside className="sidebar">
<div>
<p className="eyebrow">A2A packed app</p>
<h1>high-utility-one-page-startups-w-e3c7-3</h1>
<p className="agent-meta">
{config.agent.name} v{config.agent.version}
<main className="product-shell" data-testid="agent-app">
<section className="hero-card">
<p className="eyebrow">Property manager document generator</p>
<h1>Turn a short intake into a client-ready one-page document.</h1>
<p className="hero-copy">
Built for property managers who need a polished owner update, leasing plan, maintenance brief,
or management proposal in under two minutes. The workflow returns a live preview and a named markdown artifact.
</p>
<div className="trial-note">
<strong>Account trial:</strong> this agent requires an A2A account, funds exactly 3 platform skill calls,
then requires BYOK.
</div>
{needsSignIn && signInHref ? <a className="signin" href={signInHref}>Sign in to run this workflow</a> : null}
</section>
<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}
<form className="generator-card" onSubmit={submit}>
<div className="grid two">
<label>Client name
<input data-testid="client-name" value={form.client_name} onChange={(e) => updateField("client_name", e.target.value)} />
</label>
<label>Property name
<input data-testid="property-name" value={form.property_name} onChange={(e) => updateField("property_name", e.target.value)} />
</label>
</div>
</aside>
<section className="workbench">
<header className="toolbar">
<div>
<p className="eyebrow">Skill runner</p>
<h2>{selectedSkill?.name || "No skills found"}</h2>
<div className="grid four">
<label>Property type
<select value={form.property_type} onChange={(e) => updateField("property_type", e.target.value)}>
<option value="multifamily">Multifamily</option>
<option value="single-family">Single-family</option>
<option value="commercial">Commercial</option>
<option value="mixed-use">Mixed-use</option>
<option value="hoa">HOA</option>
</select>
</label>
<label>City
<input value={form.city} onChange={(e) => updateField("city", e.target.value)} />
</label>
<label>Document goal
<select value={form.goal} onChange={(e) => updateField("goal", e.target.value)}>
<option value="owner update">Owner update</option>
<option value="leasing plan">Leasing plan</option>
<option value="maintenance brief">Maintenance brief</option>
<option value="management proposal">Management proposal</option>
</select>
</label>
<label>Tone
<select value={form.tone} onChange={(e) => updateField("tone", e.target.value)}>
<option value="professional">Professional</option>
<option value="warm">Warm</option>
<option value="executive">Executive</option>
<option value="urgent">Urgent</option>
</select>
</label>
</div>
<a href={config.docs.base} rel="noreferrer" target="_blank">
Docs
</a>
</header>
{selectedSkill ? (
<form className="runner" onSubmit={runSkill}>
<label>
Arguments JSON
<label>Short intake
<textarea
spellCheck="false"
value={argsText}
onChange={(event) => setArgsText(event.target.value)}
data-testid="agent-input"
value={form.intake}
maxLength={5000}
onChange={(e) => updateField("intake", e.target.value)}
/>
</label>
<button disabled={running} type="submit">
{running ? "Running..." : `Run ${selectedSkill.name}`}
<label className="upload-box">Optional supporting text upload (max 2 files, 256 KB each)
<input
type="file"
accept="text/plain,text/markdown,application/json,text/csv,.txt,.md,.json,.csv"
multiple
onChange={(e) => setFiles(e.target.files || [])}
/>
</label>
<label className="check-row">
<input type="checkbox" checked={form.include_next_steps} onChange={(e) => updateField("include_next_steps", e.target.checked)} />
Include next steps
</label>
<button data-testid="agent-submit" disabled={running || needsSignIn} type="submit">
{running ? "Generating document..." : "Generate one-page document"}
</button>
{error ? <div className="error" role="alert">{error}</div> : null}
</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>
{result ? (
<section className="result-card" data-testid="agent-result">
<div className="result-header">
<div>
<p className="eyebrow">Document preview</p>
<h2>{result.document?.filename || "Generated document"}</h2>
<p>Receipt: {result.receipt_id} · {result.persisted_receipt ? "receipt persisted" : "receipt persistence pending"}</p>
</div>
<div className="panel">
<h3>Result</h3>
<pre>{error || JSON.stringify(result, null, 2) || "No run yet."}</pre>
<button
data-testid="agent-download"
type="button"
onClick={() => downloadDescriptor(result.document, result.document_preview)}
>
Download markdown
</button>
</div>
{result.warnings?.length ? <div className="warning">{result.warnings.join(" ")}</div> : null}
<pre className="preview">{result.document_preview}</pre>
</section>
</section>
) : null}
</main>
);
}