Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

Release v0.20.13

Louis Choquel90d36b270409
diff --git a/.badges/tests.json b/.badges/tests.json
index 1b27bd501..e3a697fa5 100644
--- a/.badges/tests.json
+++ b/.badges/tests.json
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"label": "tests",
- "message": "4032",
+ "message": "4001",
"color": "blue",
"cacheSeconds": 300
}
\ No newline at end of file
diff --git a/.pipelex/pipelex.toml b/.pipelex/pipelex.toml
index 2f0f7c027..e46531f62 100644
--- a/.pipelex/pipelex.toml
+++ b/.pipelex/pipelex.toml
@@ -48,7 +48,6 @@ error_stack_traces = true
graphspec_json = true
mermaidflow_mmd = true
mermaidflow_html = true
-reactflow_viewspec = true
reactflow_html = true
[pipelex.pipeline_execution_config.graph_config.reactflow_config]
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9d3920145..3906d2baf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## [v0.20.13] - 2026-03-16
+
+### Removed
+
+- Remove unused `ViewSpec` class and related code from graph/reactflow — dead code that was no longer referenced.
+
## [v0.20.12] - 2026-03-16
### Fixed
diff --git a/docs/under-the-hood/execution-graph-tracing.md b/docs/under-the-hood/execution-graph-tracing.md
index f98562ed5..c0cbad328 100644
--- a/docs/under-the-hood/execution-graph-tracing.md
+++ b/docs/under-the-hood/execution-graph-tracing.md
@@ -84,7 +84,6 @@ graph_spec = await dry_run_pipe_with_graph(pipe)
| `graphspec_json` | `_graphspec.json` | Canonical graph representation |
| `mermaidflow_mmd` | `_mermaid.mmd` | Mermaid flowchart code |
| `mermaidflow_html` | `_mermaid.html` | Standalone Mermaid viewer |
-| `reactflow_viewspec` | `_viewspec.json` | ViewSpec for ReactFlow |
| `reactflow_html` | `_reactflow.html` | Interactive ReactFlow viewer |
---
@@ -132,11 +131,9 @@ flowchart TB
subgraph RENDER["Renderers"]
direction TB
MF["MermaidflowFactory"]
- RF["ViewSpec Transformer"]
- HTML1["Mermaid HTML"]
- HTML2["ReactFlow HTML"]
- MF --> HTML1
- RF --> HTML2
+ RF["ReactFlow HTML Generator"]
+ MF --> HTML1["Mermaid HTML"]
+ RF --> HTML2["ReactFlow HTML"]
end
JOB --> CTX
@@ -363,27 +360,9 @@ print(mermaidflow.mermaid_code)
- Stuff nodes (data items) rendered as stadium shapes
- DATA edges connect producers → stuff → consumers
-### ViewSpec (ReactFlow)
+### ReactFlow HTML
-Transforms GraphSpec into a viewer-oriented model:
-
-```python
-from pipelex.graph.reactflow.viewspec_transformer import graphspec_to_viewspec
-
-analysis = GraphAnalysis.from_graphspec(graph_spec)
-viewspec = graphspec_to_viewspec(
- graph_spec,
- analysis,
- options={"show_data_edges": True},
-)
-```
-
-ViewSpec provides:
-
-- `ViewNode` with UI metadata (badges, classes, inspector data)
-- `ViewEdge` with ReactFlow properties (animated, hidden)
-- `ViewIndex` for fast client-side lookups
-- Layout configuration for Dagre
+ReactFlow HTML is generated directly from GraphSpec — no intermediate ViewSpec layer. The HTML generator embeds GraphSpec as JSON and the client-side JavaScript handles dataflow analysis, layout, and rendering.
---
@@ -405,7 +384,6 @@ error_stack_traces = true # Include full stack traces
graphspec_json = true # Generate GraphSpec JSON
mermaidflow_mmd = true # Generate Mermaid code
mermaidflow_html = true # Generate Mermaid HTML
-reactflow_viewspec = true # Generate ViewSpec JSON
reactflow_html = true # Generate ReactFlow HTML
```
@@ -480,7 +458,7 @@ validate_graphspec(graph_spec)
| `GraphSpec.to_json()` | Serialize to JSON string |
| `GraphAnalysis.from_graphspec(g)` | Pre-compute analysis |
| `MermaidflowFactory.make_from_graphspec(...)` | Generate Mermaid |
-| `graphspec_to_viewspec(g, analysis)` | Generate ViewSpec |
+| `generate_reactflow_html(graphspec, config)` | Generate ReactFlow HTML |
| `generate_graph_outputs(g, config, pipe_code)` | Generate all outputs |
---
diff --git a/pipelex/cli/agent_cli/commands/validate/bundle_cmd.py b/pipelex/cli/agent_cli/commands/validate/bundle_cmd.py
index 3bd63556e..7de1addab 100644
--- a/pipelex/cli/agent_cli/commands/validate/bundle_cmd.py
+++ b/pipelex/cli/agent_cli/commands/validate/bundle_cmd.py
@@ -49,7 +49,7 @@ def validate_bundle_cmd(
] = None,
view: Annotated[
bool,
- typer.Option("--view", help="On successful bundle validation, include a ViewSpec (structured JSON for graph rendering) in the output"),
+ typer.Option("--view", help="On successful bundle validation, include a GraphSpec (structured JSON for graph rendering) in the output"),
] = False,
library_dir: Annotated[
list[str] | None,
@@ -147,7 +147,7 @@ def validate_bundle_cmd(
except Exception as exc:
agent_error(f"Graph generation failed: {exc}", type(exc).__name__, cause=exc)
- # Generate view (ViewSpec JSON) if requested and validation succeeded
+ # Generate view (GraphSpec JSON) if requested and validation succeeded
if view:
try:
view_result = asyncio.run(
diff --git a/pipelex/graph/graph_config.py b/pipelex/graph/graph_config.py
index e55813d39..021d9bc4d 100644
--- a/pipelex/graph/graph_config.py
+++ b/pipelex/graph/graph_config.py
@@ -18,7 +18,6 @@ class GraphsInclusionConfig(ConfigModel):
graphspec_json: bool
mermaidflow_mmd: bool
mermaidflow_html: bool
- reactflow_viewspec: bool
reactflow_html: bool
diff --git a/pipelex/graph/graph_factory.py b/pipelex/graph/graph_factory.py
index 71adbb6c5..27d4e87c0 100644
--- a/pipelex/graph/graph_factory.py
+++ b/pipelex/graph/graph_factory.py
@@ -11,13 +11,10 @@ from typing import TYPE_CHECKING
from pydantic import BaseModel
from pipelex import log
-from pipelex.graph.graph_analysis import GraphAnalysis
from pipelex.graph.mermaidflow.mermaid_html import render_mermaid_html_async, render_mermaid_html_with_data_async
from pipelex.graph.mermaidflow.mermaidflow_factory import MermaidflowFactory
from pipelex.graph.mermaidflow.stuff_collector import collect_stuff_data_html, collect_stuff_data_text
from pipelex.graph.reactflow.reactflow_html import generate_reactflow_html_async
-from pipelex.graph.reactflow.viewspec import LayoutSpec
-from pipelex.graph.reactflow.viewspec_transformer import graphspec_to_viewspec
from pipelex.tools.misc.string_utils import snake_to_title_case
if TYPE_CHECKING:
@@ -37,14 +34,12 @@ class GraphOutputs(BaseModel):
graphspec_json: The GraphSpec serialized as JSON.
mermaidflow_mmd: Mermaidflow view as Mermaid flowchart code.
mermaidflow_html: Mermaidflow view as standalone HTML page.
- reactflow_viewspec: The ViewSpec serialized as JSON for ReactFlow rendering.
reactflow_html: ReactFlow interactive graph as standalone HTML page.
"""
graphspec_json: str | None = None
mermaidflow_mmd: str | None = None
mermaidflow_html: str | None = None
- reactflow_viewspec: str | None = None
reactflow_html: str | None = None
@@ -64,7 +59,6 @@ async def generate_graph_outputs(
This can generate:
- GraphSpec JSON: The canonical graph representation
- Mermaidflow view: Data flow with controller subgraphs (Mermaid)
- - ReactFlow ViewSpec: JSON for ReactFlow rendering
- ReactFlow HTML: Interactive graph viewer
Args:
@@ -84,7 +78,6 @@ async def generate_graph_outputs(
graphspec_json: str | None = None
mermaidflow_mmd: str | None = None
mermaidflow_html: str | None = None
- reactflow_viewspec: str | None = None
reactflow_html: str | None = None
# Generate GraphSpec JSON
@@ -121,47 +114,31 @@ async def generate_graph_outputs(
else:
mermaidflow_html = await render_mermaid_html_async(mermaidflow.mermaid_code, title=page_title, theme=mermaid_theme)
- # Generate ReactFlow outputs
- if inclusion.reactflow_viewspec or inclusion.reactflow_html:
- analysis = GraphAnalysis.from_graphspec(graph_spec)
- rf_config = graph_config.reactflow_config
- effective_rf_direction = direction or rf_config.layout_direction
- layout = LayoutSpec(
- direction=effective_rf_direction,
- nodesep=rf_config.nodesep,
- ranksep=rf_config.ranksep,
+ # Generate ReactFlow HTML
+ if inclusion.reactflow_html:
+ # Collect stuff data in alternate formats if configured
+ rf_stuff_data_text: dict[str, str] | None = None
+ rf_stuff_data_html: dict[str, str] | None = None
+ if graph_config.data_inclusion.stuff_text_content:
+ log.verbose("Collecting stuff data text for graph_spec")
+ rf_stuff_data_text = collect_stuff_data_text(graph_spec)
+ else:
+ log.verbose("No stuff data text to collect for graph_spec")
+ if graph_config.data_inclusion.stuff_html_content:
+ rf_stuff_data_html = collect_stuff_data_html(graph_spec)
+
+ reactflow_html = await generate_reactflow_html_async(
+ graph_spec,
+ graph_config.reactflow_config,
+ stuff_data_text=rf_stuff_data_text,
+ stuff_data_html=rf_stuff_data_html,
+ title=page_title,
)
- viewspec = graphspec_to_viewspec(graph_spec, analysis, layout=layout)
-
- if inclusion.reactflow_viewspec:
- reactflow_viewspec = viewspec.model_dump_json(indent=2)
-
- if inclusion.reactflow_html:
- # Collect stuff data in alternate formats if configured
- rf_stuff_data_text: dict[str, str] | None = None
- rf_stuff_data_html: dict[str, str] | None = None
- if graph_config.data_inclusion.stuff_text_content:
- log.verbose("Collecting stuff data text for graph_spec")
- rf_stuff_data_text = collect_stuff_data_text(graph_spec)
- else:
- log.verbose("No stuff data text to collect for graph_spec")
- if graph_config.data_inclusion.stuff_html_content:
- rf_stuff_data_html = collect_stuff_data_html(graph_spec)
-
- reactflow_html = await generate_reactflow_html_async(
- viewspec,
- graph_config.reactflow_config,
- graphspec=graph_spec,
- stuff_data_text=rf_stuff_data_text,
- stuff_data_html=rf_stuff_data_html,
- title=page_title,
- )
return GraphOutputs(
graphspec_json=graphspec_json,
mermaidflow_mmd=mermaidflow_mmd,
mermaidflow_html=mermaidflow_html,
- reactflow_viewspec=reactflow_viewspec,
reactflow_html=reactflow_html,
)
@@ -205,12 +182,6 @@ def save_graph_outputs_to_dir(
saved_files["mermaidflow_html"] = file_path
log.verbose(f"Mermaidflow HTML saved to: {file_path}")
- if graph_outputs.reactflow_viewspec is not None:
- file_path = output_dir / "viewspec.json"
- file_path.write_text(graph_outputs.reactflow_viewspec, encoding="utf-8")
- saved_files["reactflow_viewspec"] = file_path
- log.verbose(f"ReactFlow ViewSpec saved to: {file_path}")
-
if graph_outputs.reactflow_html is not None:
file_path = output_dir / "reactflow.html"
file_path.write_text(graph_outputs.reactflow_html, encoding="utf-8")
diff --git a/pipelex/graph/graph_rendering.py b/pipelex/graph/graph_rendering.py
index 5c34ba892..548923ed4 100644
--- a/pipelex/graph/graph_rendering.py
+++ b/pipelex/graph/graph_rendering.py
@@ -11,12 +11,9 @@ from pipelex.base_exceptions import PipelexError
from pipelex.config import get_config
from pipelex.core.interpreter.exceptions import PipelexInterpreterError
from pipelex.core.interpreter.interpreter import PipelexInterpreter
-from pipelex.graph.graph_analysis import GraphAnalysis
from pipelex.graph.graph_config import GraphConfig
from pipelex.graph.graph_factory import GraphOutputs, generate_graph_outputs, save_graph_outputs_to_dir
from pipelex.graph.graphspec import GraphSpec
-from pipelex.graph.reactflow.viewspec import LayoutSpec
-from pipelex.graph.reactflow.viewspec_transformer import graphspec_to_viewspec
from pipelex.pipe_run.pipe_run_mode import PipeRunMode
from pipelex.pipeline.runner import PipelexRunner
from pipelex.tools.misc.chart_utils import FlowchartDirection
@@ -89,7 +86,6 @@ async def render_graph_from_spec(
"graphspec_json": False,
"mermaidflow_mmd": False,
"mermaidflow_html": include_mermaidflow,
- "reactflow_viewspec": False,
"reactflow_html": include_reactflow,
}
),
@@ -246,15 +242,14 @@ async def generate_graph_for_bundle(
}
-# TODO: refactor to do only one dry run and generate both graph and ViewSpec
async def generate_view_for_bundle(
bundle_path: Path,
library_dirs: list[str] | None = None,
direction: FlowchartDirection | None = None,
) -> dict[str, Any]:
- """Generate a ViewSpec for a bundle via dry-run pipeline execution.
+ """Generate a GraphSpec for a bundle via dry-run pipeline execution.
- Returns structured JSON data (ViewSpec) suitable for client-side rendering,
+ Returns structured JSON data (GraphSpec) suitable for client-side rendering,
without writing any files to disk.
Args:
@@ -263,7 +258,7 @@ async def generate_view_for_bundle(
direction: Flowchart layout direction (default: None, uses config default).
Returns:
- Dictionary with viewspec (JSON-serializable dict), pipe_code, and direction.
+ Dictionary with graphspec (JSON-serializable dict), pipe_code, and direction.
Raises:
PipelexInterpreterError: If bundle parsing fails or main_pipe is missing.
@@ -279,16 +274,7 @@ async def generate_view_for_bundle(
rf_config = execution_config.graph_config.reactflow_config
effective_direction = direction or rf_config.layout_direction
- analysis = GraphAnalysis.from_graphspec(graph_spec)
- layout = LayoutSpec(
- direction=effective_direction,
- nodesep=rf_config.nodesep,
- ranksep=rf_config.ranksep,
- )
- viewspec = graphspec_to_viewspec(graph_spec, analysis, layout=layout)
-
return {
- "viewspec": viewspec.model_dump(mode="json"),
"graphspec": graph_spec.model_dump(mode="json", by_alias=True),
"pipe_code": pipe_code,
"direction": str(effective_direction) if effective_direction else None,
diff --git a/pipelex/graph/reactflow/reactflow_html.py b/pipelex/graph/reactflow/reactflow_html.py
index ba7d2e46f..d4d9502ee 100644
--- a/pipelex/graph/reactflow/reactflow_html.py
+++ b/pipelex/graph/reactflow/reactflow_html.py
@@ -1,7 +1,7 @@
-"""ReactFlow HTML generator for ViewSpec rendering.
+"""ReactFlow HTML generator for GraphSpec rendering.
This module provides functions to generate standalone HTML files with embedded
-ReactFlow viewers that can render ViewSpec graphs interactively.
+ReactFlow viewers that can render GraphSpec graphs interactively.
"""
import json
@@ -10,7 +10,6 @@ from pipelex.cogt.templating.template_category import TemplateCategory
from pipelex.graph.csp import CSP_NONCE_SENTINEL
from pipelex.graph.graphspec import GraphSpec
from pipelex.graph.reactflow.reactflow_config import ReactFlowRenderingConfig
-from pipelex.graph.reactflow.viewspec import ViewSpec
from pipelex.tools.jinja2.jinja2_rendering import render_jinja2_async, render_jinja2_sync
from pipelex.tools.jinja2.jinja2_template_registry import TemplateRegistry
from pipelex.urls import URLs
@@ -20,20 +19,18 @@ _REACTFLOW_TEMPLATE_KEY = "reactflow/main.html.jinja2"
def generate_reactflow_html(
- viewspec: ViewSpec,
+ graphspec: GraphSpec,
config: ReactFlowRenderingConfig,
*,
- graphspec: GraphSpec | None = None,
stuff_data_text: dict[str, str] | None = None,
stuff_data_html: dict[str, str] | None = None,
title: str | None = None,
) -> str:
- """Generate single-file HTML with embedded ViewSpec and ReactFlow viewer.
+ """Generate single-file HTML with embedded GraphSpec and ReactFlow viewer.
Args:
- viewspec: The ViewSpec to embed and render.
+ graphspec: The GraphSpec to embed and render.
config: ReactFlow rendering configuration.
- graphspec: Optional GraphSpec to embed (for inspector details).
stuff_data_text: Optional mapping from stuff IDs to their ASCII text representation.
stuff_data_html: Optional mapping from stuff IDs to their HTML representation.
title: Optional page title, overrides config.default_title.
@@ -44,13 +41,8 @@ def generate_reactflow_html(
# Get template from pre-loaded registry (sandbox-safe, no I/O at render time)
template_source = TemplateRegistry.get(_REACTFLOW_TEMPLATE_KEY)
- # Serialize ViewSpec to JSON
- viewspec_json = json.dumps(viewspec.model_dump(mode="json"), indent=2)
-
- # Serialize GraphSpec to JSON if provided
- graphspec_json: str | None = None
- if graphspec:
- graphspec_json = json.dumps(graphspec.model_dump(mode="json"), indent=2)
+ # Serialize GraphSpec to JSON
+ graphspec_json = json.dumps(graphspec.model_dump(mode="json"), indent=2)
# Render template (use_registry=True to support {% include %} directives)
return render_jinja2_sync(
@@ -61,12 +53,11 @@ def generate_reactflow_html(
"title": title or config.default_title,
"logo_dark": URLs.logo_white_on_transparent,
"logo_light": URLs.logo_black_on_transparent,
- "viewspec_json": viewspec_json,
"graphspec_json": graphspec_json,
"stuff_data_text_json": json.dumps(stuff_data_text or {}),
"stuff_data_html_json": json.dumps(stuff_data_html or {}),
"use_cdn": config.is_use_cdn,
- "layout_direction": viewspec.layout.direction.reactflow_code,
+ "layout_direction": config.layout_direction.reactflow_code,
"nodesep": config.nodesep,
"ranksep": config.ranksep,
"edge_type": config.edge_type,
@@ -82,22 +73,20 @@ def generate_reactflow_html(
async def generate_reactflow_html_async(
- viewspec: ViewSpec,
+ graphspec: GraphSpec,
config: ReactFlowRenderingConfig,
*,
- graphspec: GraphSpec | None = None,
stuff_data_text: dict[str, str] | None = None,
stuff_data_html: dict[str, str] | None = None,
title: str | None = None,
) -> str:
- """Generate single-file HTML with embedded ViewSpec and ReactFlow viewer (async version).
+ """Generate single-file HTML with embedded GraphSpec and ReactFlow viewer (async version).
Use this when inside an async event loop.
Args:
- viewspec: The ViewSpec to embed and render.
+ graphspec: The GraphSpec to embed and render.
config: ReactFlow rendering configuration.
- graphspec: Optional GraphSpec to embed (for inspector details).
stuff_data_text: Optional mapping from stuff IDs to their ASCII text representation.
stuff_data_html: Optional mapping from stuff IDs to their HTML representation.
title: Optional page title, overrides config.default_title.
@@ -108,13 +97,8 @@ async def generate_reactflow_html_async(
# Get template from pre-loaded registry (sandbox-safe, no I/O at render time)
template_source = TemplateRegistry.get(_REACTFLOW_TEMPLATE_KEY)
- # Serialize ViewSpec to JSON
- viewspec_json = json.dumps(viewspec.model_dump(mode="json"), indent=2)
-
- # Serialize GraphSpec to JSON if provided
- graphspec_json: str | None = None
- if graphspec:
- graphspec_json = json.dumps(graphspec.model_dump(mode="json"), indent=2)
+ # Serialize GraphSpec to JSON
+ graphspec_json = json.dumps(graphspec.model_dump(mode="json"), indent=2)
# Render template (use_registry=True to support {% include %} directives)
return await render_jinja2_async(
@@ -125,12 +109,11 @@ async def generate_reactflow_html_async(
"title": title or config.default_title,
"logo_dark": URLs.logo_white_on_transparent,
"logo_light": URLs.logo_black_on_transparent,
- "viewspec_json": viewspec_json,
"graphspec_json": graphspec_json,
"stuff_data_text_json": json.dumps(stuff_data_text or {}),
"stuff_data_html_json": json.dumps(stuff_data_html or {}),
"use_cdn": config.is_use_cdn,
- "layout_direction": viewspec.layout.direction.reactflow_code,
+ "layout_direction": config.layout_direction.reactflow_code,
"nodesep": config.nodesep,
"ranksep": config.ranksep,
"edge_type": config.edge_type,
diff --git a/pipelex/graph/reactflow/templates/_body.html.jinja2 b/pipelex/graph/reactflow/templates/_body.html.jinja2
index 8b36ac15f..8a32126ee 100644
--- a/pipelex/graph/reactflow/templates/_body.html.jinja2
+++ b/pipelex/graph/reactflow/templates/_body.html.jinja2
@@ -78,12 +78,8 @@
<div class="footer-stats" id="footer-stats"></div>
</footer>
-<!-- Embedded ViewSpec -->
-<script type="application/json" id="pipelex-viewspec">{{ viewspec_json | escape_script_tag | safe }}</script>
-{% if graphspec_json %}
-<!-- Embedded GraphSpec (for dataflow extraction) -->
+<!-- Embedded GraphSpec -->
<script type="application/json" id="pipelex-graphspec">{{ graphspec_json | escape_script_tag | safe }}</script>
-{% endif %}
<!-- Embedded stuff data in multiple formats for display toggle -->
<script type="application/json" id="pipelex-stuff-data-text">{{ stuff_data_text_json | escape_script_tag | safe }}</script>
<script type="application/json" id="pipelex-stuff-data-html">{{ stuff_data_html_json | escape_script_tag | safe }}</script>
diff --git a/pipelex/graph/reactflow/templates/_scripts.js.jinja2 b/pipelex/graph/reactflow/templates/_scripts.js.jinja2
index 82f732a8f..cdfb7d92c 100644
--- a/pipelex/graph/reactflow/templates/_scripts.js.jinja2
+++ b/pipelex/graph/reactflow/templates/_scripts.js.jinja2
@@ -47,13 +47,9 @@ document.getElementById('direction-toggle').addEventListener('click', () => {
if (window.setLayoutDirection) window.setLayoutDirection(currentDirection);
});
-// Parse embedded ViewSpec
-const viewspecElement = document.getElementById('pipelex-viewspec');
-const viewspec = JSON.parse(viewspecElement.textContent);
-
-// Parse GraphSpec if present
+// Parse embedded GraphSpec
const graphspecElement = document.getElementById('pipelex-graphspec');
-const graphspec = graphspecElement ? JSON.parse(graphspecElement.textContent) : null;
+const graphspec = JSON.parse(graphspecElement.textContent);
// Parse stuff data in alternate formats (for display toggle)
const stuffDataTextElement = document.getElementById('pipelex-stuff-data-text');
@@ -149,10 +145,10 @@ const hasDataflow = dataflowAnalysis && Object.keys(dataflowAnalysis.stuffRegist
const statsEl = document.getElementById('footer-stats');
const pipeCount = hasDataflow
? graphspec.nodes.filter(n => !dataflowAnalysis.controllerNodeIds.has(n.node_id)).length
- : viewspec.nodes.length;
+ : graphspec.nodes.length;
const stuffCount = hasDataflow ? Object.keys(dataflowAnalysis.stuffRegistry).length : 0;
-const succeededCount = viewspec.nodes.filter(n => n.status === 'succeeded').length;
-const failedCount = viewspec.nodes.filter(n => n.status === 'failed').length;
+const succeededCount = graphspec.nodes.filter(n => n.status === 'succeeded').length;
+const failedCount = graphspec.nodes.filter(n => n.status === 'failed').length;
statsEl.innerHTML = `
<div class="stat-item">
@@ -543,19 +539,20 @@ function buildDataflowGraph(graphspec, analysis) {
}
// ====================================================================
-// FALLBACK: Build orchestration graph from ViewSpec (no dataflow)
+// FALLBACK: Build orchestration graph from GraphSpec (no dataflow)
// ====================================================================
-function buildOrchestrationGraph(viewspec) {
- const nodes = viewspec.nodes.map(node => {
+function buildOrchestrationGraph(graphspec) {
+ const nodes = graphspec.nodes.map(node => {
const isController = node.kind === 'controller';
- const isFailed = node.ui?.classes?.includes('failed');
- const isSucceeded = node.ui?.classes?.includes('succeeded');
- const badge = node.ui?.badges?.[0] || '';
+ const isFailed = node.status === 'failed';
+ const isSucceeded = node.status === 'succeeded';
+ const label = node.pipe_code || node.node_id.split(':').pop() || node.node_id;
+ const badge = node.timing?.duration ? node.timing.duration.toFixed(1) + 's' : '';
// Calculate width: ~8px per char (monospace 13px) + padding + status dot
- const nodeWidth = Math.max(160, (node.label?.length || 10) * 8 + 50);
+ const nodeWidth = Math.max(160, (label.length || 10) * 8 + 50);
return {
- id: node.id,
+ id: node.node_id,
type: 'default',
data: {
label: React.createElement('div', {
@@ -581,7 +578,7 @@ function buildOrchestrationGraph(viewspec) {
fontWeight: 600,
color: 'var(--color-pipe-text)',
}
- }, node.label),
+ }, label),
isSucceeded && React.createElement('span', {
style: {
width: '8px',
@@ -614,7 +611,7 @@ function buildOrchestrationGraph(viewspec) {
fontSize: '11px',
color: 'var(--color-text-dim)',
}
- }, isController ? 'Controller' : node.inspector?.pipe_type || 'Operator'),
+ }, isController ? 'Controller' : node.pipe_type || 'Operator'),
badge && React.createElement('span', {
style: {
fontSize: '10px',
@@ -631,7 +628,7 @@ function buildOrchestrationGraph(viewspec) {
isPipe: true,
isStuff: false,
},
- position: node.position || { x: 0, y: 0 },
+ position: { x: 0, y: 0 },
style: {
background: isFailed ? 'var(--color-pipe-failed-bg)' : 'var(--color-pipe-bg)',
border: isFailed ? '2px solid var(--color-pipe-failed)' : '2px solid var(--color-pipe)',
@@ -643,12 +640,14 @@ function buildOrchestrationGraph(viewspec) {
};
});
- const edges = viewspec.edges.map(edge => ({
- id: edge.id,
+ // Filter edges: skip CONTAINS edges (handled via containment tree)
+ const visibleEdges = graphspec.edges.filter(edge => edge.kind !== 'contains');
+ const edges = visibleEdges.map((edge, index) => ({
+ id: edge.edge_id || 'edge_' + index,
source: edge.source,
target: edge.target,
type: {{ edge_type | tojson }},
- animated: edge.animated || false,
+ animated: edge.kind === 'data',
label: edge.label,
labelStyle: {
fontSize: 11,
@@ -684,7 +683,7 @@ function GraphViewer() {
if (hasDataflow) {
initialData = buildDataflowGraph(graphspec, dataflowAnalysis);
} else {
- initialData = buildOrchestrationGraph(viewspec);
+ initialData = buildOrchestrationGraph(graphspec);
}
// Apply layout
diff --git a/pipelex/graph/reactflow/viewspec.py b/pipelex/graph/reactflow/viewspec.py
deleted file mode 100644
index 622213fab..000000000
--- a/pipelex/graph/reactflow/viewspec.py
+++ /dev/null
@@ -1,182 +0,0 @@
-"""ViewSpec Pydantic v2 models for ReactFlow and other interactive graph viewers.
-
-This module defines viewer-oriented, derived models that sit on top of GraphSpec
-and answer: "What should the UI render, and how?" ViewSpec is safe to regenerate
-at any time from GraphSpec + viewer/CLI options.
-
-ViewSpec is renderer-specific enough to be convenient (ReactFlow types, handles,
-layout params), but still broadly usable for other interactive renderers later.
-"""
-
-from datetime import datetime
-from typing import Any, Literal
-
-from pydantic import BaseModel, ConfigDict, Field
-
-from pipelex.tools.misc.chart_utils import FlowchartDirection
-from pipelex.tools.typing.pydantic_utils import empty_list_factory_of
-
-# Current ViewSpec schema version (independent of GraphSpec version)
-CURRENT_VIEWSPEC_VERSION = "1.0"
-
-ViewEngine = Literal["reactflow"]
-LayoutEngine = Literal["dagre"]
-
-
-class LayoutSpec(BaseModel):
- """Layout configuration for graph rendering.
-
- Specifies how the graph should be laid out, typically using Dagre.
- """
-
- model_config = ConfigDict(extra="forbid", strict=True)
-
- engine: LayoutEngine = "dagre"
- direction: FlowchartDirection = Field(default=FlowchartDirection.TOP_DOWN, strict=False)
- nodesep: int | None = 50
- ranksep: int | None = 80
- align: str | None = None
- allow_manual_positions: bool = True
-
-
-class ViewNode(BaseModel):
- """ReactFlow node representation.
-
- Maps a GraphSpec node to a ReactFlow-compatible node with UI metadata,
- inspector data, and optional position/size.
- """
-
- model_config = ConfigDict(extra="forbid", strict=True)
-
- id: str = Field(description="GraphSpec node_id - must match exactly for cross-referencing")
- label: str = Field(description="Display label for the node")
- kind: str = Field(description="Copy or normalize GraphSpec.kind")
- status: str | None = Field(default=None, description="Copy GraphSpec.status when relevant")
-
- # ReactFlow-specific
- type: str = Field(default="default", description='ReactFlow node type, e.g. "operator", "controller", "io", "error", "artifact"')
- parent_id: str | None = Field(default=None, description="Parent node ID for grouping/containment in UI")
- extent: Literal["parent"] | None = Field(default=None, description="ReactFlow grouping behavior (optional)")
-
- # Optional persisted position (viewer will compute with Dagre if absent)
- position: dict[str, float] | None = Field(default=None, description='Optional position dict: {"x": ..., "y": ...}')
- size: dict[str, float] | None = Field(default=None, description='Optional size dict: {"width": ..., "height": ...}')
-
- # Small UI metadata (avoid heavy data here)
- ui: dict[str, Any] = Field(default_factory=dict, description='UI metadata, e.g. {"badges": ["132ms"], "classes": ["ok"], "icon": "llm"}')
-
- # What the inspector needs quickly (lightweight)
- inspector: dict[str, Any] = Field(
- default_factory=dict,
- description='Inspector data, e.g. {"pipe_code": "...", "pipe_type": "...", "timing": {...}, "io_preview": {...}, "error": {...}}',
- )
-
- # Optional handle definitions if you later do port-specific edges
- handles: list[dict[str, Any]] | None = Field(
- default=None,
- description='Optional handles, e.g. [{"id": "out.cv_pages", "type": "source", "position": "Right"}]',
- )
-
-
-class ViewEdge(BaseModel):
- """ReactFlow edge representation.
-
- Maps a GraphSpec edge to a ReactFlow-compatible edge with type, animation,
- and optional handles.
- """
-
- model_config = ConfigDict(extra="forbid", strict=True)
-
- id: str = Field(description="GraphSpec edge_id - must match exactly for cross-referencing")
- source: str = Field(description="Source node ID")
- target: str = Field(description="Target node ID")
- kind: str = Field(description="Copy GraphSpec.kind")
- label: str | None = Field(default=None, description="Edge label if present")
-
- # ReactFlow-specific
- type: str = Field(default="default", description='ReactFlow edge type, e.g. "data", "control", "contains"')
- animated: bool | None = Field(default=None, description="Whether the edge should be animated")
- hidden: bool = Field(default=False, description="Whether the edge should be hidden")
-
- source_handle: str | None = Field(default=None, description="Source handle ID for port-specific edges")
- target_handle: str | None = Field(default=None, description="Target handle ID for port-specific edges")
-
- ui: dict[str, Any] = Field(default_factory=dict, description='UI metadata, e.g. {"classes": ["dashed"], "markerEnd": "arrow"}')
-
-
-class ViewIndex(BaseModel):
- """Optional performance indexes for fast lookups in the viewer.
-
- These indexes avoid expensive client-side recomputation.
- """
-
- model_config = ConfigDict(extra="forbid", strict=True)
-
- edges_by_node: dict[str, list[str]] = Field(
- default_factory=dict,
- description="Map of node_id to list of edge_ids connected to that node",
- )
- children_by_parent: dict[str, list[str]] = Field(
- default_factory=dict,
- description="Map of parent node_id to list of child node_ids",
- )
- search: dict[str, list[str]] = Field(
- default_factory=dict,
- description='Search index, e.g. {"pipe_code:extract_text": ["nodeA"], "status:failed": ["nodeZ"]}',
- )
-
-
-class PayloadSpec(BaseModel):
- """Optional external payload strategy for large graphs.
-
- Allows lazy-loading of full I/O data instead of embedding everything inline.
- """
-
- model_config = ConfigDict(extra="forbid", strict=True)
-
- mode: Literal["inline", "external"] = "inline"
- base_path: str | None = Field(default=None, description="Base path for external payload files")
- by_digest: dict[str, str] = Field(
- default_factory=dict,
- description="Map of digest to relative file path for lazy-loading",
- )
-
-
-class ViewSpec(BaseModel):
- """Viewer-oriented, derived layer for graph rendering.
-
- ViewSpec sits on top of GraphSpec and answers: "What should the UI render, and how?"
- It is safe to regenerate at any time from GraphSpec + viewer/CLI options.
-
- ViewSpec is renderer-specific enough to be convenient (ReactFlow types, handles,
- layout params), but still broadly usable for other interactive renderers later.
- """
-
- model_config = ConfigDict(extra="forbid", strict=True)
-
- schema_version: str = Field(default=CURRENT_VIEWSPEC_VERSION, description="ViewSpec schema version (independent of GraphSpec version)")
- created_at: datetime = Field(description="When this ViewSpec was created")
- graph_id: str = Field(description="Must match GraphSpec.graph_id for cross-referencing")
- source: dict[str, Any] = Field(
- default_factory=dict,
- description='Source metadata, e.g. {"graph_schema_version": "1.0", "graph_digest": "sha256:...", "producer": "pipelex 0.9.3"}',
- )
-
- engine: ViewEngine = Field(default="reactflow", description="View engine identifier")
-
- # Global toggles applied to build this view
- options: dict[str, Any] = Field(
- default_factory=dict,
- description='View options, e.g. {"show_data_edges": True, "collapse_controllers": False, "redaction": "preview-only"}',
- )
-
- layout: LayoutSpec = Field(default_factory=LayoutSpec, description="Layout configuration")
-
- nodes: list[ViewNode] = Field(default_factory=empty_list_factory_of(ViewNode), description="List of view nodes")
- edges: list[ViewEdge] = Field(default_factory=empty_list_factory_of(ViewEdge), description="List of view edges")
-
- # Optional accelerators
- index: ViewIndex | None = Field(default=None, description="Optional performance indexes")
-
- # Optional external payload strategy for big/full-data graphs
- payloads: PayloadSpec | None = Field(default=None, description="Optional payload strategy for lazy-loading")
diff --git a/pipelex/graph/reactflow/viewspec_transformer.py b/pipelex/graph/reactflow/viewspec_transformer.py
deleted file mode 100644
index e391dffbc..000000000
--- a/pipelex/graph/reactflow/viewspec_transformer.py
+++ /dev/null
@@ -1,331 +0,0 @@
-"""Transformer from GraphSpec + GraphAnalysis to ViewSpec for ReactFlow rendering.
-
-This module provides the transformation logic to convert the canonical GraphSpec
-and pre-computed GraphAnalysis into a ViewSpec that is optimized for ReactFlow
-and other interactive graph viewers.
-"""
-
-from collections import defaultdict
-from datetime import datetime, timezone
-from typing import Any
-
-from pipelex.graph.graph_analysis import GraphAnalysis
-from pipelex.graph.graphspec import EdgeKind, GraphSpec, NodeKind, NodeStatus
-from pipelex.graph.reactflow.viewspec import LayoutSpec, ViewEdge, ViewIndex, ViewNode, ViewSpec
-from pipelex.tools.misc.package_utils import get_package_version
-
-
-def _map_node_kind_to_view_type(kind: NodeKind) -> str:
- """Map GraphSpec NodeKind to ReactFlow ViewNode type.
-
- Args:
- kind: The NodeKind from GraphSpec.
-
- Returns:
- ReactFlow node type string.
- """
- match kind:
- case NodeKind.OPERATOR:
- return "operator"
- case NodeKind.CONTROLLER:
- return "controller"
- case NodeKind.INPUT:
- return "io"
- case NodeKind.OUTPUT:
- return "io"
- case NodeKind.ARTIFACT:
- return "artifact"
- case NodeKind.ERROR:
- return "error"
- case NodeKind.PIPE_CALL:
- return "operator" # Treat pipe_call as operator for now
-
-
-def _map_edge_kind_to_view_type(kind: EdgeKind) -> str:
- """Map GraphSpec EdgeKind to ReactFlow ViewEdge type.
-
- Args:
- kind: The EdgeKind from GraphSpec.
-
- Returns:
- ReactFlow edge type string.
- """
- match kind:
- case EdgeKind.DATA:
- return "data"
- case EdgeKind.CONTROL:
- return "control"
- case EdgeKind.CONTAINS:
- return "contains"
- case EdgeKind.SELECTED_OUTCOME:
- return "control" # Treat selected_outcome as control for now
- case EdgeKind.BATCH_ITEM:
- return "batch_item"
- case EdgeKind.BATCH_AGGREGATE:
- return "batch_aggregate"
- case EdgeKind.PARALLEL_COMBINE:
- return "parallel_combine"
-
-
-def _build_node_label(node_spec: Any) -> str:
- """Build a display label for a node.
-
- Args:
- node_spec: The NodeSpec to build a label for.
-
- Returns:
- Display label string.
- """
- if node_spec.pipe_code:
- return str(node_spec.pipe_code)
- if node_spec.pipe_type:
- return str(node_spec.pipe_type)
- return str(node_spec.node_id)
-
-
-def _build_ui_classes(status: NodeStatus) -> list[str]:
- """Build UI classes based on node status.
-
- Args:
- status: The NodeStatus.
-
- Returns:
- List of CSS class names.
- """
- match status:
- case NodeStatus.SUCCEEDED:
- return ["ok", "succeeded"]
- case NodeStatus.FAILED:
- return ["failed", "error"]
- case NodeStatus.RUNNING:
- return ["running", "active"]
- case NodeStatus.SCHEDULED:
- return ["scheduled", "pending"]
- case NodeStatus.SKIPPED:
- return ["skipped"]
- case NodeStatus.CANCELED:
- return ["canceled"]
-
-
-def _build_ui_badges(timing: Any | None, metrics: dict[str, float] | None) -> list[str]:
- """Build UI badges from timing and metrics.
-
- Args:
- timing: Optional TimingSpec.
- metrics: Optional metrics dict.
-
- Returns:
- List of badge strings.
- """
- badges: list[str] = []
- if timing:
- badges.append(f"{timing.duration:.2f}s")
- if metrics:
- for key, value in metrics.items():
- if key == "llm_tokens":
- badges.append(f"{int(value)} tokens")
- elif key == "cost_usd":
- badges.append(f"${value:.4f}")
- return badges
-
-
-def _build_io_preview(node_io: Any) -> dict[str, Any]:
- """Build I/O preview for inspector from NodeIOSpec.
-
- Args:
- node_io: The NodeIOSpec to extract previews from.
-
- Returns:
- Dict with input and output previews.
- """
- io_preview: dict[str, Any] = {}
- if node_io.inputs:
- io_preview["inputs"] = [
- {
- "name": io.name,
- "concept": io.concept,
- "preview": io.preview,
- "size": io.size,
- "digest": io.digest,
- }
- for io in node_io.inputs
- ]
- if node_io.outputs:
- io_preview["outputs"] = [
- {
- "name": io.name,
- "concept": io.concept,
- "preview": io.preview,
- "size": io.size,
- "digest": io.digest,
- }
- for io in node_io.outputs
- ]
- return io_preview
-
-
-def _build_inspector_data(node_spec: Any) -> dict[str, Any]:
- """Build inspector data for a node.
-
- Args:
- node_spec: The NodeSpec to build inspector data for.
-
- Returns:
- Inspector data dict.
- """
- inspector: dict[str, Any] = {}
- if node_spec.pipe_code:
- inspector["pipe_code"] = node_spec.pipe_code
- if node_spec.pipe_type:
- inspector["pipe_type"] = node_spec.pipe_type
- if node_spec.timing:
- inspector["timing"] = {
- "started_at": node_spec.timing.started_at.isoformat(),
- "ended_at": node_spec.timing.ended_at.isoformat(),
- }
- if node_spec.node_io:
- inspector["io_preview"] = _build_io_preview(node_spec.node_io)
- if node_spec.error:
- inspector["error"] = {
- "error_type": node_spec.error.error_type,
- "message": node_spec.error.message,
- "stack": node_spec.error.stack,
- }
- if node_spec.tags:
- inspector["tags"] = node_spec.tags
- if node_spec.metrics:
- inspector["metrics"] = node_spec.metrics
- return inspector
-
-
-def graphspec_to_viewspec(
- graph: GraphSpec,
- analysis: GraphAnalysis,
- *,
- options: dict[str, Any] | None = None,
- layout: LayoutSpec | None = None,
-) -> ViewSpec:
- """Transform GraphSpec + GraphAnalysis into ViewSpec for ReactFlow.
-
- Args:
- graph: The canonical GraphSpec.
- analysis: Pre-computed GraphAnalysis.
- options: Optional view options (show_data_edges, collapse_controllers, redaction, etc.).
- layout: Optional layout configuration. If None, uses default LayoutSpec.
-
- Returns:
- ViewSpec ready for ReactFlow rendering.
- """
- if options is None:
- options = {}
- if layout is None:
- layout = LayoutSpec()
-
- # Build ViewNodes
- view_nodes: list[ViewNode] = []
- for node_spec in graph.nodes:
- # Determine parent_id from containment tree
- parent_id: str | None = None
- for parent_node_id, children in analysis.containment_tree.items():
- if node_spec.node_id in children:
- parent_id = parent_node_id
- break
-
- # Build UI classes and badges
- ui_classes = _build_ui_classes(node_spec.status)
- ui_badges = _build_ui_badges(node_spec.timing, node_spec.metrics)
- ui_data: dict[str, Any] = {"classes": ui_classes}
- if ui_badges:
- ui_data["badges"] = ui_badges
-
- # Build inspector data
- inspector_data = _build_inspector_data(node_spec)
-
- view_node = ViewNode(
- id=node_spec.node_id,
- label=_build_node_label(node_spec),
- kind=node_spec.kind,
- status=node_spec.status,
- type=_map_node_kind_to_view_type(node_spec.kind),
- parent_id=parent_id,
- extent="parent" if parent_id else None,
- ui=ui_data,
- inspector=inspector_data,
- )
- view_nodes.append(view_node)
-
- # Build ViewEdges
- view_edges: list[ViewEdge] = []
- show_data_edges = options.get("show_data_edges", True)
- collapse_controllers = options.get("collapse_controllers", False)
-
- for edge_spec in graph.edges:
- # Skip CONTAINS edges if we're using parent_id for containment
- if edge_spec.kind == EdgeKind.CONTAINS:
- continue
-
- # Skip DATA edges if show_data_edges is False
- if edge_spec.kind == EdgeKind.DATA and not show_data_edges:
- continue
-
- # Skip edges to/from controllers if collapsing
- if collapse_controllers:
- source_node = analysis.nodes_by_id.get(edge_spec.source)
- target_node = analysis.nodes_by_id.get(edge_spec.target)
- if (source_node and analysis.is_controller(source_node.node_id)) or (target_node and analysis.is_controller(target_node.node_id)):
- continue
-
- view_edge = ViewEdge(
- id=edge_spec.edge_id,
- source=edge_spec.source,
- target=edge_spec.target,
- kind=edge_spec.kind,
- label=edge_spec.label,
- type=_map_edge_kind_to_view_type(edge_spec.kind),
- animated=edge_spec.kind == EdgeKind.DATA,
- hidden=False,
- )
- view_edges.append(view_edge)
-
- # Build ViewIndex (optional but recommended for performance)
- edges_by_node: dict[str, list[str]] = defaultdict(list)
- for edge_spec in graph.edges:
- edges_by_node[edge_spec.source].append(edge_spec.edge_id)
- edges_by_node[edge_spec.target].append(edge_spec.edge_id)
-
- search_index: dict[str, list[str]] = defaultdict(list)
- for node_spec in graph.nodes:
- if node_spec.pipe_code:
- search_index[f"pipe_code:{node_spec.pipe_code}"].append(node_spec.node_id)
- if node_spec.pipe_type:
- search_index[f"pipe_type:{node_spec.pipe_type}"].append(node_spec.node_id)
- if node_spec.status:
- search_index[f"status:{node_spec.status}"].append(node_spec.node_id)
-
- view_index = ViewIndex(
- edges_by_node=dict(edges_by_node),
- children_by_parent=analysis.containment_tree,
- search=dict(search_index),
- )
-
- # Build source metadata
- source_metadata: dict[str, Any] = {
- "producer": f"pipelex {get_package_version()}",
- }
- if graph.pipeline_ref.domain:
- source_metadata["domain"] = graph.pipeline_ref.domain
- if graph.pipeline_ref.main_pipe:
- source_metadata["main_pipe"] = graph.pipeline_ref.main_pipe
-
- # Create ViewSpec
- return ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id=graph.graph_id,
- source=source_metadata,
- engine="reactflow",
- options=options,
- layout=layout,
- nodes=view_nodes,
- edges=view_edges,
- index=view_index,
- )
diff --git a/pipelex/kit/configs/pipelex.toml b/pipelex/kit/configs/pipelex.toml
index 2f0f7c027..e46531f62 100644
--- a/pipelex/kit/configs/pipelex.toml
+++ b/pipelex/kit/configs/pipelex.toml
@@ -48,7 +48,6 @@ error_stack_traces = true
graphspec_json = true
mermaidflow_mmd = true
mermaidflow_html = true
-reactflow_viewspec = true
reactflow_html = true
[pipelex.pipeline_execution_config.graph_config.reactflow_config]
diff --git a/pipelex/pipelex.toml b/pipelex/pipelex.toml
index 5fd13cb23..4237c0971 100644
--- a/pipelex/pipelex.toml
+++ b/pipelex/pipelex.toml
@@ -344,7 +344,6 @@ error_stack_traces = true
graphspec_json = true
mermaidflow_mmd = true
mermaidflow_html = true
-reactflow_viewspec = true
reactflow_html = true
[pipelex.pipeline_execution_config.graph_config.mermaid_config]
diff --git a/pyproject.toml b/pyproject.toml
index 04e3c365d..4eef47836 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "pipelex"
-version = "0.20.12"
+version = "0.20.13"
description = "Execute composable AI methods declared in the MTHDS open standard"
authors = [{ name = "Evotis S.A.S.", email = "[email protected]" }]
maintainers = [{ name = "Pipelex staff", email = "[email protected]" }]
diff --git a/tests/e2e/pipelex/graph/test_graph_renderers_from_json.py b/tests/e2e/pipelex/graph/test_graph_renderers_from_json.py
index 461aad9fe..011a9802e 100644
--- a/tests/e2e/pipelex/graph/test_graph_renderers_from_json.py
+++ b/tests/e2e/pipelex/graph/test_graph_renderers_from_json.py
@@ -10,7 +10,6 @@ import pytest
from pipelex import log, pretty_print
from pipelex.config import get_config
-from pipelex.graph.graph_analysis import GraphAnalysis
from pipelex.graph.graphspec import GraphSpec
from pipelex.graph.mermaidflow.mermaid_html import (
render_mermaid_html_async,
@@ -19,7 +18,6 @@ from pipelex.graph.mermaidflow.mermaid_html import (
from pipelex.graph.mermaidflow.mermaidflow_factory import MermaidflowFactory
from pipelex.graph.mermaidflow.stuff_collector import collect_stuff_data_html, collect_stuff_data_text
from pipelex.graph.reactflow.reactflow_html import generate_reactflow_html_async
-from pipelex.graph.reactflow.viewspec_transformer import graphspec_to_viewspec
from pipelex.tools.misc.chart_utils import FlowchartDirection
from pipelex.tools.misc.file_utils import get_incremental_directory_path, load_text_from_path
from tests.conftest import TEST_OUTPUTS_DIR
@@ -62,7 +60,6 @@ class TestGraphRenderersFromJson:
- mermaidflow.mmd + mermaidflow.html (Mermaid mermaidflow view)
- reactflow.html (ReactFlow interactive view)
- - viewspec.json (ViewSpec used by ReactFlow)
All outputs are saved in the same folder for easy comparison.
"""
@@ -105,14 +102,6 @@ class TestGraphRenderersFromJson:
# ==================== REACTFLOW OUTPUTS ====================
- # Create ViewSpec and generate ReactFlow HTML
- analysis = GraphAnalysis.from_graphspec(graph_spec)
- viewspec = graphspec_to_viewspec(graph_spec, analysis)
-
- # Save ViewSpec JSON
- viewspec_path = output_dir / "viewspec.json"
- viewspec_path.write_text(viewspec.model_dump_json(indent=2), encoding="utf-8")
-
# Collect stuff data in alternate formats if configured
rf_stuff_data_text: dict[str, str] | None = None
rf_stuff_data_html: dict[str, str] | None = None
@@ -121,11 +110,10 @@ class TestGraphRenderersFromJson:
if graph_config.data_inclusion.stuff_html_content:
rf_stuff_data_html = collect_stuff_data_html(graph_spec)
- # Generate ReactFlow HTML (with embedded GraphSpec for full data)
+ # Generate ReactFlow HTML directly from GraphSpec
reactflow_html = await generate_reactflow_html_async(
- viewspec,
+ graph_spec,
graph_config.reactflow_config,
- graphspec=graph_spec,
stuff_data_text=rf_stuff_data_text,
stuff_data_html=rf_stuff_data_html,
title=f"ReactFlow: {topic}",
@@ -139,7 +127,6 @@ class TestGraphRenderersFromJson:
expected_files = [
"mermaidflow.mmd",
"mermaidflow.html",
- "viewspec.json",
"reactflow.html",
]
for filename in expected_files:
@@ -160,10 +147,10 @@ class TestGraphRenderersFromJson:
# Summary
log.info(
- f"✅ All renderings generated for '{topic}':\n"
- f" 📁 Output: {output_dir}\n"
- f" 📊 Mermaid:\n"
+ f"All renderings generated for '{topic}':\n"
+ f" Output: {output_dir}\n"
+ f" Mermaid:\n"
f" - mermaidflow.html\n"
- f" 🔷 ReactFlow:\n"
+ f" ReactFlow:\n"
f" - reactflow.html"
)
diff --git a/tests/e2e/pipelex/graph/test_graph_with_full_data.py b/tests/e2e/pipelex/graph/test_graph_with_full_data.py
index cbaf18312..98c30576b 100644
--- a/tests/e2e/pipelex/graph/test_graph_with_full_data.py
+++ b/tests/e2e/pipelex/graph/test_graph_with_full_data.py
@@ -12,7 +12,6 @@ import pytest
from pipelex import log
from pipelex.config import get_config
from pipelex.core.stuffs.document_content import DocumentContent
-from pipelex.graph.graph_analysis import GraphAnalysis
from pipelex.graph.graphspec import GraphSpec
from pipelex.graph.mermaidflow.mermaid_html import (
render_mermaid_html_async,
@@ -20,7 +19,6 @@ from pipelex.graph.mermaidflow.mermaid_html import (
)
from pipelex.graph.mermaidflow.mermaidflow_factory import MermaidflowFactory
from pipelex.graph.reactflow.reactflow_html import generate_reactflow_html_async
-from pipelex.graph.reactflow.viewspec_transformer import graphspec_to_viewspec
from pipelex.pipe_run.pipe_run_mode import PipeRunMode
from pipelex.pipeline.runner import PipelexRunner
from pipelex.tools.misc.chart_utils import FlowchartDirection
@@ -259,10 +257,8 @@ class TestGraphWithFullData:
)
# Generate ReactFlow HTML
- analysis = GraphAnalysis.from_graphspec(graph_spec)
- viewspec = graphspec_to_viewspec(graph_spec, analysis)
rf_config = get_config().pipelex.pipeline_execution_config.graph_config.reactflow_config
- reactflow_html = await generate_reactflow_html_async(viewspec, rf_config, graphspec=graph_spec, title="Graph: cv_job_matcher")
+ reactflow_html = await generate_reactflow_html_async(graph_spec, rf_config, title="Graph: cv_job_matcher")
reactflow_path = output_dir / "reactflow.html"
reactflow_path.write_text(reactflow_html, encoding="utf-8")
log.info(f"Saved ReactFlow HTML to: {reactflow_path}")
@@ -271,11 +267,10 @@ class TestGraphWithFullData:
assert reactflow_path.exists()
assert reactflow_path.stat().st_size > 0
html_content = reactflow_path.read_text(encoding="utf-8")
- assert '<script type="application/json" id="pipelex-viewspec">' in html_content
assert '<script type="application/json" id="pipelex-graphspec">' in html_content
assert "ReactFlow" in html_content
assert "getLayoutedElements" in html_content
- assert f'"{graph_spec.graph_id}"' in html_content # ViewSpec should contain graph_id
+ assert f'"{graph_spec.graph_id}"' in html_content # GraphSpec should contain graph_id
# Final summary
log.info(
diff --git a/tests/e2e/pipelex/graph/test_reactflow_from_json.py b/tests/e2e/pipelex/graph/test_reactflow_from_json.py
index 52da8f7ab..ebe6c693c 100644
--- a/tests/e2e/pipelex/graph/test_reactflow_from_json.py
+++ b/tests/e2e/pipelex/graph/test_reactflow_from_json.py
@@ -10,10 +10,8 @@ import pytest
from pipelex import log
from pipelex.config import get_config
-from pipelex.graph.graph_analysis import GraphAnalysis
from pipelex.graph.graphspec import GraphSpec
from pipelex.graph.reactflow.reactflow_html import generate_reactflow_html_async
-from pipelex.graph.reactflow.viewspec_transformer import graphspec_to_viewspec
from pipelex.tools.misc.file_utils import get_incremental_directory_path, load_text_from_path
from tests.conftest import TEST_OUTPUTS_DIR
from tests.e2e.pipelex.graph.test_data import GraphTestData
@@ -41,10 +39,9 @@ class TestReactFlowFromJson:
This test:
1. Loads a GraphSpec from JSON
- 2. Creates ViewSpec via transformer
- 3. Generates ReactFlow HTML
- 4. Saves outputs to TEST_OUTPUTS_DIR
- 5. Verifies the HTML structure and embedded data
+ 2. Generates ReactFlow HTML directly from GraphSpec
+ 3. Saves outputs to TEST_OUTPUTS_DIR
+ 4. Verifies the HTML structure and embedded data
"""
# Load graph from JSON
json_path = Path(graph_json_path)
@@ -58,50 +55,30 @@ class TestReactFlowFromJson:
assert len(graph_spec.nodes) > 0
assert len(graph_spec.edges) > 0
- # Create ViewSpec
- analysis = GraphAnalysis.from_graphspec(graph_spec)
- viewspec = graphspec_to_viewspec(graph_spec, analysis)
-
- # Verify ViewSpec structure
- assert viewspec.graph_id == graph_spec.graph_id
- assert len(viewspec.nodes) == len(graph_spec.nodes)
- assert viewspec.index is not None
-
- # Generate ReactFlow HTML
+ # Generate ReactFlow HTML directly from GraphSpec
rf_config = get_config().pipelex.pipeline_execution_config.graph_config.reactflow_config
- reactflow_html = await generate_reactflow_html_async(viewspec, rf_config, graphspec=graph_spec, title=f"Graph: {topic}")
+ reactflow_html = await generate_reactflow_html_async(graph_spec, rf_config, title=f"Graph: {topic}")
# Save outputs to TEST_OUTPUTS_DIR
output_dir = _get_next_output_folder()
log.info(f"Saving ReactFlow outputs to: {output_dir}")
- # Save ViewSpec JSON
- viewspec_path = output_dir / "viewspec.json"
- viewspec_path.write_text(viewspec.model_dump_json(indent=2))
- log.info(f"Saved viewspec.json: {viewspec_path}")
-
# Save ReactFlow HTML
reactflow_path = output_dir / "reactflow.html"
reactflow_path.write_text(reactflow_html)
log.info(f"Saved reactflow.html: {reactflow_path}")
# Verify files were saved
- assert viewspec_path.exists()
assert reactflow_path.exists()
assert reactflow_path.stat().st_size > 1000
# Verify HTML structure
assert reactflow_html.startswith("<!DOCTYPE html>")
- assert '<script type="application/json" id="pipelex-viewspec">' in reactflow_html
assert '<script type="application/json" id="pipelex-graphspec">' in reactflow_html
assert "ReactFlow" in reactflow_html
assert "getLayoutedElements" in reactflow_html
assert f'"{graph_spec.graph_id}"' in reactflow_html
- # Verify ViewSpec JSON is embedded
- assert viewspec.nodes[0].id in reactflow_html
- assert viewspec.nodes[0].label in reactflow_html
-
# Verify GraphSpec JSON is embedded
assert graph_spec.nodes[0].node_id in reactflow_html
@@ -110,70 +87,20 @@ class TestReactFlowFromJson:
("topic", "graph_json_path"),
GraphTestData.GRAPH_JSON_TEST_CASES,
)
- async def test_reactflow_html_without_graphspec(self, topic: str, graph_json_path: str) -> None:
- """Test generating ReactFlow HTML without embedding GraphSpec."""
+ async def test_reactflow_html_graphspec_structure(self, topic: str, graph_json_path: str) -> None:
+ """Test that GraphSpec is correctly embedded in HTML."""
_ = topic # Used for test identification
# Load graph from JSON
json_str = load_text_from_path(graph_json_path)
graph_spec = GraphSpec.model_validate_json(json_str)
- # Create ViewSpec
- analysis = GraphAnalysis.from_graphspec(graph_spec)
- viewspec = graphspec_to_viewspec(graph_spec, analysis)
-
- # Generate ReactFlow HTML without GraphSpec
+ # Generate ReactFlow HTML
rf_config = get_config().pipelex.pipeline_execution_config.graph_config.reactflow_config
- reactflow_html = await generate_reactflow_html_async(viewspec, rf_config, graphspec=None, title="Test Graph")
-
- # Verify ViewSpec is embedded
- assert '<script type="application/json" id="pipelex-viewspec">' in reactflow_html
-
- # Verify GraphSpec is NOT embedded
- assert '<script type="application/json" id="pipelex-graphspec">' not in reactflow_html
-
- @pytest.mark.asyncio(loop_scope="class")
- @pytest.mark.parametrize(
- ("topic", "graph_json_path"),
- GraphTestData.GRAPH_JSON_TEST_CASES,
- )
- async def test_reactflow_html_viewspec_structure(self, topic: str, graph_json_path: str) -> None:
- """Test that ViewSpec contains all expected data from the graph."""
- _ = topic # Used for test identification
+ reactflow_html = await generate_reactflow_html_async(graph_spec, rf_config, title="Test Graph")
- # Load graph from JSON
- json_str = load_text_from_path(graph_json_path)
- graph_spec = GraphSpec.model_validate_json(json_str)
+ # Verify GraphSpec is embedded
+ assert '<script type="application/json" id="pipelex-graphspec">' in reactflow_html
- # Create ViewSpec
- analysis = GraphAnalysis.from_graphspec(graph_spec)
- viewspec = graphspec_to_viewspec(graph_spec, analysis)
-
- # Verify node mapping
- assert len(viewspec.nodes) == len(graph_spec.nodes)
- for view_node in viewspec.nodes:
- # Find corresponding GraphSpec node
- graph_node = graph_spec.nodes[0]
- for node in graph_spec.nodes:
- if node.node_id == view_node.id:
- graph_node = node
- break
-
- # Verify basic mapping
- assert view_node.id == graph_node.node_id
- assert view_node.kind == graph_node.kind
- assert view_node.status == graph_node.status
-
- # Verify inspector data
- if graph_node.pipe_code:
- assert view_node.inspector["pipe_code"] == graph_node.pipe_code
-
- # Verify edge mapping (excluding CONTAINS edges)
- contains_edges = [edge for edge in graph_spec.edges if edge.kind.value == "contains"]
- expected_edge_count = len(graph_spec.edges) - len(contains_edges)
- assert len(viewspec.edges) == expected_edge_count
-
- # Verify index
- assert viewspec.index is not None
- assert len(viewspec.index.edges_by_node) > 0
- assert len(viewspec.index.children_by_parent) > 0
+ # ViewSpec should NOT be present
+ assert 'id="pipelex-viewspec"' not in reactflow_html
diff --git a/tests/unit/pipelex/graph/test_reactflow_html.py b/tests/unit/pipelex/graph/test_reactflow_html.py
index 6cecf4605..21eacd811 100644
--- a/tests/unit/pipelex/graph/test_reactflow_html.py
+++ b/tests/unit/pipelex/graph/test_reactflow_html.py
@@ -8,13 +8,10 @@ import pytest
from pipelex.config import get_config
from pipelex.core.stuffs.stuff_template_set import STUFF_TEMPLATE_SET
from pipelex.graph.csp import CSP_NONCE_SENTINEL
-from pipelex.graph.graph_analysis import GraphAnalysis
from pipelex.graph.graphspec import GraphSpec, NodeKind, NodeSpec, NodeStatus, PipelineRef
from pipelex.graph.reactflow.reactflow_config import ReactFlowRenderingConfig
from pipelex.graph.reactflow.reactflow_html import generate_reactflow_html
from pipelex.graph.reactflow.template_set import REACTFLOW_TEMPLATE_SET
-from pipelex.graph.reactflow.viewspec import ViewSpec
-from pipelex.graph.reactflow.viewspec_transformer import graphspec_to_viewspec
from pipelex.tools.jinja2.jinja2_template_loader import TemplateLoader
from pipelex.tools.jinja2.jinja2_template_registry import TemplateRegistry
@@ -49,100 +46,73 @@ class TestReactFlowHtml:
"""Get the default ReactFlow config for testing."""
return get_config().pipelex.pipeline_execution_config.graph_config.reactflow_config
- def test_generates_html_with_embedded_viewspec(self, rf_config: ReactFlowRenderingConfig) -> None:
- """Test that HTML contains embedded ViewSpec as JSON."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="test_graph",
- )
- html = generate_reactflow_html(viewspec, rf_config)
-
- assert "<!DOCTYPE html>" in html
- assert '<script type="application/json" id="pipelex-viewspec">' in html
- assert "test_graph" in html
- assert "const viewspec = JSON.parse" in html
-
- def test_embeds_graphspec_when_provided(self, rf_config: ReactFlowRenderingConfig) -> None:
- """Test that GraphSpec is embedded when provided."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="test_graph",
- )
- graphspec = GraphSpec(
+ @pytest.fixture
+ def empty_graphspec(self) -> GraphSpec:
+ """Create an empty GraphSpec for testing."""
+ return GraphSpec(
graph_id="test_graph",
created_at=datetime.now(timezone.utc),
pipeline_ref=PipelineRef(),
nodes=[],
edges=[],
)
- html = generate_reactflow_html(viewspec, rf_config, graphspec=graphspec)
+ def test_generates_html_with_embedded_graphspec(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
+ """Test that HTML contains embedded GraphSpec as JSON."""
+ html = generate_reactflow_html(empty_graphspec, rf_config)
+
+ assert "<!DOCTYPE html>" in html
assert '<script type="application/json" id="pipelex-graphspec">' in html
assert "test_graph" in html
- def test_does_not_embed_graphspec_when_not_provided(self, rf_config: ReactFlowRenderingConfig) -> None:
- """Test that GraphSpec script tag is not present when not provided."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="test_graph",
- )
- html = generate_reactflow_html(viewspec, rf_config)
+ def test_embeds_graphspec_always(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
+ """Test that GraphSpec is always embedded."""
+ html = generate_reactflow_html(empty_graphspec, rf_config)
- # Should not have graphspec script tag
- assert '<script type="application/json" id="pipelex-graphspec">' not in html
+ assert '<script type="application/json" id="pipelex-graphspec">' in html
+ assert "test_graph" in html
+
+ def test_no_viewspec_in_html(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
+ """Test that ViewSpec script tag is no longer present."""
+ html = generate_reactflow_html(empty_graphspec, rf_config)
+
+ assert 'id="pipelex-viewspec"' not in html
- def test_cdn_mode_includes_cdn_scripts(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_cdn_mode_includes_cdn_scripts(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Test that CDN mode includes CDN script tags."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="test_graph",
- )
cdn_config = rf_config.model_copy(update={"is_use_cdn": True})
- html = generate_reactflow_html(viewspec, cdn_config)
+ html = generate_reactflow_html(empty_graphspec, cdn_config)
assert "unpkg.com/react@18" in html
assert "unpkg.com/react-dom@18" in html
assert "unpkg.com/reactflow@11" in html
assert "unpkg.com/[email protected]" in html
- def test_custom_title_in_html(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_custom_title_in_html(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Test that custom title appears in HTML."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="test_graph",
- )
- html = generate_reactflow_html(viewspec, rf_config, title="My Custom Graph")
+ html = generate_reactflow_html(empty_graphspec, rf_config, title="My Custom Graph")
assert "<title>My Custom Graph</title>" in html
- def test_includes_reactflow_viewer_code(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_includes_reactflow_viewer_code(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Test that HTML includes ReactFlow viewer JavaScript."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="test_graph",
- )
- html = generate_reactflow_html(viewspec, rf_config)
+ html = generate_reactflow_html(empty_graphspec, rf_config)
assert "ReactFlow" in html
assert "getLayoutedElements" in html
assert "onNodeClick" in html
assert "inspector" in html
- def test_includes_inspector_panel(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_includes_inspector_panel(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Test that HTML includes inspector panel markup."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="test_graph",
- )
- html = generate_reactflow_html(viewspec, rf_config)
+ html = generate_reactflow_html(empty_graphspec, rf_config)
assert 'id="inspector"' in html
assert "inspector-panel" in html
assert "closeInspector" in html
- def test_full_viewspec_serialized(self, rf_config: ReactFlowRenderingConfig) -> None:
- """Test that full ViewSpec with nodes and edges is serialized."""
- # Create a simple graph and convert to ViewSpec
+ def test_full_graphspec_serialized(self, rf_config: ReactFlowRenderingConfig) -> None:
+ """Test that full GraphSpec with nodes is serialized."""
node = NodeSpec(
node_id="node_1",
kind=NodeKind.OPERATOR,
@@ -156,22 +126,16 @@ class TestReactFlowHtml:
nodes=[node],
edges=[],
)
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
- html = generate_reactflow_html(viewspec, rf_config)
+ html = generate_reactflow_html(graph, rf_config)
- # ViewSpec should be embedded with node data
+ # GraphSpec should be embedded with node data
assert "node_1" in html
assert "test_pipe" in html
- def test_html_is_valid_structure(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_html_is_valid_structure(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Test that generated HTML has valid structure."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="test_graph",
- )
- html = generate_reactflow_html(viewspec, rf_config)
+ html = generate_reactflow_html(empty_graphspec, rf_config)
# Check for essential HTML structure
assert html.startswith("<!DOCTYPE html>")
@@ -181,39 +145,32 @@ class TestReactFlowHtml:
assert "</html>" in html
assert '<div id="root">' in html
- def test_dagre_layout_included(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_dagre_layout_included(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Test that Dagre layout function is included."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="test_graph",
- )
- html = generate_reactflow_html(viewspec, rf_config)
+ html = generate_reactflow_html(empty_graphspec, rf_config)
assert "dagre" in html
assert "getLayoutedElements" in html
assert "rankdir" in html
- def test_html_contains_csp_nonce_on_inline_script(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_html_contains_csp_nonce_on_inline_script(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Verify the inline script tag has the CSP nonce sentinel."""
- viewspec = ViewSpec(created_at=datetime.now(timezone.utc), graph_id="test_graph")
- html = generate_reactflow_html(viewspec, rf_config)
+ html = generate_reactflow_html(empty_graphspec, rf_config)
# The main inline <script nonce="..."> (not type="application/json")
pattern = rf'<script nonce="{re.escape(CSP_NONCE_SENTINEL)}">'
assert re.search(pattern, html), "Inline <script> should have the CSP nonce sentinel"
- def test_html_contains_csp_nonce_on_inline_style(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_html_contains_csp_nonce_on_inline_style(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Verify the inline style tag has the CSP nonce sentinel."""
- viewspec = ViewSpec(created_at=datetime.now(timezone.utc), graph_id="test_graph")
- html = generate_reactflow_html(viewspec, rf_config)
+ html = generate_reactflow_html(empty_graphspec, rf_config)
assert f'<style nonce="{CSP_NONCE_SENTINEL}">' in html
- def test_html_contains_csp_nonce_on_cdn_scripts(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_html_contains_csp_nonce_on_cdn_scripts(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Verify CDN script tags have the CSP nonce sentinel."""
- viewspec = ViewSpec(created_at=datetime.now(timezone.utc), graph_id="test_graph")
cdn_config = rf_config.model_copy(update={"is_use_cdn": True})
- html = generate_reactflow_html(viewspec, cdn_config)
+ html = generate_reactflow_html(empty_graphspec, cdn_config)
# All CDN <script src="..."> tags should have nonce
cdn_scripts = re.findall(r'<script [^>]*src="https?://[^"]*"[^>]*>', html)
@@ -221,26 +178,17 @@ class TestReactFlowHtml:
for tag in cdn_scripts:
assert f'nonce="{CSP_NONCE_SENTINEL}"' in tag, f"CDN script missing nonce: {tag}"
- def test_json_data_scripts_have_no_nonce(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_json_data_scripts_have_no_nonce(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Verify application/json script tags do NOT have a nonce attribute."""
- viewspec = ViewSpec(created_at=datetime.now(timezone.utc), graph_id="test_graph")
- graphspec = GraphSpec(
- graph_id="test_graph",
- created_at=datetime.now(timezone.utc),
- pipeline_ref=PipelineRef(),
- nodes=[],
- edges=[],
- )
- html = generate_reactflow_html(viewspec, rf_config, graphspec=graphspec)
+ html = generate_reactflow_html(empty_graphspec, rf_config)
json_scripts = re.findall(r'<script type="application/json"[^>]*>', html)
assert len(json_scripts) >= 1, "Expected at least 1 JSON data script tag"
for tag in json_scripts:
assert "nonce" not in tag, f"JSON data script should not have nonce: {tag}"
- def test_html_has_no_csp_meta_tag(self, rf_config: ReactFlowRenderingConfig) -> None:
+ def test_html_has_no_csp_meta_tag(self, rf_config: ReactFlowRenderingConfig, empty_graphspec: GraphSpec) -> None:
"""Verify no CSP meta tag is present (standalone HTML should be CSP-free)."""
- viewspec = ViewSpec(created_at=datetime.now(timezone.utc), graph_id="test_graph")
- html = generate_reactflow_html(viewspec, rf_config)
+ html = generate_reactflow_html(empty_graphspec, rf_config)
assert "Content-Security-Policy" not in html
diff --git a/tests/unit/pipelex/graph/test_viewspec.py b/tests/unit/pipelex/graph/test_viewspec.py
deleted file mode 100644
index 1f0c0a2fb..000000000
--- a/tests/unit/pipelex/graph/test_viewspec.py
+++ /dev/null
@@ -1,284 +0,0 @@
-"""Unit tests for the ViewSpec models."""
-
-from datetime import datetime, timezone
-
-from pipelex.graph.reactflow.viewspec import (
- CURRENT_VIEWSPEC_VERSION,
- LayoutSpec,
- PayloadSpec,
- ViewEdge,
- ViewIndex,
- ViewNode,
- ViewSpec,
-)
-from pipelex.tools.misc.chart_utils import FlowchartDirection
-
-
-class TestViewNode:
- """Tests for the ViewNode model."""
-
- def test_minimal_view_node(self) -> None:
- """Test creating a minimal ViewNode with required fields."""
- node = ViewNode(id="node_1", label="Test Node", kind="operator")
- assert node.id == "node_1"
- assert node.label == "Test Node"
- assert node.kind == "operator"
- assert node.status is None
- assert node.type == "default"
- assert node.parent_id is None
- assert node.position is None
- assert node.size is None
- assert node.ui == {}
- assert node.inspector == {}
- assert node.handles is None
-
- def test_view_node_with_all_fields(self) -> None:
- """Test creating a ViewNode with all optional fields."""
- node = ViewNode(
- id="node_1",
- label="Test Node",
- kind="operator",
- status="succeeded",
- type="operator",
- parent_id="ctrl_1",
- extent="parent",
- position={"x": 100.0, "y": 200.0},
- size={"width": 150.0, "height": 50.0},
- ui={"badges": ["132ms"], "classes": ["ok"], "icon": "llm"},
- inspector={
- "pipe_code": "extract_text",
- "pipe_type": "PipeLLM",
- "timing": {"started_at": "2024-01-15T10:30:00+00:00", "ended_at": "2024-01-15T10:30:00.132000+00:00"},
- },
- handles=[{"id": "out.text", "type": "source", "position": "Right"}],
- )
- assert node.id == "node_1"
- assert node.status == "succeeded"
- assert node.type == "operator"
- assert node.parent_id == "ctrl_1"
- assert node.extent == "parent"
- assert node.position == {"x": 100.0, "y": 200.0}
- assert node.size == {"width": 150.0, "height": 50.0}
- assert node.ui["badges"] == ["132ms"]
- assert node.inspector["pipe_code"] == "extract_text"
- assert node.handles is not None
- assert len(node.handles) == 1
-
- def test_view_node_defaults(self) -> None:
- """Test that ViewNode has correct defaults."""
- node = ViewNode(id="node_1", label="Test", kind="operator")
- assert node.type == "default"
- assert node.ui == {}
- assert node.inspector == {}
-
-
-class TestViewEdge:
- """Tests for the ViewEdge model."""
-
- def test_minimal_view_edge(self) -> None:
- """Test creating a minimal ViewEdge with required fields."""
- edge = ViewEdge(id="edge_1", source="node_1", target="node_2", kind="control")
- assert edge.id == "edge_1"
- assert edge.source == "node_1"
- assert edge.target == "node_2"
- assert edge.kind == "control"
- assert edge.label is None
- assert edge.type == "default"
- assert edge.animated is None
- assert edge.hidden is False
- assert edge.source_handle is None
- assert edge.target_handle is None
- assert edge.ui == {}
-
- def test_view_edge_with_all_fields(self) -> None:
- """Test creating a ViewEdge with all optional fields."""
- edge = ViewEdge(
- id="edge_1",
- source="node_1",
- target="node_2",
- kind="data",
- label="output_data",
- type="data",
- animated=True,
- hidden=False,
- source_handle="out.data",
- target_handle="in.data",
- ui={"classes": ["dashed"], "markerEnd": "arrow"},
- )
- assert edge.label == "output_data"
- assert edge.type == "data"
- assert edge.animated is True
- assert edge.source_handle == "out.data"
- assert edge.target_handle == "in.data"
- assert edge.ui["classes"] == ["dashed"]
-
-
-class TestLayoutSpec:
- """Tests for the LayoutSpec model."""
-
- def test_default_layout_spec(self) -> None:
- """Test that LayoutSpec has correct defaults."""
- layout = LayoutSpec()
- assert layout.engine == "dagre"
- assert layout.direction == FlowchartDirection.TOP_DOWN
- assert layout.nodesep == 50
- assert layout.ranksep == 80
- assert layout.align is None
- assert layout.allow_manual_positions is True
-
- def test_custom_layout_spec(self) -> None:
- """Test creating a LayoutSpec with custom values."""
- layout = LayoutSpec(
- engine="dagre",
- direction=FlowchartDirection.LEFT_TO_RIGHT,
- nodesep=100,
- ranksep=150,
- align="UL",
- allow_manual_positions=False,
- )
- assert layout.direction == FlowchartDirection.LEFT_TO_RIGHT
- assert layout.nodesep == 100
- assert layout.ranksep == 150
- assert layout.align == "UL"
- assert layout.allow_manual_positions is False
-
-
-class TestViewIndex:
- """Tests for the ViewIndex model."""
-
- def test_empty_view_index(self) -> None:
- """Test creating an empty ViewIndex."""
- index = ViewIndex()
- assert index.edges_by_node == {}
- assert index.children_by_parent == {}
- assert index.search == {}
-
- def test_view_index_with_data(self) -> None:
- """Test creating a ViewIndex with data."""
- index = ViewIndex(
- edges_by_node={"node_1": ["edge_1", "edge_2"]},
- children_by_parent={"ctrl_1": ["node_1", "node_2"]},
- search={"pipe_code:extract_text": ["node_1"], "status:failed": ["node_2"]},
- )
- assert index.edges_by_node["node_1"] == ["edge_1", "edge_2"]
- assert index.children_by_parent["ctrl_1"] == ["node_1", "node_2"]
- assert index.search["pipe_code:extract_text"] == ["node_1"]
-
-
-class TestPayloadSpec:
- """Tests for the PayloadSpec model."""
-
- def test_default_payload_spec(self) -> None:
- """Test that PayloadSpec has correct defaults."""
- payload = PayloadSpec()
- assert payload.mode == "inline"
- assert payload.base_path is None
- assert payload.by_digest == {}
-
- def test_external_payload_spec(self) -> None:
- """Test creating an external PayloadSpec."""
- payload = PayloadSpec(
- mode="external",
- base_path="/data/payloads",
- by_digest={"digest_001": "payload_001.json", "digest_002": "payload_002.json"},
- )
- assert payload.mode == "external"
- assert payload.base_path == "/data/payloads"
- assert payload.by_digest["digest_001"] == "payload_001.json"
-
-
-class TestViewSpec:
- """Tests for the ViewSpec model."""
-
- def test_minimal_view_spec(self) -> None:
- """Test creating a minimal ViewSpec with required fields."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="graph_001",
- )
- assert viewspec.schema_version == CURRENT_VIEWSPEC_VERSION
- assert viewspec.graph_id == "graph_001"
- assert viewspec.engine == "reactflow"
- assert viewspec.source == {}
- assert viewspec.options == {}
- assert isinstance(viewspec.layout, LayoutSpec)
- assert viewspec.nodes == []
- assert viewspec.edges == []
- assert viewspec.index is None
- assert viewspec.payloads is None
-
- def test_view_spec_with_all_fields(self) -> None:
- """Test creating a ViewSpec with all fields."""
- node = ViewNode(id="node_1", label="Test Node", kind="operator")
- edge = ViewEdge(id="edge_1", source="node_1", target="node_2", kind="control")
- index = ViewIndex(edges_by_node={"node_1": ["edge_1"]})
- payload = PayloadSpec(mode="inline")
- layout = LayoutSpec(direction=FlowchartDirection.LEFT_TO_RIGHT)
-
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="graph_001",
- source={"graph_schema_version": "1.0", "producer": "pipelex 0.9.3"},
- options={"show_data_edges": True, "collapse_controllers": False},
- layout=layout,
- nodes=[node],
- edges=[edge],
- index=index,
- payloads=payload,
- )
-
- assert viewspec.graph_id == "graph_001"
- assert viewspec.source["producer"] == "pipelex 0.9.3"
- assert viewspec.options["show_data_edges"] is True
- assert viewspec.layout.direction == FlowchartDirection.LEFT_TO_RIGHT
- assert len(viewspec.nodes) == 1
- assert len(viewspec.edges) == 1
- assert viewspec.index is not None
- assert viewspec.index.edges_by_node["node_1"] == ["edge_1"]
- assert viewspec.payloads is not None
-
- def test_view_spec_serialization(self) -> None:
- """Test that ViewSpec can be serialized to JSON."""
- node = ViewNode(id="node_1", label="Test Node", kind="operator", position={"x": 100.0, "y": 200.0})
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="graph_001",
- nodes=[node],
- )
-
- # Serialize to dict (Pydantic handles JSON serialization)
- data = viewspec.model_dump()
- assert data["graph_id"] == "graph_001"
- assert len(data["nodes"]) == 1
- assert data["nodes"][0]["id"] == "node_1"
- assert data["nodes"][0]["position"] == {"x": 100.0, "y": 200.0}
-
- def test_view_spec_deserialization(self) -> None:
- """Test that ViewSpec can be deserialized from dict."""
- created_at = datetime.now(timezone.utc)
- data = {
- "schema_version": CURRENT_VIEWSPEC_VERSION,
- "created_at": created_at,
- "graph_id": "graph_001",
- "engine": "reactflow",
- "source": {},
- "options": {},
- "layout": {"engine": "dagre", "direction": "top_down"},
- "nodes": [{"id": "node_1", "label": "Test", "kind": "operator"}],
- "edges": [],
- }
-
- viewspec = ViewSpec.model_validate(data)
- assert viewspec.graph_id == "graph_001"
- assert len(viewspec.nodes) == 1
- assert viewspec.nodes[0].id == "node_1"
-
- def test_view_spec_default_layout(self) -> None:
- """Test that ViewSpec creates default LayoutSpec if not provided."""
- viewspec = ViewSpec(
- created_at=datetime.now(timezone.utc),
- graph_id="graph_001",
- )
- assert isinstance(viewspec.layout, LayoutSpec)
- assert viewspec.layout.engine == "dagre"
- assert viewspec.layout.direction == FlowchartDirection.TOP_DOWN
diff --git a/tests/unit/pipelex/graph/test_viewspec_transformer.py b/tests/unit/pipelex/graph/test_viewspec_transformer.py
deleted file mode 100644
index bd1543eb9..000000000
--- a/tests/unit/pipelex/graph/test_viewspec_transformer.py
+++ /dev/null
@@ -1,403 +0,0 @@
-"""Unit tests for the ViewSpec transformer."""
-
-from datetime import datetime, timezone
-from typing import Any, ClassVar
-
-from pipelex.graph.graph_analysis import GraphAnalysis
-from pipelex.graph.graphspec import (
- EdgeKind,
- EdgeSpec,
- ErrorSpec,
- GraphSpec,
- IOSpec,
- NodeIOSpec,
- NodeKind,
- NodeSpec,
- NodeStatus,
- PipelineRef,
- TimingSpec,
-)
-from pipelex.graph.reactflow.viewspec import LayoutSpec
-from pipelex.graph.reactflow.viewspec_transformer import graphspec_to_viewspec
-from pipelex.tools.misc.chart_utils import FlowchartDirection
-from pipelex.tools.misc.package_utils import get_package_version
-
-
-class TestViewSpecTransformer:
- """Tests for graphspec_to_viewspec function."""
-
- GRAPH_ID: ClassVar[str] = "transformer_test:001"
- CREATED_AT: ClassVar[datetime] = datetime(2024, 1, 15, 10, 30, 0, tzinfo=timezone.utc)
-
- def _make_graph(
- self,
- nodes: list[dict[str, Any]],
- edges: list[dict[str, Any]] | None = None,
- ) -> GraphSpec:
- """Helper to create a GraphSpec with nodes and edges."""
- node_specs: list[NodeSpec] = []
- for node_dict in nodes:
- node_specs.append(NodeSpec(**node_dict))
-
- edge_specs: list[EdgeSpec] = []
- if edges:
- for edge_dict in edges:
- edge_specs.append(EdgeSpec(**edge_dict))
-
- return GraphSpec(
- graph_id=self.GRAPH_ID,
- created_at=self.CREATED_AT,
- pipeline_ref=PipelineRef(),
- nodes=node_specs,
- edges=edge_specs,
- )
-
- def test_minimal_graph_to_viewspec(self) -> None:
- """Test transforming a minimal graph to ViewSpec."""
- node = {
- "node_id": "node_1",
- "kind": NodeKind.OPERATOR,
- "pipe_code": "test_pipe",
- "status": NodeStatus.SUCCEEDED,
- }
- graph = self._make_graph(nodes=[node])
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- assert viewspec.graph_id == self.GRAPH_ID
- assert viewspec.engine == "reactflow"
- assert len(viewspec.nodes) == 1
- assert viewspec.nodes[0].id == "node_1"
- assert viewspec.nodes[0].label == "test_pipe"
- assert viewspec.nodes[0].kind == NodeKind.OPERATOR
- assert viewspec.nodes[0].status == NodeStatus.SUCCEEDED
- assert viewspec.nodes[0].type == "operator"
- assert len(viewspec.edges) == 0
-
- def test_node_kind_mapping(self) -> None:
- """Test that NodeKind is correctly mapped to ViewNode.type."""
- nodes = [
- {"node_id": "op_1", "kind": NodeKind.OPERATOR, "status": NodeStatus.SUCCEEDED},
- {"node_id": "ctrl_1", "kind": NodeKind.CONTROLLER, "status": NodeStatus.SUCCEEDED},
- {"node_id": "input_1", "kind": NodeKind.INPUT, "status": NodeStatus.SUCCEEDED},
- {"node_id": "output_1", "kind": NodeKind.OUTPUT, "status": NodeStatus.SUCCEEDED},
- {"node_id": "artifact_1", "kind": NodeKind.ARTIFACT, "status": NodeStatus.SUCCEEDED},
- {"node_id": "error_1", "kind": NodeKind.ERROR, "status": NodeStatus.FAILED},
- ]
- graph = self._make_graph(nodes=nodes)
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- type_map = {node.id: node.type for node in viewspec.nodes}
- assert type_map["op_1"] == "operator"
- assert type_map["ctrl_1"] == "controller"
- assert type_map["input_1"] == "io"
- assert type_map["output_1"] == "io"
- assert type_map["artifact_1"] == "artifact"
- assert type_map["error_1"] == "error"
-
- def test_edge_kind_mapping(self) -> None:
- """Test that EdgeKind is correctly mapped to ViewEdge.type."""
- nodes = [
- {"node_id": "node_1", "kind": NodeKind.OPERATOR, "status": NodeStatus.SUCCEEDED},
- {"node_id": "node_2", "kind": NodeKind.OPERATOR, "status": NodeStatus.SUCCEEDED},
- {"node_id": "node_3", "kind": NodeKind.OPERATOR, "status": NodeStatus.SUCCEEDED},
- ]
- edges = [
- {"edge_id": "edge_1", "source": "node_1", "target": "node_2", "kind": EdgeKind.CONTROL},
- {"edge_id": "edge_2", "source": "node_2", "target": "node_3", "kind": EdgeKind.DATA},
- ]
- graph = self._make_graph(nodes=nodes, edges=edges)
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- type_map = {edge.id: edge.type for edge in viewspec.edges}
- assert type_map["edge_1"] == "control"
- assert type_map["edge_2"] == "data"
-
- # DATA edges should be animated
- data_edge = next(edge for edge in viewspec.edges if edge.id == "edge_2")
- assert data_edge.animated is True
-
- def test_containment_tree_parent_id(self) -> None:
- """Test that parent_id is set correctly from containment tree."""
- controller_node = {
- "node_id": "ctrl_1",
- "kind": NodeKind.CONTROLLER,
- "pipe_code": "main_sequence",
- "status": NodeStatus.SUCCEEDED,
- }
- child_node = {
- "node_id": "child_1",
- "kind": NodeKind.OPERATOR,
- "pipe_code": "step_a",
- "status": NodeStatus.SUCCEEDED,
- }
- contains_edge = {
- "edge_id": "edge_1",
- "source": "ctrl_1",
- "target": "child_1",
- "kind": EdgeKind.CONTAINS,
- }
- graph = self._make_graph(nodes=[controller_node, child_node], edges=[contains_edge])
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- child_view_node = next(node for node in viewspec.nodes if node.id == "child_1")
- assert child_view_node.parent_id == "ctrl_1"
- assert child_view_node.extent == "parent"
-
- controller_view_node = next(node for node in viewspec.nodes if node.id == "ctrl_1")
- assert controller_view_node.parent_id is None
-
- def test_ui_classes_from_status(self) -> None:
- """Test that UI classes are built from node status."""
- nodes = [
- {"node_id": "succeeded_1", "kind": NodeKind.OPERATOR, "status": NodeStatus.SUCCEEDED},
- {"node_id": "failed_1", "kind": NodeKind.OPERATOR, "status": NodeStatus.FAILED},
- {"node_id": "running_1", "kind": NodeKind.OPERATOR, "status": NodeStatus.RUNNING},
- ]
- graph = self._make_graph(nodes=nodes)
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- succeeded_node = next(node for node in viewspec.nodes if node.id == "succeeded_1")
- assert "ok" in succeeded_node.ui["classes"]
- assert "succeeded" in succeeded_node.ui["classes"]
-
- failed_node = next(node for node in viewspec.nodes if node.id == "failed_1")
- assert "failed" in failed_node.ui["classes"]
- assert "error" in failed_node.ui["classes"]
-
- running_node = next(node for node in viewspec.nodes if node.id == "running_1")
- assert "running" in running_node.ui["classes"]
-
- def test_ui_badges_from_timing_and_metrics(self) -> None:
- """Test that UI badges are built from timing and metrics."""
- node = {
- "node_id": "node_1",
- "kind": NodeKind.OPERATOR,
- "pipe_code": "test_pipe",
- "status": NodeStatus.SUCCEEDED,
- "timing": TimingSpec(
- started_at=datetime(2024, 1, 15, 10, 30, 0, tzinfo=timezone.utc),
- ended_at=datetime(2024, 1, 15, 10, 30, 0, 132000, tzinfo=timezone.utc),
- ),
- "metrics": {"llm_tokens": 150.0, "cost_usd": 0.0015},
- }
- graph = self._make_graph(nodes=[node])
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- view_node = viewspec.nodes[0]
- assert "badges" in view_node.ui
- badges = view_node.ui["badges"]
- assert "0.13s" in badges
- assert "150 tokens" in badges
- assert "$0.0015" in badges
-
- def test_inspector_data_populated(self) -> None:
- """Test that inspector data is populated correctly."""
- node = {
- "node_id": "node_1",
- "kind": NodeKind.OPERATOR,
- "pipe_code": "extract_text",
- "pipe_type": "PipeLLM",
- "status": NodeStatus.SUCCEEDED,
- "timing": TimingSpec(
- started_at=datetime(2024, 1, 15, 10, 30, 0, tzinfo=timezone.utc),
- ended_at=datetime(2024, 1, 15, 10, 30, 5, tzinfo=timezone.utc),
- ),
- "node_io": NodeIOSpec(
- inputs=[IOSpec(name="input", concept="Text", preview="Hello", digest="digest_001")],
- outputs=[IOSpec(name="output", concept="Text", preview="World", digest="digest_002")],
- ),
- "tags": {"layer": "root"},
- "metrics": {"llm_tokens": 150.0},
- }
- graph = self._make_graph(nodes=[node])
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- view_node = viewspec.nodes[0]
- assert view_node.inspector["pipe_code"] == "extract_text"
- assert view_node.inspector["pipe_type"] == "PipeLLM"
- assert "timing" in view_node.inspector
- assert "started_at" in view_node.inspector["timing"]
- assert "ended_at" in view_node.inspector["timing"]
- assert "io_preview" in view_node.inspector
- assert len(view_node.inspector["io_preview"]["inputs"]) == 1
- assert len(view_node.inspector["io_preview"]["outputs"]) == 1
- assert view_node.inspector["tags"] == {"layer": "root"}
- assert view_node.inspector["metrics"] == {"llm_tokens": 150.0}
-
- def test_view_index_built(self) -> None:
- """Test that ViewIndex is built correctly."""
- nodes = [
- {"node_id": "node_1", "kind": NodeKind.OPERATOR, "pipe_code": "pipe_a", "status": NodeStatus.SUCCEEDED},
- {"node_id": "node_2", "kind": NodeKind.OPERATOR, "pipe_code": "pipe_b", "status": NodeStatus.FAILED},
- ]
- edges = [
- {"edge_id": "edge_1", "source": "node_1", "target": "node_2", "kind": EdgeKind.CONTROL},
- ]
- graph = self._make_graph(nodes=nodes, edges=edges)
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- assert viewspec.index is not None
- assert "node_1" in viewspec.index.edges_by_node
- assert "edge_1" in viewspec.index.edges_by_node["node_1"]
- assert "pipe_code:pipe_a" in viewspec.index.search
- assert "node_1" in viewspec.index.search["pipe_code:pipe_a"]
- assert "status:failed" in viewspec.index.search
- assert "node_2" in viewspec.index.search["status:failed"]
-
- def test_contains_edges_skipped(self) -> None:
- """Test that CONTAINS edges are skipped (handled via parent_id)."""
- controller_node = {
- "node_id": "ctrl_1",
- "kind": NodeKind.CONTROLLER,
- "pipe_code": "main_sequence",
- "status": NodeStatus.SUCCEEDED,
- }
- child_node = {
- "node_id": "child_1",
- "kind": NodeKind.OPERATOR,
- "pipe_code": "step_a",
- "status": NodeStatus.SUCCEEDED,
- }
- contains_edge = {
- "edge_id": "edge_contains",
- "source": "ctrl_1",
- "target": "child_1",
- "kind": EdgeKind.CONTAINS,
- }
- control_edge = {
- "edge_id": "edge_control",
- "source": "child_1",
- "target": "node_2",
- "kind": EdgeKind.CONTROL,
- }
- other_node = {
- "node_id": "node_2",
- "kind": NodeKind.OPERATOR,
- "pipe_code": "step_b",
- "status": NodeStatus.SUCCEEDED,
- }
- graph = self._make_graph(nodes=[controller_node, child_node, other_node], edges=[contains_edge, control_edge])
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- # CONTAINS edge should not be in ViewEdges
- contains_edge_ids = [edge.id for edge in viewspec.edges if edge.kind == EdgeKind.CONTAINS]
- assert len(contains_edge_ids) == 0
-
- # CONTROL edge should be present
- control_edge_ids = [edge.id for edge in viewspec.edges if edge.kind == EdgeKind.CONTROL]
- assert "edge_control" in control_edge_ids
-
- def test_show_data_edges_option(self) -> None:
- """Test that show_data_edges option filters DATA edges."""
- nodes = [
- {"node_id": "node_1", "kind": NodeKind.OPERATOR, "status": NodeStatus.SUCCEEDED},
- {"node_id": "node_2", "kind": NodeKind.OPERATOR, "status": NodeStatus.SUCCEEDED},
- ]
- edges = [
- {"edge_id": "edge_data", "source": "node_1", "target": "node_2", "kind": EdgeKind.DATA},
- {"edge_id": "edge_control", "source": "node_1", "target": "node_2", "kind": EdgeKind.CONTROL},
- ]
- graph = self._make_graph(nodes=nodes, edges=edges)
- analysis = GraphAnalysis.from_graphspec(graph)
-
- # With show_data_edges=True (default)
- viewspec_with_data = graphspec_to_viewspec(graph, analysis, options={"show_data_edges": True})
- assert len(viewspec_with_data.edges) == 2
-
- # With show_data_edges=False
- viewspec_without_data = graphspec_to_viewspec(graph, analysis, options={"show_data_edges": False})
- assert len(viewspec_without_data.edges) == 1
- assert viewspec_without_data.edges[0].kind == EdgeKind.CONTROL
-
- def test_custom_layout_spec(self) -> None:
- """Test that custom LayoutSpec is used."""
- node = {
- "node_id": "node_1",
- "kind": NodeKind.OPERATOR,
- "status": NodeStatus.SUCCEEDED,
- }
- graph = self._make_graph(nodes=[node])
- analysis = GraphAnalysis.from_graphspec(graph)
-
- custom_layout = LayoutSpec(direction=FlowchartDirection.LEFT_TO_RIGHT, nodesep=100, ranksep=150)
- viewspec = graphspec_to_viewspec(graph, analysis, layout=custom_layout)
-
- assert viewspec.layout.direction == FlowchartDirection.LEFT_TO_RIGHT
- assert viewspec.layout.nodesep == 100
- assert viewspec.layout.ranksep == 150
-
- def test_source_metadata_populated(self) -> None:
- """Test that source metadata is populated from GraphSpec."""
- graph = GraphSpec(
- graph_id=self.GRAPH_ID,
- created_at=self.CREATED_AT,
- pipeline_ref=PipelineRef(domain="test_domain", main_pipe="test_main_pipe"),
- nodes=[],
- edges=[],
- )
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- assert viewspec.source["producer"] == f"pipelex {get_package_version()}"
- assert viewspec.source["domain"] == "test_domain"
- assert viewspec.source["main_pipe"] == "test_main_pipe"
-
- def test_node_label_from_pipe_code(self) -> None:
- """Test that node label uses pipe_code when available."""
- node_with_code = {
- "node_id": "node_1",
- "kind": NodeKind.OPERATOR,
- "pipe_code": "extract_text",
- "status": NodeStatus.SUCCEEDED,
- }
- node_without_code = {
- "node_id": "node_2",
- "kind": NodeKind.OPERATOR,
- "pipe_type": "PipeLLM",
- "status": NodeStatus.SUCCEEDED,
- }
- node_with_nothing = {
- "node_id": "node_3",
- "kind": NodeKind.OPERATOR,
- "status": NodeStatus.SUCCEEDED,
- }
- graph = self._make_graph(nodes=[node_with_code, node_without_code, node_with_nothing])
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- node1 = next(node for node in viewspec.nodes if node.id == "node_1")
- assert node1.label == "extract_text"
-
- node2 = next(node for node in viewspec.nodes if node.id == "node_2")
- assert node2.label == "PipeLLM"
-
- node3 = next(node for node in viewspec.nodes if node.id == "node_3")
- assert node3.label == "node_3"
-
- def test_error_in_inspector(self) -> None:
- """Test that error information is included in inspector."""
- node = {
- "node_id": "node_1",
- "kind": NodeKind.OPERATOR,
- "pipe_code": "failed_pipe",
- "status": NodeStatus.FAILED,
- "error": ErrorSpec(error_type="PipeRunError", message="LLM generation failed", stack="Traceback..."),
- }
- graph = self._make_graph(nodes=[node])
- analysis = GraphAnalysis.from_graphspec(graph)
- viewspec = graphspec_to_viewspec(graph, analysis)
-
- view_node = viewspec.nodes[0]
- assert "error" in view_node.inspector
- assert view_node.inspector["error"]["error_type"] == "PipeRunError"
- assert view_node.inspector["error"]["message"] == "LLM generation failed"
- assert view_node.inspector["error"]["stack"] == "Traceback..."
diff --git a/uv.lock b/uv.lock
index 07a11acf6..aeb0b8178 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3420,7 +3420,7 @@ wheels = [
[[package]]
name = "pipelex"
-version = "0.20.12"
+version = "0.20.13"
source = { editable = "." }
dependencies = [
{ name = "aiofiles" },