workflow-graph-shared 1.2.11

Core types and YAML parser for workflow-graph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
pub mod yaml;

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

/// Direction of a port on a node.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PortDirection {
    Input,
    Output,
}

/// A typed input or output port on a node.
/// Ports define connection points — edges connect from an output port to an input port.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Port {
    /// Unique identifier within the node (e.g., "message", "response").
    pub id: String,
    /// Display label.
    pub label: String,
    /// Whether this is an input or output port.
    pub direction: PortDirection,
    /// Type tag for connection compatibility (e.g., "text", "json", "tool_call").
    /// Only ports with matching types can be connected.
    #[serde(default)]
    pub port_type: String,
    /// Optional color override for the port dot.
    #[serde(default)]
    pub color: Option<String>,
}

/// Type of inline field rendered inside a node body.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FieldType {
    Text,
    Textarea,
    Select,
    Toggle,
    Badge,
    Slider,
}

/// Definition of an inline field rendered inside a node.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FieldDef {
    /// Key used to read/write the field value in `Job.metadata`.
    pub key: String,
    /// What kind of control to render.
    pub field_type: FieldType,
    /// Display label.
    pub label: String,
    /// Available options (for `Select` fields).
    #[serde(default)]
    pub options: Vec<String>,
    /// Default value (serialized as JSON).
    #[serde(default)]
    pub default_value: Option<serde_json::Value>,
    /// Minimum value (for `Slider` fields).
    #[serde(default)]
    pub min: Option<f64>,
    /// Maximum value (for `Slider` fields).
    #[serde(default)]
    pub max: Option<f64>,
}

/// Declarative definition of a node type.
///
/// Registered via `WorkflowGraph.registerNodeType()`. The renderer uses this
/// to draw colored headers, inline fields, and type-specific visuals.
/// Consumers can define any number of custom node types.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NodeDefinition {
    /// Unique type key (e.g., "agent", "tool", "my-custom-node").
    /// Matched against `Job.metadata["node_type"]`.
    pub node_type: String,
    /// Display label shown in the header bar.
    pub label: String,
    /// Icon character (emoji or Unicode) rendered in the header.
    #[serde(default)]
    pub icon: String,
    /// Hex color for the header bar (e.g., "#3b82f6").
    #[serde(default)]
    pub header_color: String,
    /// Category for grouping in palettes (consumer-defined, no constraints).
    #[serde(default)]
    pub category: String,
    /// Inline fields rendered in the node body.
    #[serde(default)]
    pub fields: Vec<FieldDef>,
    /// Default input ports for this node type.
    #[serde(default)]
    pub inputs: Vec<Port>,
    /// Default output ports for this node type.
    #[serde(default)]
    pub outputs: Vec<Port>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum JobStatus {
    Queued,
    Running,
    Success,
    Failure,
    Skipped,
    Cancelled,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Job {
    pub id: String,
    pub name: String,
    pub status: JobStatus,
    pub command: String,
    pub duration_secs: Option<u64>,
    /// Epoch milliseconds when the job started running (for live timer).
    #[serde(default)]
    pub started_at: Option<f64>,
    pub depends_on: Vec<String>,
    pub output: Option<String>,
    /// Worker labels required to execute this job.
    #[serde(default)]
    pub required_labels: Vec<String>,
    /// Maximum number of retries on failure.
    #[serde(default)]
    pub max_retries: u32,
    /// Current attempt number (0-indexed).
    #[serde(default)]
    pub attempt: u32,
    /// Arbitrary metadata for custom renderers (e.g., node_type, icon, color).
    #[serde(default)]
    pub metadata: HashMap<String, serde_json::Value>,
    /// Input and output ports for node-graph-style connections.
    #[serde(default)]
    pub ports: Vec<Port>,
    /// If this is a compound node (node group), contains the child nodes.
    /// When collapsed, renders as a single node with aggregated ports.
    /// When expanded, renders children with a dashed border.
    #[serde(default)]
    pub children: Option<Vec<Job>>,
    /// Whether this compound node is collapsed (shows as single node).
    #[serde(default)]
    pub collapsed: bool,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Workflow {
    pub id: String,
    pub name: String,
    pub trigger: String,
    pub jobs: Vec<Job>,
}

impl Workflow {
    /// Returns a sample workflow matching the GitHub Actions screenshot.
    pub fn sample() -> Self {
        Workflow {
            id: "ci-1".into(),
            name: "ci.yml".into(),
            trigger: "on: push".into(),
            jobs: vec![
                Job {
                    id: "unit-tests".into(),
                    name: "Unit Tests".into(),
                    status: JobStatus::Queued,
                    command: "echo 'Running unit tests' && sleep 2".into(),
                    duration_secs: None,
                    depends_on: vec![],
                    started_at: None,
                    output: None,
                    required_labels: vec![],
                    max_retries: 0,
                    attempt: 0,
                    metadata: HashMap::new(),
                    ports: vec![],
                    children: None,
                    collapsed: false,
                },
                Job {
                    id: "lint".into(),
                    name: "Lint".into(),
                    status: JobStatus::Queued,
                    command: "echo 'Running linter' && sleep 1".into(),
                    duration_secs: None,
                    depends_on: vec![],
                    started_at: None,
                    output: None,
                    required_labels: vec![],
                    max_retries: 0,
                    attempt: 0,
                    metadata: HashMap::new(),
                    ports: vec![],
                    children: None,
                    collapsed: false,
                },
                Job {
                    id: "typecheck".into(),
                    name: "Typecheck".into(),
                    status: JobStatus::Queued,
                    command: "echo 'Running typecheck' && sleep 2".into(),
                    duration_secs: None,
                    depends_on: vec![],
                    started_at: None,
                    output: None,
                    required_labels: vec![],
                    max_retries: 0,
                    attempt: 0,
                    metadata: HashMap::new(),
                    ports: vec![],
                    children: None,
                    collapsed: false,
                },
                Job {
                    id: "build".into(),
                    name: "Build".into(),
                    status: JobStatus::Queued,
                    command: "echo 'Building project' && sleep 3".into(),
                    duration_secs: None,
                    depends_on: vec!["unit-tests".into(), "lint".into(), "typecheck".into()],
                    started_at: None,
                    output: None,
                    required_labels: vec![],
                    max_retries: 0,
                    attempt: 0,
                    metadata: HashMap::new(),
                    ports: vec![],
                    children: None,
                    collapsed: false,
                },
                Job {
                    id: "deploy-db".into(),
                    name: "Deploy DB Migrations".into(),
                    status: JobStatus::Queued,
                    command: "echo 'Deploying DB migrations' && sleep 1".into(),
                    duration_secs: None,
                    depends_on: vec!["build".into()],
                    started_at: None,
                    output: None,
                    required_labels: vec![],
                    max_retries: 0,
                    attempt: 0,
                    metadata: HashMap::new(),
                    ports: vec![],
                    children: None,
                    collapsed: false,
                },
                Job {
                    id: "e2e-tests".into(),
                    name: "E2E Tests".into(),
                    status: JobStatus::Queued,
                    command: "echo 'Running E2E tests' && sleep 5".into(),
                    duration_secs: None,
                    depends_on: vec!["build".into()],
                    started_at: None,
                    output: None,
                    required_labels: vec![],
                    max_retries: 0,
                    attempt: 0,
                    metadata: HashMap::new(),
                    ports: vec![],
                    children: None,
                    collapsed: false,
                },
                Job {
                    id: "deploy-preview".into(),
                    name: "Deploy Preview".into(),
                    status: JobStatus::Queued,
                    command: "echo 'Deploying preview' && sleep 1".into(),
                    duration_secs: None,
                    depends_on: vec!["build".into()],
                    started_at: None,
                    output: None,
                    required_labels: vec![],
                    max_retries: 0,
                    attempt: 0,
                    metadata: HashMap::new(),
                    ports: vec![],
                    children: None,
                    collapsed: false,
                },
                Job {
                    id: "deploy-web".into(),
                    name: "Deploy Web".into(),
                    status: JobStatus::Queued,
                    command: "echo 'Deploying to production' && sleep 3".into(),
                    duration_secs: None,
                    depends_on: vec!["deploy-db".into()],
                    started_at: None,
                    output: None,
                    required_labels: vec![],
                    max_retries: 0,
                    attempt: 0,
                    metadata: HashMap::new(),
                    ports: vec![],
                    children: None,
                    collapsed: false,
                },
            ],
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_job(id: &str, metadata: HashMap<String, serde_json::Value>) -> Job {
        Job {
            id: id.into(),
            name: id.into(),
            status: JobStatus::Queued,
            command: "echo test".into(),
            duration_secs: None,
            started_at: None,
            depends_on: vec![],
            output: None,
            required_labels: vec![],
            max_retries: 0,
            attempt: 0,
            metadata,
            ports: vec![],
            children: None,
            collapsed: false,
        }
    }

    #[test]
    fn job_metadata_serializes_roundtrip() {
        let mut meta = HashMap::new();
        meta.insert("node_type".into(), serde_json::json!("deploy"));
        meta.insert("icon".into(), serde_json::json!("rocket"));
        meta.insert("priority".into(), serde_json::json!(42));

        let job = make_job("deploy-1", meta);
        let json = serde_json::to_string(&job).unwrap();
        let deserialized: Job = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.metadata.len(), 3);
        assert_eq!(
            deserialized.metadata["node_type"],
            serde_json::json!("deploy")
        );
        assert_eq!(deserialized.metadata["icon"], serde_json::json!("rocket"));
        assert_eq!(deserialized.metadata["priority"], serde_json::json!(42));
    }

    #[test]
    fn job_metadata_defaults_to_empty() {
        let json = r#"{
            "id": "test",
            "name": "Test",
            "status": "queued",
            "command": "echo hi",
            "depends_on": []
        }"#;
        let job: Job = serde_json::from_str(json).unwrap();
        assert!(job.metadata.is_empty());
    }

    #[test]
    fn job_metadata_with_nested_values() {
        let mut meta = HashMap::new();
        meta.insert(
            "config".into(),
            serde_json::json!({"timeout": 30, "retries": true}),
        );
        meta.insert("tags".into(), serde_json::json!(["ci", "deploy"]));

        let job = make_job("complex", meta);
        let json = serde_json::to_string(&job).unwrap();
        let deserialized: Job = serde_json::from_str(&json).unwrap();

        assert_eq!(
            deserialized.metadata["config"],
            serde_json::json!({"timeout": 30, "retries": true})
        );
        assert_eq!(
            deserialized.metadata["tags"],
            serde_json::json!(["ci", "deploy"])
        );
    }

    #[test]
    fn job_metadata_from_json_string() {
        let json = r##"{
            "id": "styled",
            "name": "Styled Node",
            "status": "running",
            "command": "echo hi",
            "depends_on": [],
            "metadata": {
                "color": "#ff0000",
                "weight": 1.5,
                "visible": true
            }
        }"##;
        let job: Job = serde_json::from_str(json).unwrap();
        assert_eq!(job.metadata.len(), 3);
        assert_eq!(job.metadata["color"], serde_json::json!("#ff0000"));
        assert_eq!(job.metadata["weight"], serde_json::json!(1.5));
        assert_eq!(job.metadata["visible"], serde_json::json!(true));
    }

    #[test]
    fn workflow_sample_has_empty_metadata() {
        let wf = Workflow::sample();
        for job in &wf.jobs {
            assert!(
                job.metadata.is_empty(),
                "Expected empty metadata for job '{}'",
                job.id
            );
        }
    }
}