mirror of
https://github.com/fabro-sh/fabro.git
synced 2026-12-01 00:27:17 +00:00
## Summary
Adds a new `/playground` route where users build a Fabro workflow by
chatting with Ask Fabro on the right while watching a live canvas
re-render on the left. The workflow can be downloaded as a `.fabro.zip`
or — eventually — launched as a real Fabro run; today the "Run for
real" button POSTs to `/api/v1/runs` and redirects to the resulting
`/runs/{id}` page, with a placeholder project/repo/folder picker.
The feature is built as a standalone component subtree under
`apps/fabro-web/app/components/playground/` with no `AppShell` or
`react-router` dependencies, so it can be re-embedded in other contexts
later by passing `chatEndpoint`, `authMode`, and an optional
`realRunRedirect` prop.
## What changed
**Frontend (`apps/fabro-web/`)**
- New `/playground` route + `<Playground>` component tree.
- Live SVG canvas via `@viz-js/viz` with click-to-inspect (read-only
node detail panel), pan, zoom, fit-to-window, and a simulated walk
through the graph driven by a Play button.
- Docked chat sidebar (assistant-ui) wired to the new
`/api/v1/playground/chat` endpoint, with auto-retry on parse failure
and a playground-specific tool-call summary that reads
`Wrote workflow.fabro (N nodes, M edges)`.
- File tabs (`workflow.fabro` / `workflow.toml` / `README.md`),
`.fabro.zip` download via `fflate`, and a "Run for real" toolbar
button that POSTs an inline `RunManifest` to `/api/v1/runs`.
- Draft persists across page refreshes via `localStorage`.
**Backend (`lib/crates/fabro-server/`)**
- New `POST /api/v1/playground/chat` SSE endpoint. Server is stateless
across turns: each request carries the full draft, the server runs
the LLM with a single `write_workflow_file` tool, streams
`StreamEvent` frames back, and lets the client own diffing/animating
the result into the canvas.
- Request-size caps before the LLM call (50 messages, 100 nodes, 200
edges) so a misbehaving or malicious client can't drag multi-MB
transcripts through token billing.
**Spec / wire contract**
- OpenAPI: new `playground/chat` operation + four new schemas
(`CreatePlaygroundChatRequest`, `PlaygroundWorkflowDraft`,
`PlaygroundWorkflowNode`, `PlaygroundWorkflowEdge`).
- `lib/packages/fabro-api-client` not regenerated yet (the playground
uses raw `fetch`); reviewers who want the TS client to pick up the
new types can run `bun run generate` in that package.
## Key design decisions
1. **Single `write_workflow_file` tool, not six per-op tools.** The
first cut exposed `add_node`/`update_node`/`connect`/etc. as
discrete tool calls. The model would routinely add nodes without
wiring them up, leaving the canvas in a broken half-state. Pivoted
to a single tool that takes the full new `workflow.fabro` content;
the browser parses the DOT, diffs it against the local draft, and
animates the resulting reducer ops in. The model only has to "get
the file right", and the canvas still paints node-by-node thanks
to the client-side animator.
2. **Stateless server.** Each chat turn POSTs the full current draft;
nothing is persisted server-side. Keeps the endpoint cheap, makes
refresh-resumption trivial (browser owns the truth), and means the
same endpoint can later sit behind a rate-limited anonymous variant
without growing per-session state.
3. **Standalone component subtree.** `<Playground>` has no
`AppShell`/router/store dependencies. All cross-cutting concerns
flow in as props (`chatEndpoint`, `authMode`, `realRunRedirect`).
This is the structural hook that makes future re-embedding possible
without a refactor.
4. **Chat is the only mutation path.** Click-to-inspect on the canvas
is read-only. Bi-directional canvas editing was explicitly cut from
scope to keep one source of truth for "how the workflow changed."
5. **Inline `RunManifest` instead of temp-dir-then-clone.** The
playground has no project to run against, so the `Run for real`
modal builds a `RunManifest` that carries the full DOT and
`workflow.toml` source inline (`workflows[key].{source, config}`).
`cwd` is pinned to a fixed `/tmp/fabro-playground` constant — no
LLM-controlled segment in a filesystem-looking field.
6. **React effects policy compliance.** All `useEffect` calls in
playground component code go through the existing primitives in
`app/hooks/effects.ts` (`useDocumentEvent`, `useInterval`) or a
purpose-named hook (`useCanvasRender`).
## Still outstanding (planned follow-ups)
- [ ] **Actually kicking off the ad-hoc run.** "Run for real" today
POSTs a manifest with a placeholder project/repo/folder
fieldset. The intent is to reuse the project-picker pattern
being introduced on the in-flight automations branch — once
that pattern lands, the disabled inputs in
`run-for-real-modal.tsx` become the live surface.
- [ ] **Header link to `/playground`.** No nav entry yet; users have
to type the URL directly.
- [ ] **Live SSE-driven canvas overlay** via
`GET /api/v1/runs/{id}/attach` — currently the modal redirects
to the standard run-view page; the "watch it build on the
playground canvas" experience comes when the `stage.*` events
are wired through.
- [ ] **Regenerate `lib/packages/fabro-api-client`** so the new types
ship to TS consumers.
- [ ] **Smoke test:** end-to-end download → unzip →
`fabro run <name>` round-trip.
- [ ] **`scripts/build.ts` dist-symlink bug:** `pruneOldBuilds` can
delete the directory `apps/fabro-web/dist` points at, which
pins the dev server in 503 "build in progress" forever.
Workaround documented; the real fix is a separate PR.
## Test plan
- [ ] `cd apps/fabro-web && bun run test app/components/playground/` —
111 tests pass
- [ ] `cd apps/fabro-web && bun run typecheck` — clean
- [ ] `cargo test -p fabro-server playground` — 6 tests pass
- [ ] Visit `/playground`; the canvas renders the welcome `start → ??? →
exit` ghost.
- [ ] Type "build me a release-notes workflow" in chat; nodes/edges
animate in; ack reads `Wrote workflow.fabro (N nodes, M edges)`.
- [ ] Click a node → inspector panel populates; click empty canvas →
deselects.
- [ ] Click `Simulate`; nodes light up `start → ... → exit` along the
resolved path.
- [ ] Click `Download .fabro`; unzip; `cd <unzipped> && fabro run
<name>` runs locally.
- [ ] Click `Run for real` → modal opens → confirm → POST succeeds →
redirected to `/runs/{id}` → run executes.
- [ ] Refresh the page; the draft persists from localStorage.
- [ ] Click `Start over` → `Yes`; canvas resets to welcome state.
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
170 lines
6 KiB
TypeScript
170 lines
6 KiB
TypeScript
/**
|
|
* Canvas-flavoured DOT renderer.
|
|
*
|
|
* Layers on top of `files/render-fabro.ts` to:
|
|
*
|
|
* 1. Inject the playground's graph theme (`graphTheme` from `lib/graph-theme`)
|
|
* so the rendered SVG matches the rest of fabro-web rather than
|
|
* Graphviz's defaults.
|
|
* 2. In the welcome state (`start → exit` with no user nodes), splice in a
|
|
* dashed ghost `???` node so the canvas doesn't look like an empty page.
|
|
*
|
|
* The canvas-only decorations live here so the download artifact
|
|
* (`render-fabro.ts`) stays a clean, vendor-neutral `.fabro` file with no
|
|
* theme attributes baked in.
|
|
*/
|
|
|
|
import { graphTheme } from "../../../lib/graph-theme";
|
|
import { isWelcomeState, type WorkflowDraft } from "../state/draft";
|
|
import type { SimulationState } from "./simulation";
|
|
|
|
const GHOST_ID = "__ghost__";
|
|
|
|
/** Highlight overlay derived from the live simulation state. */
|
|
function simulationOverlay(node: string, sim?: SimulationState): string | null {
|
|
if (!sim) return null;
|
|
if (sim.active === node) {
|
|
return ` ${node} [fillcolor="${graphTheme.runningFill}", color="${graphTheme.runningBorder}", fontcolor="${graphTheme.runningText}", penwidth=2]`;
|
|
}
|
|
if (sim.done.includes(node)) {
|
|
return ` ${node} [fillcolor="${graphTheme.completedFill}", color="${graphTheme.completedBorder}", fontcolor="${graphTheme.completedText}"]`;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Defaults injected at the top of the DOT, mirroring `automation-diagram`. */
|
|
function styleHeader(): string {
|
|
return [
|
|
" bgcolor=\"transparent\"",
|
|
" pad=0.5",
|
|
"",
|
|
" node [",
|
|
" fontname=\"ui-sans-serif, system-ui\"",
|
|
" fontsize=12",
|
|
` fontcolor="${graphTheme.nodeText}"`,
|
|
` color="${graphTheme.edgeColor}"`,
|
|
` fillcolor="${graphTheme.nodeFill}"`,
|
|
" style=filled",
|
|
" penwidth=1.2",
|
|
" ]",
|
|
" edge [",
|
|
" fontname=\"ui-monospace, monospace\"",
|
|
" fontsize=10",
|
|
` fontcolor="${graphTheme.fontcolor}"`,
|
|
` color="${graphTheme.edgeColor}"`,
|
|
" arrowsize=0.7",
|
|
" penwidth=1.2",
|
|
" ]",
|
|
].join("\n");
|
|
}
|
|
|
|
/** Per-shape theming applied to specific node ids. */
|
|
function styleNode(id: string, kind: "start" | "exit" | "ghost"): string {
|
|
if (kind === "start") {
|
|
return ` ${id} [fillcolor="${graphTheme.startFill}", color="${graphTheme.startBorder}", fontcolor="${graphTheme.startText}"]`;
|
|
}
|
|
if (kind === "exit") {
|
|
return ` ${id} [fillcolor="${graphTheme.completedFill}", color="${graphTheme.completedBorder}", fontcolor="${graphTheme.completedText}"]`;
|
|
}
|
|
// ghost
|
|
return ` ${id} [shape=box, label="your workflow goes here", style="dashed,filled", fillcolor="${graphTheme.nodeFill}", color="${graphTheme.fontcolor}", fontcolor="${graphTheme.fontcolor}"]`;
|
|
}
|
|
|
|
/**
|
|
* Build the DOT shown in the canvas. Behaviour:
|
|
*
|
|
* - Welcome state → emits a small `start → ghost → exit` flow with the
|
|
* ghost styled as a dashed placeholder.
|
|
* - Non-welcome state → emits the user's actual graph, themed for fabro-web.
|
|
*
|
|
* The output is deliberately not 1:1 with `render-fabro` — themed attrs and
|
|
* the welcome ghost are canvas-only concerns and must never leak into the
|
|
* downloaded zip.
|
|
*/
|
|
export function renderCanvasDot(
|
|
draft: WorkflowDraft,
|
|
sim?: SimulationState,
|
|
): string {
|
|
const lines: string[] = [];
|
|
lines.push("digraph Playground {");
|
|
if (draft.goal.length > 0) {
|
|
lines.push(` graph [goal="${escapeDot(draft.goal)}"]`);
|
|
}
|
|
lines.push(" rankdir=LR");
|
|
lines.push(styleHeader());
|
|
lines.push("");
|
|
|
|
// Terminals.
|
|
lines.push(' start [shape=Mdiamond, label="Start"]');
|
|
lines.push(' exit [shape=Msquare, label="Exit"]');
|
|
lines.push(styleNode("start", "start"));
|
|
lines.push(styleNode("exit", "exit"));
|
|
lines.push("");
|
|
|
|
if (isWelcomeState(draft)) {
|
|
// Replace the implicit start → exit with start → ghost → exit so the
|
|
// canvas has something to look at on first load.
|
|
lines.push(styleNode(GHOST_ID, "ghost"));
|
|
lines.push(` start -> ${GHOST_ID} -> exit`);
|
|
} else {
|
|
for (const node of draft.nodes) {
|
|
if (node.id === "start" || node.id === "exit") continue;
|
|
lines.push(` ${node.id} [${nodeBody(node)}]`);
|
|
}
|
|
if (draft.nodes.length > 2) lines.push("");
|
|
for (const edge of draft.edges) {
|
|
lines.push(` ${edge.from} -> ${edge.to}${edgeBody(edge)}`);
|
|
}
|
|
}
|
|
|
|
// Apply simulation overlays last so they win over the base theming.
|
|
if (sim) {
|
|
lines.push("");
|
|
for (const node of draft.nodes) {
|
|
const overlay = simulationOverlay(node.id, sim);
|
|
if (overlay) lines.push(overlay);
|
|
}
|
|
}
|
|
|
|
lines.push("}");
|
|
return lines.join("\n");
|
|
}
|
|
|
|
function escapeDot(value: string): string {
|
|
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
}
|
|
|
|
function renderAttrValue(value: string | number | boolean): string {
|
|
if (typeof value === "boolean") return value ? "true" : "false";
|
|
if (typeof value === "number") {
|
|
return Number.isFinite(value) ? String(value) : '"NaN"';
|
|
}
|
|
return `"${escapeDot(value)}"`;
|
|
}
|
|
|
|
function nodeBody(node: WorkflowDraft["nodes"][number]): string {
|
|
const parts: string[] = [`shape=${node.shape}`];
|
|
if (node.label !== undefined) parts.push(`label=${renderAttrValue(node.label)}`);
|
|
if (node.attrs) {
|
|
for (const [k, v] of Object.entries(node.attrs)) {
|
|
// Skip prompts in the canvas — they often run multi-line and clutter
|
|
// node bodies. The chat trace already shows what each node is for.
|
|
parts.push(`${k}=${renderAttrValue(v)}`);
|
|
}
|
|
}
|
|
return parts.join(", ");
|
|
}
|
|
|
|
function edgeBody(edge: WorkflowDraft["edges"][number]): string {
|
|
const parts: string[] = [];
|
|
if (edge.label !== undefined) parts.push(`label=${renderAttrValue(edge.label)}`);
|
|
if (edge.condition !== undefined) {
|
|
parts.push(`condition=${renderAttrValue(edge.condition)}`);
|
|
}
|
|
if (edge.attrs) {
|
|
for (const [k, v] of Object.entries(edge.attrs)) {
|
|
parts.push(`${k}=${renderAttrValue(v)}`);
|
|
}
|
|
}
|
|
return parts.length === 0 ? "" : ` [${parts.join(", ")}]`;
|
|
}
|